Compare commits
41 Commits
Author | SHA1 | Date | |
---|---|---|---|
93ea037230 | |||
3f592988a9 | |||
96f490f84a | |||
37603735bd | |||
af40048841 | |||
3435c67e68 | |||
ecb9e4f57d | |||
dd61e8d19d | |||
eae06a4a7d | |||
0822b526d5 | |||
95e9ae2d8d | |||
29cf3ca0ef | |||
36716ca695 | |||
2334bafe68 | |||
bd4302e096 | |||
d8a1d88ded | |||
c427bc89ef | |||
4d7096f451 | |||
4525707048 | |||
b8267a69f6 | |||
ad53b42a68 | |||
93e0dbdc78 | |||
3e4bc9f85c | |||
8e10e67b89 | |||
3b0cc8548c | |||
e48ccdd4c8 | |||
e103040158 | |||
1948ea11ef | |||
6d375ac37e | |||
82a8c03953 | |||
207371aeae | |||
52cfa94652 | |||
65f4a35e7f | |||
e5284cf647 | |||
0a3595414e | |||
f4326daaa4 | |||
710cd5aed2 | |||
521a190b0f | |||
e22ff74e79 | |||
2c82a2bfc8 | |||
461e0a6873 |
33
.github/workflows/go.yml
vendored
33
.github/workflows/go.yml
vendored
@ -6,16 +6,39 @@ jobs:
|
|||||||
name: Build
|
name: Build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
- name: Setup Go
|
||||||
- name: Set up Go 1.13
|
|
||||||
uses: actions/setup-go@v1
|
uses: actions/setup-go@v1
|
||||||
with:
|
with:
|
||||||
go-version: 1.13
|
go-version: 1.13.x
|
||||||
id: go
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
- name: Check out code into the Go module directory
|
||||||
uses: actions/checkout@v1
|
uses: actions/checkout@v1
|
||||||
|
|
||||||
- name: Get dependencies
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v1
|
||||||
|
with:
|
||||||
|
path: ~/go/pkg/mod
|
||||||
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-go-
|
||||||
|
|
||||||
|
- name: Get dependencies and run test
|
||||||
run: |
|
run: |
|
||||||
go test ./...
|
go test ./...
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
env:
|
||||||
|
NAME: clash
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j releases
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
with:
|
||||||
|
files: bin/*
|
||||||
|
draft: true
|
||||||
|
prerelease: true
|
||||||
|
26
.travis.yml
26
.travis.yml
@ -1,26 +0,0 @@
|
|||||||
language: go
|
|
||||||
sudo: false
|
|
||||||
go:
|
|
||||||
- '1.13'
|
|
||||||
install:
|
|
||||||
- "go mod download"
|
|
||||||
env:
|
|
||||||
global:
|
|
||||||
- NAME=clash
|
|
||||||
- BINDIR=bin
|
|
||||||
- GO111MODULE=on
|
|
||||||
script:
|
|
||||||
- go test ./...
|
|
||||||
before_deploy: make -j releases
|
|
||||||
deploy:
|
|
||||||
provider: releases
|
|
||||||
prerelease: true
|
|
||||||
skip_cleanup: true
|
|
||||||
api_key:
|
|
||||||
secure: dp1tc1h0er7aaAZ1hY0Xk/cUKwB0ifsAjg6e0M/Ad5NC87oucP6ESNFkDu0e9rUS1yB826/VnVGzNE/Z5zdjXVzPft+g5v5oRxzI4BKLhf07t9s+x8Z+3sApTxdsC5BvcN9x+5yRbpDLQ3biDPxSFu86j7m2pkEWw6XYNZO3/5y+RZXX7zu+d4MzTLUaA2kWl7KQAP0tEJNuw9ACDhpkw7LYbU/8q3E76prOTeme5/AT6Gxj7XhKUNP27lazhhqBSWM14ybPANqojNLEfMFHN/Eu2phYO07MuLTd4zuOIuw9y65kgvTFcHRlORjwUhnviXyA69obQejjgDI1WDOtU4PqpFaSLrxWtKI6k5VNWHARYggDm/wKl0WG7F0Kgio1KiGGhDg2yrbseXr/zBNaDhBtTFh6XJffqqwmgby1PXB6PWwfvWXooJMaQiFZczLWeMBl8v6XbSN6jtMTh/PQlKai6BcDd4LM8GQ7VHpSeff4qXEU4Vpnadjgs8VDPOHng6/HV+wDs8q2LrlMbnxLWxbCjOMUB6w7YnSrwH9owzKSoUs/531I4tTCRQIgipJtTK2b881/8osVjdMGS1mDXhBWO+OM0LCAdORJz+kN4PIkXXvKLt6jX74k6z4M3swFaqqtlTduN2Yy/ErsjguQO1VZfHmcpNssmJXI5QB9sxA=
|
|
||||||
file: bin/*
|
|
||||||
file_glob: true
|
|
||||||
on:
|
|
||||||
repo: Dreamacro/clash
|
|
||||||
branch: master
|
|
||||||
tags: true
|
|
687
LICENSE
687
LICENSE
@ -1,21 +1,674 @@
|
|||||||
MIT License
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
Copyright (c) 2018 Dreamacro
|
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.
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Preamble
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
The GNU General Public License is a free, copyleft license for
|
||||||
copies or substantial portions of the Software.
|
software and other kinds of works.
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
The licenses for most software and other practical works are designed
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
to take away your freedom to share and change the works. By contrast,
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
share and change all versions of a program--to make sure it remains free
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
GNU General Public License for most of our software; it applies also to
|
||||||
SOFTWARE.
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
|
23
README.md
23
README.md
@ -6,9 +6,8 @@
|
|||||||
<h4 align="center">A rule-based tunnel in Go.</h4>
|
<h4 align="center">A rule-based tunnel in Go.</h4>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://travis-ci.org/Dreamacro/clash">
|
<a href="https://github.com/Dreamacro/clash/actions">
|
||||||
<img src="https://img.shields.io/travis/Dreamacro/clash.svg?style=flat-square"
|
<img src="https://img.shields.io/github/workflow/status/Dreamacro/clash/Go?style=flat-square" alt="Github Actions">
|
||||||
alt="Travis-CI">
|
|
||||||
</a>
|
</a>
|
||||||
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
||||||
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?style=flat-square">
|
||||||
@ -21,7 +20,6 @@
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Local HTTP/HTTPS/SOCKS server
|
- Local HTTP/HTTPS/SOCKS server
|
||||||
- Surge-like configuration format
|
|
||||||
- GeoIP rule support
|
- GeoIP rule support
|
||||||
- Supports Vmess, Shadowsocks, Snell and SOCKS5 protocol
|
- Supports Vmess, Shadowsocks, Snell and SOCKS5 protocol
|
||||||
- Supports Netfilter TCP redirecting
|
- Supports Netfilter TCP redirecting
|
||||||
@ -74,7 +72,7 @@ $ clash -d .
|
|||||||
```
|
```
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>This is an example configuration file</summary>
|
<summary>This is an example configuration file (click to expand)</summary>
|
||||||
|
|
||||||
```yml
|
```yml
|
||||||
# port of HTTP
|
# port of HTTP
|
||||||
@ -132,6 +130,9 @@ experimental:
|
|||||||
# listen: 0.0.0.0:53
|
# listen: 0.0.0.0:53
|
||||||
# enhanced-mode: redir-host # or fake-ip
|
# enhanced-mode: redir-host # or fake-ip
|
||||||
# # fake-ip-range: 198.18.0.1/16 # if you don't know what it is, don't change it
|
# # fake-ip-range: 198.18.0.1/16 # if you don't know what it is, don't change it
|
||||||
|
# fake-ip-filter: # fake ip white domain list
|
||||||
|
# - *.lan
|
||||||
|
# - localhost.ptlogin2.qq.com
|
||||||
# nameserver:
|
# nameserver:
|
||||||
# - 114.114.114.114
|
# - 114.114.114.114
|
||||||
# - tls://dns.rubyfish.cn:853 # dns over tls
|
# - tls://dns.rubyfish.cn:853 # dns over tls
|
||||||
@ -144,13 +145,12 @@ experimental:
|
|||||||
# - 240.0.0.0/4
|
# - 240.0.0.0/4
|
||||||
|
|
||||||
Proxy:
|
Proxy:
|
||||||
|
|
||||||
# shadowsocks
|
# shadowsocks
|
||||||
# The supported ciphers(encrypt methods):
|
# The supported ciphers(encrypt methods):
|
||||||
# aes-128-gcm aes-192-gcm aes-256-gcm
|
# aes-128-gcm aes-192-gcm aes-256-gcm
|
||||||
# aes-128-cfb aes-192-cfb aes-256-cfb
|
# aes-128-cfb aes-192-cfb aes-256-cfb
|
||||||
# aes-128-ctr aes-192-ctr aes-256-ctr
|
# aes-128-ctr aes-192-ctr aes-256-ctr
|
||||||
# rc4-md5 chacha20 chacha20-ietf xchacha20
|
# rc4-md5 chacha20-ietf xchacha20
|
||||||
# chacha20-ietf-poly1305 xchacha20-ietf-poly1305
|
# chacha20-ietf-poly1305 xchacha20-ietf-poly1305
|
||||||
- name: "ss1"
|
- name: "ss1"
|
||||||
type: ss
|
type: ss
|
||||||
@ -283,9 +283,10 @@ Rule:
|
|||||||
- DOMAIN-KEYWORD,google,auto
|
- DOMAIN-KEYWORD,google,auto
|
||||||
- DOMAIN,google.com,auto
|
- DOMAIN,google.com,auto
|
||||||
- DOMAIN-SUFFIX,ad.com,REJECT
|
- DOMAIN-SUFFIX,ad.com,REJECT
|
||||||
- IP-CIDR,127.0.0.0/8,DIRECT
|
|
||||||
# rename SOURCE-IP-CIDR and would remove after prerelease
|
# rename SOURCE-IP-CIDR and would remove after prerelease
|
||||||
- SRC-IP-CIDR,192.168.1.201/32,DIRECT
|
- SRC-IP-CIDR,192.168.1.201/32,DIRECT
|
||||||
|
# optional param "no-resolve" for IP rules (GEOIP IP-CIDR)
|
||||||
|
- IP-CIDR,127.0.0.0/8,DIRECT
|
||||||
- GEOIP,CN,DIRECT
|
- GEOIP,CN,DIRECT
|
||||||
- DST-PORT,80,DIRECT
|
- DST-PORT,80,DIRECT
|
||||||
- SRC-PORT,7777,DIRECT
|
- SRC-PORT,7777,DIRECT
|
||||||
@ -295,6 +296,9 @@ Rule:
|
|||||||
```
|
```
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
## Advanced
|
||||||
|
[Provider](https://github.com/Dreamacro/clash/wiki/Provider)
|
||||||
|
|
||||||
## Documentations
|
## Documentations
|
||||||
https://clash.gitbook.io/
|
https://clash.gitbook.io/
|
||||||
|
|
||||||
@ -313,4 +317,5 @@ https://clash.gitbook.io/
|
|||||||
- [x] Complementing the necessary rule operators
|
- [x] Complementing the necessary rule operators
|
||||||
- [x] Redir proxy
|
- [x] Redir proxy
|
||||||
- [x] UDP support
|
- [x] UDP support
|
||||||
- [ ] Connection manager
|
- [x] Connection manager
|
||||||
|
- [ ] Event API
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
@ -23,6 +23,7 @@ func (h *HTTPAdapter) Metadata() *C.Metadata {
|
|||||||
// NewHTTP is HTTPAdapter generator
|
// NewHTTP is HTTPAdapter generator
|
||||||
func NewHTTP(request *http.Request, conn net.Conn) *HTTPAdapter {
|
func NewHTTP(request *http.Request, conn net.Conn) *HTTPAdapter {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
|
metadata.Type = C.HTTP
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
|
@ -1,13 +1,16 @@
|
|||||||
package adapters
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTPS is HTTPAdapter generator
|
// NewHTTPS is HTTPAdapter generator
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn) *SocketAdapter {
|
func NewHTTPS(request *http.Request, conn net.Conn) *SocketAdapter {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
|
metadata.Type = C.HTTPCONNECT
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
|
33
adapters/inbound/packet.go
Normal file
33
adapters/inbound/packet.go
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/Dreamacro/clash/component/socks5"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
||||||
|
type PacketAdapter struct {
|
||||||
|
C.UDPPacket
|
||||||
|
metadata *C.Metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metadata returns destination metadata
|
||||||
|
func (s *PacketAdapter) Metadata() *C.Metadata {
|
||||||
|
return s.metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPacket is PacketAdapter generator
|
||||||
|
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, netType C.NetWork) *PacketAdapter {
|
||||||
|
metadata := parseSocksAddr(target)
|
||||||
|
metadata.NetWork = netType
|
||||||
|
metadata.Type = source
|
||||||
|
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
||||||
|
metadata.SrcIP = ip
|
||||||
|
metadata.SrcPort = port
|
||||||
|
}
|
||||||
|
|
||||||
|
return &PacketAdapter{
|
||||||
|
UDPPacket: packet,
|
||||||
|
metadata: metadata,
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
@ -20,11 +20,11 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
|||||||
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||||
case socks5.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
ip := net.IP(target[1 : 1+net.IPv4len])
|
ip := net.IP(target[1 : 1+net.IPv4len])
|
||||||
metadata.DstIP = &ip
|
metadata.DstIP = ip
|
||||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||||
case socks5.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
ip := net.IP(target[1 : 1+net.IPv6len])
|
ip := net.IP(target[1 : 1+net.IPv6len])
|
||||||
metadata.DstIP = &ip
|
metadata.DstIP = ip
|
||||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -40,7 +40,6 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{
|
||||||
NetWork: C.TCP,
|
NetWork: C.TCP,
|
||||||
Type: C.HTTP,
|
|
||||||
AddrType: C.AtypDomainName,
|
AddrType: C.AtypDomainName,
|
||||||
Host: host,
|
Host: host,
|
||||||
DstIP: nil,
|
DstIP: nil,
|
||||||
@ -55,18 +54,18 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
default:
|
default:
|
||||||
metadata.AddrType = C.AtypIPv4
|
metadata.AddrType = C.AtypIPv4
|
||||||
}
|
}
|
||||||
metadata.DstIP = &ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAddr(addr string) (*net.IP, string, error) {
|
func parseAddr(addr string) (net.IP, string, error) {
|
||||||
host, port, err := net.SplitHostPort(addr)
|
host, port, err := net.SplitHostPort(addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", err
|
return nil, "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := net.ParseIP(host)
|
ip := net.ParseIP(host)
|
||||||
return &ip, port, nil
|
return ip, port, nil
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@ -38,14 +38,16 @@ func (b *Base) SupportUDP() bool {
|
|||||||
return b.udp
|
return b.udp
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Base) Destroy() {}
|
|
||||||
|
|
||||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]string{
|
return json.Marshal(map[string]string{
|
||||||
"type": b.Type().String(),
|
"type": b.Type().String(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewBase(name string, tp C.AdapterType, udp bool) *Base {
|
||||||
|
return &Base{name, tp, udp}
|
||||||
|
}
|
||||||
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
@ -140,6 +142,7 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
mapping := map[string]interface{}{}
|
mapping := map[string]interface{}{}
|
||||||
json.Unmarshal(inner, &mapping)
|
json.Unmarshal(inner, &mapping)
|
||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
|
mapping["name"] = p.Name()
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -199,9 +202,3 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||||
return &Proxy{adapter, queue.New(10), true}
|
return &Proxy{adapter, queue.New(10), true}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyGroupOption contain the common options for all kind of ProxyGroup
|
|
||||||
type ProxyGroupOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
}
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
@ -1,134 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Fallback struct {
|
|
||||||
*Base
|
|
||||||
proxies []C.Proxy
|
|
||||||
rawURL string
|
|
||||||
interval time.Duration
|
|
||||||
done chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
type FallbackOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
URL string `proxy:"url"`
|
|
||||||
Interval int `proxy:"interval"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
return proxy.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
c, err := proxy.DialContext(ctx, metadata)
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(f)
|
|
||||||
}
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
pc, addr, err := proxy.DialUDP(metadata)
|
|
||||||
if err == nil {
|
|
||||||
pc.AppendToChains(f)
|
|
||||||
}
|
|
||||||
return pc, addr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) SupportUDP() bool {
|
|
||||||
proxy := f.findAliveProxy()
|
|
||||||
return proxy.SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for _, proxy := range f.proxies {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": f.Type().String(),
|
|
||||||
"now": f.Now(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) Destroy() {
|
|
||||||
f.done <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) loop() {
|
|
||||||
tick := time.NewTicker(f.interval)
|
|
||||||
go f.validTest()
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-tick.C:
|
|
||||||
go f.validTest()
|
|
||||||
case <-f.done:
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) findAliveProxy() C.Proxy {
|
|
||||||
for _, proxy := range f.proxies {
|
|
||||||
if proxy.Alive() {
|
|
||||||
return proxy
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return f.proxies[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) validTest() {
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
wg.Add(len(f.proxies))
|
|
||||||
|
|
||||||
for _, p := range f.proxies {
|
|
||||||
go func(p C.Proxy) {
|
|
||||||
p.URLTest(context.Background(), f.rawURL)
|
|
||||||
wg.Done()
|
|
||||||
}(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFallback(option FallbackOption, proxies []C.Proxy) (*Fallback, error) {
|
|
||||||
_, err := urlToMetadata(option.URL)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(proxies) < 1 {
|
|
||||||
return nil, errors.New("The number of proxies cannot be 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
|
||||||
|
|
||||||
Fallback := &Fallback{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.Fallback,
|
|
||||||
},
|
|
||||||
proxies: proxies,
|
|
||||||
rawURL: option.URL,
|
|
||||||
interval: interval,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
|
||||||
go Fallback.loop()
|
|
||||||
return Fallback, nil
|
|
||||||
}
|
|
@ -1,8 +1,7 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
@ -11,6 +10,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -21,8 +21,6 @@ type Http struct {
|
|||||||
addr string
|
addr string
|
||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tls bool
|
|
||||||
skipCertVerify bool
|
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,14 +36,14 @@ type HttpOption struct {
|
|||||||
|
|
||||||
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
c, err := dialContext(ctx, "tcp", h.addr)
|
c, err := dialContext(ctx, "tcp", h.addr)
|
||||||
if err == nil && h.tls {
|
if err == nil && h.tlsConfig != nil {
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
err = cc.Handshake()
|
err = cc.Handshake()
|
||||||
c = cc
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error", h.addr)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
if err := h.shakeHand(metadata, c); err != nil {
|
if err := h.shakeHand(metadata, c); err != nil {
|
||||||
@ -56,28 +54,28 @@ func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
||||||
var buf bytes.Buffer
|
|
||||||
var err error
|
|
||||||
|
|
||||||
addr := metadata.RemoteAddress()
|
addr := metadata.RemoteAddress()
|
||||||
buf.WriteString("CONNECT " + addr + " HTTP/1.1\r\n")
|
req := &http.Request{
|
||||||
buf.WriteString("Host: " + metadata.String() + "\r\n")
|
Method: http.MethodConnect,
|
||||||
buf.WriteString("Proxy-Connection: Keep-Alive\r\n")
|
URL: &url.URL{
|
||||||
|
Host: addr,
|
||||||
|
},
|
||||||
|
Host: addr,
|
||||||
|
Header: http.Header{
|
||||||
|
"Proxy-Connection": []string{"Keep-Alive"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
if h.user != "" && h.pass != "" {
|
if h.user != "" && h.pass != "" {
|
||||||
auth := h.user + ":" + h.pass
|
auth := h.user + ":" + h.pass
|
||||||
buf.WriteString("Proxy-Authorization: Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) + "\r\n")
|
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
||||||
}
|
}
|
||||||
// header ended
|
|
||||||
buf.WriteString("\r\n")
|
|
||||||
|
|
||||||
_, err = rw.Write(buf.Bytes())
|
if err := req.Write(rw); err != nil {
|
||||||
if err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
var req http.Request
|
resp, err := http.ReadResponse(bufio.NewReader(rw), req)
|
||||||
resp, err := http.ReadResponse(bufio.NewReader(rw), &req)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -97,6 +95,7 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
if resp.StatusCode >= http.StatusInternalServerError {
|
if resp.StatusCode >= http.StatusInternalServerError {
|
||||||
return errors.New(resp.Status)
|
return errors.New(resp.Status)
|
||||||
}
|
}
|
||||||
|
|
||||||
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -118,8 +117,6 @@ func NewHttp(option HttpOption) *Http {
|
|||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
|
||||||
skipCertVerify: option.SkipCertVerify,
|
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
64
adapters/outbound/parser.go
Normal file
64
adapters/outbound/parser.go
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ParseProxy(mapping map[string]interface{}) (C.Proxy, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
|
proxyType, existType := mapping["type"].(string)
|
||||||
|
if !existType {
|
||||||
|
return nil, fmt.Errorf("Missing type")
|
||||||
|
}
|
||||||
|
|
||||||
|
var proxy C.ProxyAdapter
|
||||||
|
err := fmt.Errorf("Cannot parse")
|
||||||
|
switch proxyType {
|
||||||
|
case "ss":
|
||||||
|
ssOption := &ShadowSocksOption{}
|
||||||
|
err = decoder.Decode(mapping, ssOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = NewShadowSocks(*ssOption)
|
||||||
|
case "socks5":
|
||||||
|
socksOption := &Socks5Option{}
|
||||||
|
err = decoder.Decode(mapping, socksOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = NewSocks5(*socksOption)
|
||||||
|
case "http":
|
||||||
|
httpOption := &HttpOption{}
|
||||||
|
err = decoder.Decode(mapping, httpOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = NewHttp(*httpOption)
|
||||||
|
case "vmess":
|
||||||
|
vmessOption := &VmessOption{}
|
||||||
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = NewVmess(*vmessOption)
|
||||||
|
case "snell":
|
||||||
|
snellOption := &SnellOption{}
|
||||||
|
err = decoder.Decode(mapping, snellOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = NewSnell(*snellOption)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("Unsupport proxy type: %s", proxyType)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewProxy(proxy), nil
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
@ -1,87 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Selector struct {
|
|
||||||
*Base
|
|
||||||
selected C.Proxy
|
|
||||||
proxies map[string]C.Proxy
|
|
||||||
proxyList []string
|
|
||||||
}
|
|
||||||
|
|
||||||
type SelectorOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
c, err := s.selected.DialContext(ctx, metadata)
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(s)
|
|
||||||
}
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
|
||||||
pc, addr, err := s.selected.DialUDP(metadata)
|
|
||||||
if err == nil {
|
|
||||||
pc.AppendToChains(s)
|
|
||||||
}
|
|
||||||
return pc, addr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) SupportUDP() bool {
|
|
||||||
return s.selected.SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": s.Type().String(),
|
|
||||||
"now": s.Now(),
|
|
||||||
"all": s.proxyList,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Now() string {
|
|
||||||
return s.selected.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Selector) Set(name string) error {
|
|
||||||
proxy, exist := s.proxies[name]
|
|
||||||
if !exist {
|
|
||||||
return errors.New("Proxy does not exist")
|
|
||||||
}
|
|
||||||
s.selected = proxy
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSelector(name string, proxies []C.Proxy) (*Selector, error) {
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, errors.New("Provide at least one proxy")
|
|
||||||
}
|
|
||||||
|
|
||||||
mapping := make(map[string]C.Proxy)
|
|
||||||
proxyList := make([]string, len(proxies))
|
|
||||||
for idx, proxy := range proxies {
|
|
||||||
mapping[proxy.Name()] = proxy
|
|
||||||
proxyList[idx] = proxy.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &Selector{
|
|
||||||
Base: &Base{
|
|
||||||
name: name,
|
|
||||||
tp: C.Selector,
|
|
||||||
},
|
|
||||||
proxies: mapping,
|
|
||||||
selected: proxies[0],
|
|
||||||
proxyList: proxyList,
|
|
||||||
}
|
|
||||||
return s, nil
|
|
||||||
}
|
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@ -61,7 +61,7 @@ type v2rayObfsOption struct {
|
|||||||
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
c, err := dialContext(ctx, "tcp", ss.server)
|
c, err := dialContext(ctx, "tcp", ss.server)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", ss.server, err.Error())
|
return nil, fmt.Errorf("%s connect error: %w", ss.server, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
switch ss.obfsMode {
|
switch ss.obfsMode {
|
||||||
@ -74,7 +74,7 @@ func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata) (C
|
|||||||
var err error
|
var err error
|
||||||
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", ss.server, err.Error())
|
return nil, fmt.Errorf("%s connect error: %w", ss.server, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c = ss.cipher.StreamConn(c)
|
c = ss.cipher.StreamConn(c)
|
||||||
@ -95,7 +95,7 @@ func (ss *ShadowSocks) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, er
|
|||||||
|
|
||||||
targetAddr := socks5.ParseAddr(metadata.RemoteAddress())
|
targetAddr := socks5.ParseAddr(metadata.RemoteAddress())
|
||||||
if targetAddr == nil {
|
if targetAddr == nil {
|
||||||
return nil, nil, fmt.Errorf("parse address error: %v:%v", metadata.String(), metadata.DstPort)
|
return nil, nil, fmt.Errorf("parse address %s error: %s", metadata.String(), metadata.DstPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
pc = ss.cipher.PacketConn(pc)
|
pc = ss.cipher.PacketConn(pc)
|
||||||
@ -114,7 +114,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
password := option.Password
|
password := option.Password
|
||||||
ciph, err := core.PickCipher(cipher, nil, password)
|
ciph, err := core.PickCipher(cipher, nil, password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %s", server, err.Error())
|
return nil, fmt.Errorf("ss %s initialize error: %w", server, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var v2rayOption *v2rayObfs.Option
|
var v2rayOption *v2rayObfs.Option
|
||||||
@ -136,7 +136,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
if option.Plugin == "obfs" {
|
if option.Plugin == "obfs" {
|
||||||
opts := simpleObfsOption{Host: "bing.com"}
|
opts := simpleObfsOption{Host: "bing.com"}
|
||||||
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize obfs error: %s", server, err.Error())
|
return nil, fmt.Errorf("ss %s initialize obfs error: %w", server, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.Mode != "tls" && opts.Mode != "http" {
|
if opts.Mode != "tls" && opts.Mode != "http" {
|
||||||
@ -147,7 +147,7 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
} else if option.Plugin == "v2ray-plugin" {
|
} else if option.Plugin == "v2ray-plugin" {
|
||||||
opts := v2rayObfsOption{Host: "bing.com", Mux: true}
|
opts := v2rayObfsOption{Host: "bing.com", Mux: true}
|
||||||
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %s", server, err.Error())
|
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %w", server, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if opts.Mode != "websocket" {
|
if opts.Mode != "websocket" {
|
||||||
@ -201,8 +201,13 @@ func (uc *ssUDPConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (uc *ssUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
func (uc *ssUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
n, a, e := uc.PacketConn.ReadFrom(b)
|
n, _, e := uc.PacketConn.ReadFrom(b)
|
||||||
addr := socks5.SplitAddr(b[:n])
|
addr := socks5.SplitAddr(b[:n])
|
||||||
copy(b, b[len(addr):])
|
var from net.Addr
|
||||||
return n - len(addr), a, e
|
if e == nil {
|
||||||
|
// Get the source IP/Port of packet.
|
||||||
|
from = addr.UDPAddr()
|
||||||
|
}
|
||||||
|
copy(b, b[len(addr):])
|
||||||
|
return n - len(addr), from, e
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@ -30,7 +30,7 @@ type SnellOption struct {
|
|||||||
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
c, err := dialContext(ctx, "tcp", s.server)
|
c, err := dialContext(ctx, "tcp", s.server)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", s.server, err.Error())
|
return nil, fmt.Errorf("%s connect error: %w", s.server, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
switch s.obfsOption.Mode {
|
switch s.obfsOption.Mode {
|
||||||
@ -53,7 +53,7 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
obfsOption := &simpleObfsOption{Host: "bing.com"}
|
obfsOption := &simpleObfsOption{Host: "bing.com"}
|
||||||
if err := decoder.Decode(option.ObfsOpts, obfsOption); err != nil {
|
if err := decoder.Decode(option.ObfsOpts, obfsOption); err != nil {
|
||||||
return nil, fmt.Errorf("snell %s initialize obfs error: %s", server, err.Error())
|
return nil, fmt.Errorf("snell %s initialize obfs error: %w", server, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if obfsOption.Mode != "tls" && obfsOption.Mode != "http" {
|
if obfsOption.Mode != "tls" && obfsOption.Mode != "http" {
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@ -44,7 +44,7 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error", ss.addr)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
var user *socks5.User
|
var user *socks5.User
|
||||||
@ -65,7 +65,7 @@ func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, _ net.Addr, err
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
c, err := dialContext(ctx, "tcp", ss.addr)
|
c, err := dialContext(ctx, "tcp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("%s connect error", ss.addr)
|
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -92,7 +92,7 @@ func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, _ net.Addr, err
|
|||||||
|
|
||||||
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("%v client hanshake error", err)
|
err = fmt.Errorf("client hanshake error: %w", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -103,7 +103,7 @@ func (ss *Socks5) DialUDP(metadata *C.Metadata) (_ C.PacketConn, _ net.Addr, err
|
|||||||
|
|
||||||
targetAddr := socks5.ParseAddr(metadata.RemoteAddress())
|
targetAddr := socks5.ParseAddr(metadata.RemoteAddress())
|
||||||
if targetAddr == nil {
|
if targetAddr == nil {
|
||||||
return nil, nil, fmt.Errorf("parse address error: %v:%v", metadata.String(), metadata.DstPort)
|
return nil, nil, fmt.Errorf("parse address %s error: %s", metadata.String(), metadata.DstPort)
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := net.ListenPacket("udp", "")
|
pc, err := net.ListenPacket("udp", "")
|
||||||
|
@ -1,159 +0,0 @@
|
|||||||
package adapters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net"
|
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/picker"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type URLTest struct {
|
|
||||||
*Base
|
|
||||||
proxies []C.Proxy
|
|
||||||
rawURL string
|
|
||||||
fast C.Proxy
|
|
||||||
interval time.Duration
|
|
||||||
done chan struct{}
|
|
||||||
once int32
|
|
||||||
}
|
|
||||||
|
|
||||||
type URLTestOption struct {
|
|
||||||
Name string `proxy:"name"`
|
|
||||||
Proxies []string `proxy:"proxies"`
|
|
||||||
URL string `proxy:"url"`
|
|
||||||
Interval int `proxy:"interval"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
|
||||||
return u.fast.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
|
||||||
for i := 0; i < 3; i++ {
|
|
||||||
c, err = u.fast.DialContext(ctx, metadata)
|
|
||||||
if err == nil {
|
|
||||||
c.AppendToChains(u)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
u.fallback()
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
|
||||||
pc, addr, err := u.fast.DialUDP(metadata)
|
|
||||||
if err == nil {
|
|
||||||
pc.AppendToChains(u)
|
|
||||||
}
|
|
||||||
return pc, addr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) SupportUDP() bool {
|
|
||||||
return u.fast.SupportUDP()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|
||||||
var all []string
|
|
||||||
for _, proxy := range u.proxies {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]interface{}{
|
|
||||||
"type": u.Type().String(),
|
|
||||||
"now": u.Now(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) Destroy() {
|
|
||||||
u.done <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) loop() {
|
|
||||||
tick := time.NewTicker(u.interval)
|
|
||||||
go u.speedTest()
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-tick.C:
|
|
||||||
go u.speedTest()
|
|
||||||
case <-u.done:
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) fallback() {
|
|
||||||
fast := u.proxies[0]
|
|
||||||
min := fast.LastDelay()
|
|
||||||
for _, proxy := range u.proxies[1:] {
|
|
||||||
if !proxy.Alive() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
delay := proxy.LastDelay()
|
|
||||||
if delay < min {
|
|
||||||
fast = proxy
|
|
||||||
min = delay
|
|
||||||
}
|
|
||||||
}
|
|
||||||
u.fast = fast
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *URLTest) speedTest() {
|
|
||||||
if !atomic.CompareAndSwapInt32(&u.once, 0, 1) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer atomic.StoreInt32(&u.once, 0)
|
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
|
||||||
defer cancel()
|
|
||||||
picker := picker.WithoutAutoCancel(ctx)
|
|
||||||
for _, p := range u.proxies {
|
|
||||||
proxy := p
|
|
||||||
picker.Go(func() (interface{}, error) {
|
|
||||||
_, err := proxy.URLTest(ctx, u.rawURL)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return proxy, nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fast := picker.WaitWithoutCancel()
|
|
||||||
if fast != nil {
|
|
||||||
u.fast = fast.(C.Proxy)
|
|
||||||
}
|
|
||||||
|
|
||||||
picker.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewURLTest(option URLTestOption, proxies []C.Proxy) (*URLTest, error) {
|
|
||||||
_, err := urlToMetadata(option.URL)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(proxies) < 1 {
|
|
||||||
return nil, errors.New("The number of proxies cannot be 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
|
||||||
urlTest := &URLTest{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.URLTest,
|
|
||||||
},
|
|
||||||
proxies: proxies[:],
|
|
||||||
rawURL: option.URL,
|
|
||||||
fast: proxies[0],
|
|
||||||
interval: interval,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
once: 0,
|
|
||||||
}
|
|
||||||
go urlTest.loop()
|
|
||||||
return urlTest, nil
|
|
||||||
}
|
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
@ -33,11 +33,12 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
|
|
||||||
port := u.Port()
|
port := u.Port()
|
||||||
if port == "" {
|
if port == "" {
|
||||||
if u.Scheme == "https" {
|
switch u.Scheme {
|
||||||
|
case "https":
|
||||||
port = "443"
|
port = "443"
|
||||||
} else if u.Scheme == "http" {
|
case "http":
|
||||||
port = "80"
|
port = "80"
|
||||||
} else {
|
default:
|
||||||
err = fmt.Errorf("%s scheme not Support", rawURL)
|
err = fmt.Errorf("%s scheme not Support", rawURL)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -92,8 +93,6 @@ func dialContext(ctx context.Context, network, address string) (net.Conn, error)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
dialer := net.Dialer{}
|
|
||||||
|
|
||||||
returned := make(chan struct{})
|
returned := make(chan struct{})
|
||||||
defer close(returned)
|
defer close(returned)
|
||||||
|
|
||||||
@ -108,6 +107,7 @@ func dialContext(ctx context.Context, network, address string) (net.Conn, error)
|
|||||||
var primary, fallback dialResult
|
var primary, fallback dialResult
|
||||||
|
|
||||||
startRacer := func(ctx context.Context, host string, ipv6 bool) {
|
startRacer := func(ctx context.Context, host string, ipv6 bool) {
|
||||||
|
dialer := net.Dialer{}
|
||||||
result := dialResult{ipv6: ipv6, done: true}
|
result := dialResult{ipv6: ipv6, done: true}
|
||||||
defer func() {
|
defer func() {
|
||||||
select {
|
select {
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package adapters
|
package outbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
20
adapters/outboundgroup/common.go
Normal file
20
adapters/outboundgroup/common.go
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultGetProxiesDuration = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
|
func getProvidersProxies(providers []provider.ProxyProvider) []C.Proxy {
|
||||||
|
proxies := []C.Proxy{}
|
||||||
|
for _, provider := range providers {
|
||||||
|
proxies = append(proxies, provider.Proxies()...)
|
||||||
|
}
|
||||||
|
return proxies
|
||||||
|
}
|
85
adapters/outboundgroup/fallback.go
Normal file
85
adapters/outboundgroup/fallback.go
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Fallback struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Now() string {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
return proxy.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
c, err := proxy.DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(f)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
pc, addr, err := proxy.DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(f)
|
||||||
|
}
|
||||||
|
return pc, addr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) SupportUDP() bool {
|
||||||
|
proxy := f.findAliveProxy()
|
||||||
|
return proxy.SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range f.proxies() {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": f.Type().String(),
|
||||||
|
"now": f.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) proxies() []C.Proxy {
|
||||||
|
elm, _, _ := f.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(f.providers), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) findAliveProxy() C.Proxy {
|
||||||
|
proxies := f.proxies()
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return f.proxies()[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFallback(name string, providers []provider.ProxyProvider) *Fallback {
|
||||||
|
return &Fallback{
|
||||||
|
Base: outbound.NewBase(name, C.Fallback, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
}
|
||||||
|
}
|
@ -1,26 +1,24 @@
|
|||||||
package adapters
|
package outboundgroup
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
|
|
||||||
type LoadBalance struct {
|
type LoadBalance struct {
|
||||||
*Base
|
*outbound.Base
|
||||||
proxies []C.Proxy
|
single *singledo.Single
|
||||||
maxRetry int
|
maxRetry int
|
||||||
rawURL string
|
providers []provider.ProxyProvider
|
||||||
interval time.Duration
|
|
||||||
done chan struct{}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func getKey(metadata *C.Metadata) string {
|
func getKey(metadata *C.Metadata) string {
|
||||||
@ -62,16 +60,17 @@ func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata) (c
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
buckets := int32(len(lb.proxies))
|
proxies := lb.proxies()
|
||||||
|
buckets := int32(len(proxies))
|
||||||
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
||||||
idx := jumpHash(key, buckets)
|
idx := jumpHash(key, buckets)
|
||||||
proxy := lb.proxies[idx]
|
proxy := proxies[idx]
|
||||||
if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
c, err = proxy.DialContext(ctx, metadata)
|
c, err = proxy.DialContext(ctx, metadata)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err = lb.proxies[0].DialContext(ctx, metadata)
|
c, err = proxies[0].DialContext(ctx, metadata)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -83,57 +82,34 @@ func (lb *LoadBalance) DialUDP(metadata *C.Metadata) (pc C.PacketConn, addr net.
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
||||||
buckets := int32(len(lb.proxies))
|
proxies := lb.proxies()
|
||||||
|
buckets := int32(len(proxies))
|
||||||
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
for i := 0; i < lb.maxRetry; i, key = i+1, key+1 {
|
||||||
idx := jumpHash(key, buckets)
|
idx := jumpHash(key, buckets)
|
||||||
proxy := lb.proxies[idx]
|
proxy := proxies[idx]
|
||||||
if proxy.Alive() {
|
if proxy.Alive() {
|
||||||
return proxy.DialUDP(metadata)
|
return proxy.DialUDP(metadata)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return lb.proxies[0].DialUDP(metadata)
|
return proxies[0].DialUDP(metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lb *LoadBalance) SupportUDP() bool {
|
func (lb *LoadBalance) SupportUDP() bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lb *LoadBalance) Destroy() {
|
func (lb *LoadBalance) proxies() []C.Proxy {
|
||||||
lb.done <- struct{}{}
|
elm, _, _ := lb.single.Do(func() (interface{}, error) {
|
||||||
}
|
return getProvidersProxies(lb.providers), nil
|
||||||
|
})
|
||||||
|
|
||||||
func (lb *LoadBalance) validTest() {
|
return elm.([]C.Proxy)
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
wg.Add(len(lb.proxies))
|
|
||||||
|
|
||||||
for _, p := range lb.proxies {
|
|
||||||
go func(p C.Proxy) {
|
|
||||||
p.URLTest(context.Background(), lb.rawURL)
|
|
||||||
wg.Done()
|
|
||||||
}(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lb *LoadBalance) loop() {
|
|
||||||
tick := time.NewTicker(lb.interval)
|
|
||||||
go lb.validTest()
|
|
||||||
Loop:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-tick.C:
|
|
||||||
go lb.validTest()
|
|
||||||
case <-lb.done:
|
|
||||||
break Loop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
var all []string
|
||||||
for _, proxy := range lb.proxies {
|
for _, proxy := range lb.proxies() {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]interface{}{
|
return json.Marshal(map[string]interface{}{
|
||||||
@ -142,31 +118,11 @@ func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
type LoadBalanceOption struct {
|
func NewLoadBalance(name string, providers []provider.ProxyProvider) *LoadBalance {
|
||||||
Name string `proxy:"name"`
|
return &LoadBalance{
|
||||||
Proxies []string `proxy:"proxies"`
|
Base: outbound.NewBase(name, C.LoadBalance, false),
|
||||||
URL string `proxy:"url"`
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
Interval int `proxy:"interval"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLoadBalance(option LoadBalanceOption, proxies []C.Proxy) (*LoadBalance, error) {
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, errors.New("Provide at least one proxy")
|
|
||||||
}
|
|
||||||
|
|
||||||
interval := time.Duration(option.Interval) * time.Second
|
|
||||||
|
|
||||||
lb := &LoadBalance{
|
|
||||||
Base: &Base{
|
|
||||||
name: option.Name,
|
|
||||||
tp: C.LoadBalance,
|
|
||||||
},
|
|
||||||
proxies: proxies,
|
|
||||||
maxRetry: 3,
|
maxRetry: 3,
|
||||||
rawURL: option.URL,
|
providers: providers,
|
||||||
interval: interval,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
}
|
||||||
go lb.loop()
|
|
||||||
return lb, nil
|
|
||||||
}
|
}
|
144
adapters/outboundgroup/parser.go
Normal file
144
adapters/outboundgroup/parser.go
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errFormat = errors.New("format error")
|
||||||
|
errType = errors.New("unsupport type")
|
||||||
|
errMissUse = errors.New("`use` field should not be empty")
|
||||||
|
errMissProxy = errors.New("`use` or `proxies` missing")
|
||||||
|
errMissHealthCheck = errors.New("`url` or `interval` missing")
|
||||||
|
errDuplicateProvider = errors.New("`duplicate provider name")
|
||||||
|
)
|
||||||
|
|
||||||
|
type GroupCommonOption struct {
|
||||||
|
Name string `group:"name"`
|
||||||
|
Type string `group:"type"`
|
||||||
|
Proxies []string `group:"proxies,omitempty"`
|
||||||
|
Use []string `group:"use,omitempty"`
|
||||||
|
URL string `group:"url,omitempty"`
|
||||||
|
Interval int `group:"interval,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseProxyGroup(config map[string]interface{}, proxyMap map[string]C.Proxy, providersMap map[string]provider.ProxyProvider) (C.ProxyAdapter, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
|
||||||
|
groupOption := &GroupCommonOption{}
|
||||||
|
if err := decoder.Decode(config, groupOption); err != nil {
|
||||||
|
return nil, errFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
if groupOption.Type == "" || groupOption.Name == "" {
|
||||||
|
return nil, errFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
groupName := groupOption.Name
|
||||||
|
|
||||||
|
providers := []provider.ProxyProvider{}
|
||||||
|
|
||||||
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
|
return nil, errMissProxy
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(groupOption.Proxies) != 0 {
|
||||||
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// if Use not empty, drop health check options
|
||||||
|
if len(groupOption.Use) != 0 {
|
||||||
|
hc := provider.NewHealthCheck(ps, "", 0)
|
||||||
|
pd, err := provider.NewCompatibleProvier(groupName, ps, hc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providers = append(providers, pd)
|
||||||
|
} else {
|
||||||
|
// select don't need health check
|
||||||
|
if groupOption.Type == "select" {
|
||||||
|
hc := provider.NewHealthCheck(ps, "", 0)
|
||||||
|
pd, err := provider.NewCompatibleProvier(groupName, ps, hc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providers = append(providers, pd)
|
||||||
|
providersMap[groupName] = pd
|
||||||
|
} else {
|
||||||
|
if groupOption.URL == "" || groupOption.Interval == 0 {
|
||||||
|
return nil, errMissHealthCheck
|
||||||
|
}
|
||||||
|
|
||||||
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval))
|
||||||
|
pd, err := provider.NewCompatibleProvier(groupName, ps, hc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providers = append(providers, pd)
|
||||||
|
providersMap[groupName] = pd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(groupOption.Use) != 0 {
|
||||||
|
list, err := getProviders(providersMap, groupOption.Use)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
providers = append(providers, list...)
|
||||||
|
}
|
||||||
|
|
||||||
|
var group C.ProxyAdapter
|
||||||
|
switch groupOption.Type {
|
||||||
|
case "url-test":
|
||||||
|
group = NewURLTest(groupName, providers)
|
||||||
|
case "select":
|
||||||
|
group = NewSelector(groupName, providers)
|
||||||
|
case "fallback":
|
||||||
|
group = NewFallback(groupName, providers)
|
||||||
|
case "load-balance":
|
||||||
|
group = NewLoadBalance(groupName, providers)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
return group, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
||||||
|
var ps []C.Proxy
|
||||||
|
for _, name := range list {
|
||||||
|
p, ok := mapping[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
|
}
|
||||||
|
ps = append(ps, p)
|
||||||
|
}
|
||||||
|
return ps, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProviders(mapping map[string]provider.ProxyProvider, list []string) ([]provider.ProxyProvider, error) {
|
||||||
|
var ps []provider.ProxyProvider
|
||||||
|
for _, name := range list {
|
||||||
|
p, ok := mapping[name]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.VehicleType() == provider.Compatible {
|
||||||
|
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
||||||
|
}
|
||||||
|
ps = append(ps, p)
|
||||||
|
}
|
||||||
|
return ps, nil
|
||||||
|
}
|
86
adapters/outboundgroup/selector.go
Normal file
86
adapters/outboundgroup/selector.go
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Selector struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single
|
||||||
|
selected C.Proxy
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
c, err := s.selected.DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
|
pc, addr, err := s.selected.DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(s)
|
||||||
|
}
|
||||||
|
return pc, addr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) SupportUDP() bool {
|
||||||
|
return s.selected.SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range s.proxies() {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": s.Type().String(),
|
||||||
|
"now": s.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Now() string {
|
||||||
|
return s.selected.Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Set(name string) error {
|
||||||
|
for _, proxy := range s.proxies() {
|
||||||
|
if proxy.Name() == name {
|
||||||
|
s.selected = proxy
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.New("Proxy does not exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) proxies() []C.Proxy {
|
||||||
|
elm, _, _ := s.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(s.providers), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSelector(name string, providers []provider.ProxyProvider) *Selector {
|
||||||
|
selected := providers[0].Proxies()[0]
|
||||||
|
return &Selector{
|
||||||
|
Base: outbound.NewBase(name, C.Selector, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
providers: providers,
|
||||||
|
selected: selected,
|
||||||
|
}
|
||||||
|
}
|
95
adapters/outboundgroup/urltest.go
Normal file
95
adapters/outboundgroup/urltest.go
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type URLTest struct {
|
||||||
|
*outbound.Base
|
||||||
|
single *singledo.Single
|
||||||
|
fastSingle *singledo.Single
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Now() string {
|
||||||
|
return u.fast().Name()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
||||||
|
c, err = u.fast().DialContext(ctx, metadata)
|
||||||
|
if err == nil {
|
||||||
|
c.AppendToChains(u)
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) DialUDP(metadata *C.Metadata) (C.PacketConn, net.Addr, error) {
|
||||||
|
pc, addr, err := u.fast().DialUDP(metadata)
|
||||||
|
if err == nil {
|
||||||
|
pc.AppendToChains(u)
|
||||||
|
}
|
||||||
|
return pc, addr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) proxies() []C.Proxy {
|
||||||
|
elm, _, _ := u.single.Do(func() (interface{}, error) {
|
||||||
|
return getProvidersProxies(u.providers), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.([]C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) fast() C.Proxy {
|
||||||
|
elm, _, _ := u.fastSingle.Do(func() (interface{}, error) {
|
||||||
|
proxies := u.proxies()
|
||||||
|
fast := proxies[0]
|
||||||
|
min := fast.LastDelay()
|
||||||
|
for _, proxy := range proxies[1:] {
|
||||||
|
if !proxy.Alive() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
delay := proxy.LastDelay()
|
||||||
|
if delay < min {
|
||||||
|
fast = proxy
|
||||||
|
min = delay
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fast, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return elm.(C.Proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) SupportUDP() bool {
|
||||||
|
return u.fast().SupportUDP()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
|
var all []string
|
||||||
|
for _, proxy := range u.proxies() {
|
||||||
|
all = append(all, proxy.Name())
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"type": u.Type().String(),
|
||||||
|
"now": u.Now(),
|
||||||
|
"all": all,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewURLTest(name string, providers []provider.ProxyProvider) *URLTest {
|
||||||
|
return &URLTest{
|
||||||
|
Base: outbound.NewBase(name, C.URLTest, false),
|
||||||
|
single: singledo.NewSingle(defaultGetProxiesDuration),
|
||||||
|
fastSingle: singledo.NewSingle(time.Second * 10),
|
||||||
|
providers: providers,
|
||||||
|
}
|
||||||
|
}
|
70
adapters/provider/healthcheck.go
Normal file
70
adapters/provider/healthcheck.go
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultURLTestTimeout = time.Second * 5
|
||||||
|
)
|
||||||
|
|
||||||
|
type HealthCheckOption struct {
|
||||||
|
URL string
|
||||||
|
Interval uint
|
||||||
|
}
|
||||||
|
|
||||||
|
type HealthCheck struct {
|
||||||
|
url string
|
||||||
|
proxies []C.Proxy
|
||||||
|
interval uint
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) process() {
|
||||||
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
|
go hc.check()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
hc.check()
|
||||||
|
case <-hc.done:
|
||||||
|
ticker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
||||||
|
hc.proxies = proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) auto() bool {
|
||||||
|
return hc.interval != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) check() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
|
for _, proxy := range hc.proxies {
|
||||||
|
go proxy.URLTest(ctx, hc.url)
|
||||||
|
}
|
||||||
|
|
||||||
|
<-ctx.Done()
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) close() {
|
||||||
|
hc.done <- struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHealthCheck(proxies []C.Proxy, url string, interval uint) *HealthCheck {
|
||||||
|
return &HealthCheck{
|
||||||
|
proxies: proxies,
|
||||||
|
url: url,
|
||||||
|
interval: interval,
|
||||||
|
done: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
}
|
58
adapters/provider/parser.go
Normal file
58
adapters/provider/parser.go
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errVehicleType = errors.New("unsupport vehicle type")
|
||||||
|
)
|
||||||
|
|
||||||
|
type healthCheckSchema struct {
|
||||||
|
Enable bool `provider:"enable"`
|
||||||
|
URL string `provider:"url"`
|
||||||
|
Interval int `provider:"interval"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type proxyProviderSchema struct {
|
||||||
|
Type string `provider:"type"`
|
||||||
|
Path string `provider:"path"`
|
||||||
|
URL string `provider:"url,omitempty"`
|
||||||
|
Interval int `provider:"interval,omitempty"`
|
||||||
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseProxyProvider(name string, mapping map[string]interface{}) (ProxyProvider, error) {
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
|
schema := &proxyProviderSchema{}
|
||||||
|
if err := decoder.Decode(mapping, schema); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var hcInterval uint = 0
|
||||||
|
if schema.HealthCheck.Enable {
|
||||||
|
hcInterval = uint(schema.HealthCheck.Interval)
|
||||||
|
}
|
||||||
|
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval)
|
||||||
|
|
||||||
|
path := C.Path.Reslove(schema.Path)
|
||||||
|
|
||||||
|
var vehicle Vehicle
|
||||||
|
switch schema.Type {
|
||||||
|
case "file":
|
||||||
|
vehicle = NewFileVehicle(path)
|
||||||
|
case "http":
|
||||||
|
vehicle = NewHTTPVehicle(schema.URL, path)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||||
|
return NewProxySetProvider(name, interval, vehicle, hc), nil
|
||||||
|
}
|
318
adapters/provider/provider.go
Normal file
318
adapters/provider/provider.go
Normal file
@ -0,0 +1,318 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/md5"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ReservedName = "default"
|
||||||
|
|
||||||
|
fileMode = 0666
|
||||||
|
)
|
||||||
|
|
||||||
|
// Provider Type
|
||||||
|
const (
|
||||||
|
Proxy ProviderType = iota
|
||||||
|
Rule
|
||||||
|
)
|
||||||
|
|
||||||
|
// ProviderType defined
|
||||||
|
type ProviderType int
|
||||||
|
|
||||||
|
func (pt ProviderType) String() string {
|
||||||
|
switch pt {
|
||||||
|
case Proxy:
|
||||||
|
return "Proxy"
|
||||||
|
case Rule:
|
||||||
|
return "Rule"
|
||||||
|
default:
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provider interface
|
||||||
|
type Provider interface {
|
||||||
|
Name() string
|
||||||
|
VehicleType() VehicleType
|
||||||
|
Type() ProviderType
|
||||||
|
Initial() error
|
||||||
|
Reload() error
|
||||||
|
Destroy() error
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyProvider interface
|
||||||
|
type ProxyProvider interface {
|
||||||
|
Provider
|
||||||
|
Proxies() []C.Proxy
|
||||||
|
HealthCheck()
|
||||||
|
Update() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxySchema struct {
|
||||||
|
Proxies []map[string]interface{} `yaml:"proxies"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxySetProvider struct {
|
||||||
|
name string
|
||||||
|
vehicle Vehicle
|
||||||
|
hash [16]byte
|
||||||
|
proxies []C.Proxy
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
ticker *time.Ticker
|
||||||
|
updatedAt *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"name": pp.Name(),
|
||||||
|
"type": pp.Type().String(),
|
||||||
|
"vehicleType": pp.VehicleType().String(),
|
||||||
|
"proxies": pp.Proxies(),
|
||||||
|
"updatedAt": pp.updatedAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Name() string {
|
||||||
|
return pp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Reload() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) HealthCheck() {
|
||||||
|
pp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Update() error {
|
||||||
|
return pp.pull()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Destroy() error {
|
||||||
|
pp.healthCheck.close()
|
||||||
|
|
||||||
|
if pp.ticker != nil {
|
||||||
|
pp.ticker.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Initial() error {
|
||||||
|
var buf []byte
|
||||||
|
var err error
|
||||||
|
if stat, err := os.Stat(pp.vehicle.Path()); err == nil {
|
||||||
|
buf, err = ioutil.ReadFile(pp.vehicle.Path())
|
||||||
|
modTime := stat.ModTime()
|
||||||
|
pp.updatedAt = &modTime
|
||||||
|
} else {
|
||||||
|
buf, err = pp.vehicle.Read()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err := pp.parse(buf)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := ioutil.WriteFile(pp.vehicle.Path(), buf, fileMode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
pp.hash = md5.Sum(buf)
|
||||||
|
pp.setProxies(proxies)
|
||||||
|
|
||||||
|
// pull proxies automatically
|
||||||
|
if pp.ticker != nil {
|
||||||
|
go pp.pullLoop()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) VehicleType() VehicleType {
|
||||||
|
return pp.vehicle.Type()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Type() ProviderType {
|
||||||
|
return Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Proxies() []C.Proxy {
|
||||||
|
return pp.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) pullLoop() {
|
||||||
|
for range pp.ticker.C {
|
||||||
|
if err := pp.pull(); err != nil {
|
||||||
|
log.Warnln("[Provider] %s pull error: %s", pp.Name(), err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) pull() error {
|
||||||
|
buf, err := pp.vehicle.Read()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
hash := md5.Sum(buf)
|
||||||
|
if bytes.Equal(pp.hash[:], hash[:]) {
|
||||||
|
log.Debugln("[Provider] %s's proxies doesn't change", pp.Name())
|
||||||
|
pp.updatedAt = &now
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies, err := pp.parse(buf)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
log.Infoln("[Provider] %s's proxies update", pp.Name())
|
||||||
|
|
||||||
|
if err := ioutil.WriteFile(pp.vehicle.Path(), buf, fileMode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
pp.updatedAt = &now
|
||||||
|
pp.hash = hash
|
||||||
|
pp.setProxies(proxies)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) parse(buf []byte) ([]C.Proxy, error) {
|
||||||
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
|
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if schema.Proxies == nil {
|
||||||
|
return nil, errors.New("File must have a `proxies` field")
|
||||||
|
}
|
||||||
|
|
||||||
|
proxies := []C.Proxy{}
|
||||||
|
for idx, mapping := range schema.Proxies {
|
||||||
|
proxy, err := outbound.ParseProxy(mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Proxy %d error: %w", idx, err)
|
||||||
|
}
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("File doesn't have any valid proxy")
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) setProxies(proxies []C.Proxy) {
|
||||||
|
pp.proxies = proxies
|
||||||
|
pp.healthCheck.setProxy(proxies)
|
||||||
|
go pp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProxySetProvider(name string, interval time.Duration, vehicle Vehicle, hc *HealthCheck) *ProxySetProvider {
|
||||||
|
var ticker *time.Ticker
|
||||||
|
if interval != 0 {
|
||||||
|
ticker = time.NewTicker(interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ProxySetProvider{
|
||||||
|
name: name,
|
||||||
|
vehicle: vehicle,
|
||||||
|
proxies: []C.Proxy{},
|
||||||
|
healthCheck: hc,
|
||||||
|
ticker: ticker,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type CompatibleProvier struct {
|
||||||
|
name string
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
proxies []C.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]interface{}{
|
||||||
|
"name": cp.Name(),
|
||||||
|
"type": cp.Type().String(),
|
||||||
|
"vehicleType": cp.VehicleType().String(),
|
||||||
|
"proxies": cp.Proxies(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) Name() string {
|
||||||
|
return cp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) Reload() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) Destroy() error {
|
||||||
|
cp.healthCheck.close()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) HealthCheck() {
|
||||||
|
cp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) Update() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) Initial() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) VehicleType() VehicleType {
|
||||||
|
return Compatible
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) Type() ProviderType {
|
||||||
|
return Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvier) Proxies() []C.Proxy {
|
||||||
|
return cp.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCompatibleProvier(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvier, error) {
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("Provider need one proxy at least")
|
||||||
|
}
|
||||||
|
|
||||||
|
if hc.auto() {
|
||||||
|
go hc.process()
|
||||||
|
}
|
||||||
|
|
||||||
|
return &CompatibleProvier{
|
||||||
|
name: name,
|
||||||
|
proxies: proxies,
|
||||||
|
healthCheck: hc,
|
||||||
|
}, nil
|
||||||
|
}
|
109
adapters/provider/vehicle.go
Normal file
109
adapters/provider/vehicle.go
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io/ioutil"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Vehicle Type
|
||||||
|
const (
|
||||||
|
File VehicleType = iota
|
||||||
|
HTTP
|
||||||
|
Compatible
|
||||||
|
)
|
||||||
|
|
||||||
|
// VehicleType defined
|
||||||
|
type VehicleType int
|
||||||
|
|
||||||
|
func (v VehicleType) String() string {
|
||||||
|
switch v {
|
||||||
|
case File:
|
||||||
|
return "File"
|
||||||
|
case HTTP:
|
||||||
|
return "HTTP"
|
||||||
|
case Compatible:
|
||||||
|
return "Compatible"
|
||||||
|
default:
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Vehicle interface {
|
||||||
|
Read() ([]byte, error)
|
||||||
|
Path() string
|
||||||
|
Type() VehicleType
|
||||||
|
}
|
||||||
|
|
||||||
|
type FileVehicle struct {
|
||||||
|
path string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Type() VehicleType {
|
||||||
|
return File
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Path() string {
|
||||||
|
return f.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *FileVehicle) Read() ([]byte, error) {
|
||||||
|
return ioutil.ReadFile(f.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFileVehicle(path string) *FileVehicle {
|
||||||
|
return &FileVehicle{path: path}
|
||||||
|
}
|
||||||
|
|
||||||
|
type HTTPVehicle struct {
|
||||||
|
url string
|
||||||
|
path string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Type() VehicleType {
|
||||||
|
return HTTP
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Path() string {
|
||||||
|
return h.path
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *HTTPVehicle) Read() ([]byte, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, h.url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
transport := &http.Transport{
|
||||||
|
// from http.DefaultTransport
|
||||||
|
MaxIdleConns: 100,
|
||||||
|
IdleConnTimeout: 90 * time.Second,
|
||||||
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
client := http.Client{Transport: transport}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
buf, err := ioutil.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := ioutil.WriteFile(h.path, buf, fileMode); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
|
||||||
|
return &HTTPVehicle{url, path}
|
||||||
|
}
|
14
common/cache/lrucache.go
vendored
14
common/cache/lrucache.go
vendored
@ -11,6 +11,16 @@ import (
|
|||||||
// Option is part of Functional Options Pattern
|
// Option is part of Functional Options Pattern
|
||||||
type Option func(*LruCache)
|
type Option func(*LruCache)
|
||||||
|
|
||||||
|
// EvictCallback is used to get a callback when a cache entry is evicted
|
||||||
|
type EvictCallback func(key interface{}, value interface{})
|
||||||
|
|
||||||
|
// WithEvict set the evict callback
|
||||||
|
func WithEvict(cb EvictCallback) Option {
|
||||||
|
return func(l *LruCache) {
|
||||||
|
l.onEvict = cb
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// WithUpdateAgeOnGet update expires when Get element
|
// WithUpdateAgeOnGet update expires when Get element
|
||||||
func WithUpdateAgeOnGet() Option {
|
func WithUpdateAgeOnGet() Option {
|
||||||
return func(l *LruCache) {
|
return func(l *LruCache) {
|
||||||
@ -42,6 +52,7 @@ type LruCache struct {
|
|||||||
cache map[interface{}]*list.Element
|
cache map[interface{}]*list.Element
|
||||||
lru *list.List // Front is least-recent
|
lru *list.List // Front is least-recent
|
||||||
updateAgeOnGet bool
|
updateAgeOnGet bool
|
||||||
|
onEvict EvictCallback
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewLRUCache creates an LruCache
|
// NewLRUCache creates an LruCache
|
||||||
@ -148,6 +159,9 @@ func (c *LruCache) deleteElement(le *list.Element) {
|
|||||||
c.lru.Remove(le)
|
c.lru.Remove(le)
|
||||||
e := le.Value.(*entry)
|
e := le.Value.(*entry)
|
||||||
delete(c.cache, e.key)
|
delete(c.cache, e.key)
|
||||||
|
if c.onEvict != nil {
|
||||||
|
c.onEvict(e.key, e.value)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type entry struct {
|
type entry struct {
|
||||||
|
21
common/cache/lrucache_test.go
vendored
21
common/cache/lrucache_test.go
vendored
@ -115,3 +115,24 @@ func TestMaxSize(t *testing.T) {
|
|||||||
_, ok = c.Get("foo")
|
_, ok = c.Get("foo")
|
||||||
assert.False(t, ok)
|
assert.False(t, ok)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExist(t *testing.T) {
|
||||||
|
c := NewLRUCache(WithSize(1))
|
||||||
|
c.Set(1, 2)
|
||||||
|
assert.True(t, c.Exist(1))
|
||||||
|
c.Set(2, 3)
|
||||||
|
assert.False(t, c.Exist(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEvict(t *testing.T) {
|
||||||
|
temp := 0
|
||||||
|
evict := func(key interface{}, value interface{}) {
|
||||||
|
temp = key.(int) + value.(int)
|
||||||
|
}
|
||||||
|
|
||||||
|
c := NewLRUCache(WithEvict(evict), WithSize(1))
|
||||||
|
c.Set(1, 2)
|
||||||
|
c.Set(2, 3)
|
||||||
|
|
||||||
|
assert.Equal(t, temp, 3)
|
||||||
|
}
|
||||||
|
@ -7,60 +7,58 @@ import (
|
|||||||
|
|
||||||
type Observable struct {
|
type Observable struct {
|
||||||
iterable Iterable
|
iterable Iterable
|
||||||
listener *sync.Map
|
listener map[Subscription]*Subscriber
|
||||||
|
mux sync.Mutex
|
||||||
done bool
|
done bool
|
||||||
doneLock sync.RWMutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) process() {
|
func (o *Observable) process() {
|
||||||
for item := range o.iterable {
|
for item := range o.iterable {
|
||||||
o.listener.Range(func(key, value interface{}) bool {
|
o.mux.Lock()
|
||||||
elm := value.(*Subscriber)
|
for _, sub := range o.listener {
|
||||||
elm.Emit(item)
|
sub.Emit(item)
|
||||||
return true
|
}
|
||||||
})
|
o.mux.Unlock()
|
||||||
}
|
}
|
||||||
o.close()
|
o.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) close() {
|
func (o *Observable) close() {
|
||||||
o.doneLock.Lock()
|
o.mux.Lock()
|
||||||
o.done = true
|
defer o.mux.Unlock()
|
||||||
o.doneLock.Unlock()
|
|
||||||
|
|
||||||
o.listener.Range(func(key, value interface{}) bool {
|
o.done = true
|
||||||
elm := value.(*Subscriber)
|
for _, sub := range o.listener {
|
||||||
elm.Close()
|
sub.Close()
|
||||||
return true
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) Subscribe() (Subscription, error) {
|
func (o *Observable) Subscribe() (Subscription, error) {
|
||||||
o.doneLock.RLock()
|
o.mux.Lock()
|
||||||
done := o.done
|
defer o.mux.Unlock()
|
||||||
o.doneLock.RUnlock()
|
if o.done {
|
||||||
if done == true {
|
|
||||||
return nil, errors.New("Observable is closed")
|
return nil, errors.New("Observable is closed")
|
||||||
}
|
}
|
||||||
subscriber := newSubscriber()
|
subscriber := newSubscriber()
|
||||||
o.listener.Store(subscriber.Out(), subscriber)
|
o.listener[subscriber.Out()] = subscriber
|
||||||
return subscriber.Out(), nil
|
return subscriber.Out(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *Observable) UnSubscribe(sub Subscription) {
|
func (o *Observable) UnSubscribe(sub Subscription) {
|
||||||
elm, exist := o.listener.Load(sub)
|
o.mux.Lock()
|
||||||
|
defer o.mux.Unlock()
|
||||||
|
subscriber, exist := o.listener[sub]
|
||||||
if !exist {
|
if !exist {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
subscriber := elm.(*Subscriber)
|
delete(o.listener, sub)
|
||||||
o.listener.Delete(subscriber.Out())
|
|
||||||
subscriber.Close()
|
subscriber.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewObservable(any Iterable) *Observable {
|
func NewObservable(any Iterable) *Observable {
|
||||||
observable := &Observable{
|
observable := &Observable{
|
||||||
iterable: any,
|
iterable: any,
|
||||||
listener: &sync.Map{},
|
listener: map[Subscription]*Subscriber{},
|
||||||
}
|
}
|
||||||
go observable.process()
|
go observable.process()
|
||||||
return observable
|
return observable
|
||||||
|
@ -5,6 +5,8 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func iterator(item []interface{}) chan interface{} {
|
func iterator(item []interface{}) chan interface{} {
|
||||||
@ -23,16 +25,12 @@ func TestObservable(t *testing.T) {
|
|||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
if err != nil {
|
assert.Nil(t, err)
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
count := 0
|
count := 0
|
||||||
for range data {
|
for range data {
|
||||||
count = count + 1
|
count++
|
||||||
}
|
|
||||||
if count != 5 {
|
|
||||||
t.Error("Revc number error")
|
|
||||||
}
|
}
|
||||||
|
assert.Equal(t, count, 5)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_MutilSubscribe(t *testing.T) {
|
func TestObservable_MutilSubscribe(t *testing.T) {
|
||||||
@ -46,30 +44,24 @@ func TestObservable_MutilSubscribe(t *testing.T) {
|
|||||||
wg.Add(2)
|
wg.Add(2)
|
||||||
waitCh := func(ch <-chan interface{}) {
|
waitCh := func(ch <-chan interface{}) {
|
||||||
for range ch {
|
for range ch {
|
||||||
count = count + 1
|
count++
|
||||||
}
|
}
|
||||||
wg.Done()
|
wg.Done()
|
||||||
}
|
}
|
||||||
go waitCh(ch1)
|
go waitCh(ch1)
|
||||||
go waitCh(ch2)
|
go waitCh(ch2)
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
if count != 10 {
|
assert.Equal(t, count, 10)
|
||||||
t.Error("Revc number error")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribe(t *testing.T) {
|
func TestObservable_UnSubscribe(t *testing.T) {
|
||||||
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
iter := iterator([]interface{}{1, 2, 3, 4, 5})
|
||||||
src := NewObservable(iter)
|
src := NewObservable(iter)
|
||||||
data, err := src.Subscribe()
|
data, err := src.Subscribe()
|
||||||
if err != nil {
|
assert.Nil(t, err)
|
||||||
t.Error(err)
|
|
||||||
}
|
|
||||||
src.UnSubscribe(data)
|
src.UnSubscribe(data)
|
||||||
_, open := <-data
|
_, open := <-data
|
||||||
if open {
|
assert.False(t, open)
|
||||||
t.Error("Revc number error")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
func TestObservable_SubscribeClosedSource(t *testing.T) {
|
||||||
@ -79,9 +71,7 @@ func TestObservable_SubscribeClosedSource(t *testing.T) {
|
|||||||
<-data
|
<-data
|
||||||
|
|
||||||
_, closed := src.Subscribe()
|
_, closed := src.Subscribe()
|
||||||
if closed == nil {
|
assert.NotNil(t, closed)
|
||||||
t.Error("Observable should be closed")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
func TestObservable_UnSubscribeWithNotExistSubscription(t *testing.T) {
|
||||||
@ -118,7 +108,5 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
|
|||||||
}
|
}
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
now := runtime.NumGoroutine()
|
now := runtime.NumGoroutine()
|
||||||
if init != now {
|
assert.Equal(t, init, now)
|
||||||
t.Errorf("Goroutine Leak: init %d now %d", init, now)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
55
common/singledo/singledo.go
Normal file
55
common/singledo/singledo.go
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
package singledo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type call struct {
|
||||||
|
wg sync.WaitGroup
|
||||||
|
val interface{}
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Single struct {
|
||||||
|
mux sync.Mutex
|
||||||
|
last time.Time
|
||||||
|
wait time.Duration
|
||||||
|
call *call
|
||||||
|
result *Result
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Val interface{}
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Single) Do(fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
|
||||||
|
s.mux.Lock()
|
||||||
|
now := time.Now()
|
||||||
|
if now.Before(s.last.Add(s.wait)) {
|
||||||
|
s.mux.Unlock()
|
||||||
|
return s.result.Val, s.result.Err, true
|
||||||
|
}
|
||||||
|
|
||||||
|
if call := s.call; call != nil {
|
||||||
|
s.mux.Unlock()
|
||||||
|
call.wg.Wait()
|
||||||
|
return call.val, call.err, true
|
||||||
|
}
|
||||||
|
|
||||||
|
call := &call{}
|
||||||
|
call.wg.Add(1)
|
||||||
|
s.call = call
|
||||||
|
s.mux.Unlock()
|
||||||
|
call.val, call.err = fn()
|
||||||
|
call.wg.Done()
|
||||||
|
s.call = nil
|
||||||
|
s.result = &Result{call.val, call.err}
|
||||||
|
s.last = now
|
||||||
|
return call.val, call.err, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSingle(wait time.Duration) *Single {
|
||||||
|
return &Single{wait: wait}
|
||||||
|
}
|
53
common/singledo/singledo_test.go
Normal file
53
common/singledo/singledo_test.go
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
package singledo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBasic(t *testing.T) {
|
||||||
|
single := NewSingle(time.Millisecond * 30)
|
||||||
|
foo := 0
|
||||||
|
shardCount := 0
|
||||||
|
call := func() (interface{}, error) {
|
||||||
|
foo++
|
||||||
|
time.Sleep(time.Millisecond * 5)
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
const n = 10
|
||||||
|
wg.Add(n)
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
go func() {
|
||||||
|
_, _, shard := single.Do(call)
|
||||||
|
if shard {
|
||||||
|
shardCount++
|
||||||
|
}
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
assert.Equal(t, 1, foo)
|
||||||
|
assert.Equal(t, 9, shardCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTimer(t *testing.T) {
|
||||||
|
single := NewSingle(time.Millisecond * 30)
|
||||||
|
foo := 0
|
||||||
|
call := func() (interface{}, error) {
|
||||||
|
foo++
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
single.Do(call)
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
_, _, shard := single.Do(call)
|
||||||
|
|
||||||
|
assert.Equal(t, 1, foo)
|
||||||
|
assert.True(t, shard)
|
||||||
|
}
|
@ -76,6 +76,8 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error
|
|||||||
return d.decodeMap(name, data, val)
|
return d.decodeMap(name, data, val)
|
||||||
case reflect.Interface:
|
case reflect.Interface:
|
||||||
return d.setInterface(name, data, val)
|
return d.setInterface(name, data, val)
|
||||||
|
case reflect.Struct:
|
||||||
|
return d.decodeStruct(name, data, val)
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("type %s not support", val.Kind().String())
|
return fmt.Errorf("type %s not support", val.Kind().String())
|
||||||
}
|
}
|
||||||
@ -232,6 +234,159 @@ func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val refle
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error {
|
||||||
|
dataVal := reflect.Indirect(reflect.ValueOf(data))
|
||||||
|
|
||||||
|
// If the type of the value to write to and the data match directly,
|
||||||
|
// then we just set it directly instead of recursing into the structure.
|
||||||
|
if dataVal.Type() == val.Type() {
|
||||||
|
val.Set(dataVal)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
dataValKind := dataVal.Kind()
|
||||||
|
switch dataValKind {
|
||||||
|
case reflect.Map:
|
||||||
|
return d.decodeStructFromMap(name, dataVal, val)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) error {
|
||||||
|
dataValType := dataVal.Type()
|
||||||
|
if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface {
|
||||||
|
return fmt.Errorf(
|
||||||
|
"'%s' needs a map with string keys, has '%s' keys",
|
||||||
|
name, dataValType.Key().Kind())
|
||||||
|
}
|
||||||
|
|
||||||
|
dataValKeys := make(map[reflect.Value]struct{})
|
||||||
|
dataValKeysUnused := make(map[interface{}]struct{})
|
||||||
|
for _, dataValKey := range dataVal.MapKeys() {
|
||||||
|
dataValKeys[dataValKey] = struct{}{}
|
||||||
|
dataValKeysUnused[dataValKey.Interface()] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
errors := make([]string, 0)
|
||||||
|
|
||||||
|
// This slice will keep track of all the structs we'll be decoding.
|
||||||
|
// There can be more than one struct if there are embedded structs
|
||||||
|
// that are squashed.
|
||||||
|
structs := make([]reflect.Value, 1, 5)
|
||||||
|
structs[0] = val
|
||||||
|
|
||||||
|
// Compile the list of all the fields that we're going to be decoding
|
||||||
|
// from all the structs.
|
||||||
|
type field struct {
|
||||||
|
field reflect.StructField
|
||||||
|
val reflect.Value
|
||||||
|
}
|
||||||
|
fields := []field{}
|
||||||
|
for len(structs) > 0 {
|
||||||
|
structVal := structs[0]
|
||||||
|
structs = structs[1:]
|
||||||
|
|
||||||
|
structType := structVal.Type()
|
||||||
|
|
||||||
|
for i := 0; i < structType.NumField(); i++ {
|
||||||
|
fieldType := structType.Field(i)
|
||||||
|
fieldKind := fieldType.Type.Kind()
|
||||||
|
|
||||||
|
// If "squash" is specified in the tag, we squash the field down.
|
||||||
|
squash := false
|
||||||
|
tagParts := strings.Split(fieldType.Tag.Get(d.option.TagName), ",")
|
||||||
|
for _, tag := range tagParts[1:] {
|
||||||
|
if tag == "squash" {
|
||||||
|
squash = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if squash {
|
||||||
|
if fieldKind != reflect.Struct {
|
||||||
|
errors = append(errors,
|
||||||
|
fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind).Error())
|
||||||
|
} else {
|
||||||
|
structs = append(structs, structVal.FieldByName(fieldType.Name))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal struct field, store it away
|
||||||
|
fields = append(fields, field{fieldType, structVal.Field(i)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// for fieldType, field := range fields {
|
||||||
|
for _, f := range fields {
|
||||||
|
field, fieldValue := f.field, f.val
|
||||||
|
fieldName := field.Name
|
||||||
|
|
||||||
|
tagValue := field.Tag.Get(d.option.TagName)
|
||||||
|
tagValue = strings.SplitN(tagValue, ",", 2)[0]
|
||||||
|
if tagValue != "" {
|
||||||
|
fieldName = tagValue
|
||||||
|
}
|
||||||
|
|
||||||
|
rawMapKey := reflect.ValueOf(fieldName)
|
||||||
|
rawMapVal := dataVal.MapIndex(rawMapKey)
|
||||||
|
if !rawMapVal.IsValid() {
|
||||||
|
// Do a slower search by iterating over each key and
|
||||||
|
// doing case-insensitive search.
|
||||||
|
for dataValKey := range dataValKeys {
|
||||||
|
mK, ok := dataValKey.Interface().(string)
|
||||||
|
if !ok {
|
||||||
|
// Not a string key
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.EqualFold(mK, fieldName) {
|
||||||
|
rawMapKey = dataValKey
|
||||||
|
rawMapVal = dataVal.MapIndex(dataValKey)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !rawMapVal.IsValid() {
|
||||||
|
// There was no matching key in the map for the value in
|
||||||
|
// the struct. Just ignore.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the key we're using from the unused map so we stop tracking
|
||||||
|
delete(dataValKeysUnused, rawMapKey.Interface())
|
||||||
|
|
||||||
|
if !fieldValue.IsValid() {
|
||||||
|
// This should never happen
|
||||||
|
panic("field is not valid")
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we can't set the field, then it is unexported or something,
|
||||||
|
// and we just continue onwards.
|
||||||
|
if !fieldValue.CanSet() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the name is empty string, then we're at the root, and we
|
||||||
|
// don't dot-join the fields.
|
||||||
|
if name != "" {
|
||||||
|
fieldName = fmt.Sprintf("%s.%s", name, fieldName)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil {
|
||||||
|
errors = append(errors, err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(errors) > 0 {
|
||||||
|
return fmt.Errorf(strings.Join(errors, ","))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (d *Decoder) setInterface(name string, data interface{}, val reflect.Value) (err error) {
|
func (d *Decoder) setInterface(name string, data interface{}, val reflect.Value) (err error) {
|
||||||
dataVal := reflect.ValueOf(data)
|
dataVal := reflect.ValueOf(data)
|
||||||
val.Set(dataVal)
|
val.Set(dataVal)
|
||||||
|
@ -6,6 +6,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
|
trie "github.com/Dreamacro/clash/component/domain-trie"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Pool is a implementation about fake ip generator without storage
|
// Pool is a implementation about fake ip generator without storage
|
||||||
@ -14,7 +15,8 @@ type Pool struct {
|
|||||||
min uint32
|
min uint32
|
||||||
gateway uint32
|
gateway uint32
|
||||||
offset uint32
|
offset uint32
|
||||||
mux *sync.Mutex
|
mux sync.Mutex
|
||||||
|
host *trie.Trie
|
||||||
cache *cache.LruCache
|
cache *cache.LruCache
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -60,6 +62,28 @@ func (p *Pool) LookBack(ip net.IP) (string, bool) {
|
|||||||
return "", false
|
return "", false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LookupHost return if domain in host
|
||||||
|
func (p *Pool) LookupHost(domain string) bool {
|
||||||
|
if p.host == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return p.host.Search(domain) != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exist returns if given ip exists in fake-ip pool
|
||||||
|
func (p *Pool) Exist(ip net.IP) bool {
|
||||||
|
p.mux.Lock()
|
||||||
|
defer p.mux.Unlock()
|
||||||
|
|
||||||
|
if ip = ip.To4(); ip == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
n := ipToUint(ip.To4())
|
||||||
|
offset := n - p.min + 1
|
||||||
|
return p.cache.Exist(offset)
|
||||||
|
}
|
||||||
|
|
||||||
// Gateway return gateway ip
|
// Gateway return gateway ip
|
||||||
func (p *Pool) Gateway() net.IP {
|
func (p *Pool) Gateway() net.IP {
|
||||||
return uintToIP(p.gateway)
|
return uintToIP(p.gateway)
|
||||||
@ -96,7 +120,7 @@ func uintToIP(v uint32) net.IP {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// New return Pool instance
|
// New return Pool instance
|
||||||
func New(ipnet *net.IPNet, size int) (*Pool, error) {
|
func New(ipnet *net.IPNet, size int, host *trie.Trie) (*Pool, error) {
|
||||||
min := ipToUint(ipnet.IP) + 2
|
min := ipToUint(ipnet.IP) + 2
|
||||||
|
|
||||||
ones, bits := ipnet.Mask.Size()
|
ones, bits := ipnet.Mask.Size()
|
||||||
@ -111,7 +135,7 @@ func New(ipnet *net.IPNet, size int) (*Pool, error) {
|
|||||||
min: min,
|
min: min,
|
||||||
max: max,
|
max: max,
|
||||||
gateway: min - 1,
|
gateway: min - 1,
|
||||||
mux: &sync.Mutex{},
|
host: host,
|
||||||
cache: cache.NewLRUCache(cache.WithSize(size * 2)),
|
cache: cache.NewLRUCache(cache.WithSize(size * 2)),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,7 @@ import (
|
|||||||
|
|
||||||
func TestPool_Basic(t *testing.T) {
|
func TestPool_Basic(t *testing.T) {
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/29")
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/29")
|
||||||
pool, _ := New(ipnet, 10)
|
pool, _ := New(ipnet, 10, nil)
|
||||||
|
|
||||||
first := pool.Lookup("foo.com")
|
first := pool.Lookup("foo.com")
|
||||||
last := pool.Lookup("bar.com")
|
last := pool.Lookup("bar.com")
|
||||||
@ -23,7 +23,7 @@ func TestPool_Basic(t *testing.T) {
|
|||||||
|
|
||||||
func TestPool_Cycle(t *testing.T) {
|
func TestPool_Cycle(t *testing.T) {
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/30")
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/30")
|
||||||
pool, _ := New(ipnet, 10)
|
pool, _ := New(ipnet, 10, nil)
|
||||||
|
|
||||||
first := pool.Lookup("foo.com")
|
first := pool.Lookup("foo.com")
|
||||||
same := pool.Lookup("baz.com")
|
same := pool.Lookup("baz.com")
|
||||||
@ -33,7 +33,7 @@ func TestPool_Cycle(t *testing.T) {
|
|||||||
|
|
||||||
func TestPool_MaxCacheSize(t *testing.T) {
|
func TestPool_MaxCacheSize(t *testing.T) {
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/24")
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/24")
|
||||||
pool, _ := New(ipnet, 2)
|
pool, _ := New(ipnet, 2, nil)
|
||||||
|
|
||||||
first := pool.Lookup("foo.com")
|
first := pool.Lookup("foo.com")
|
||||||
pool.Lookup("bar.com")
|
pool.Lookup("bar.com")
|
||||||
@ -45,7 +45,7 @@ func TestPool_MaxCacheSize(t *testing.T) {
|
|||||||
|
|
||||||
func TestPool_DoubleMapping(t *testing.T) {
|
func TestPool_DoubleMapping(t *testing.T) {
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/24")
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/24")
|
||||||
pool, _ := New(ipnet, 2)
|
pool, _ := New(ipnet, 2, nil)
|
||||||
|
|
||||||
// fill cache
|
// fill cache
|
||||||
fooIP := pool.Lookup("foo.com")
|
fooIP := pool.Lookup("foo.com")
|
||||||
@ -72,7 +72,7 @@ func TestPool_DoubleMapping(t *testing.T) {
|
|||||||
|
|
||||||
func TestPool_Error(t *testing.T) {
|
func TestPool_Error(t *testing.T) {
|
||||||
_, ipnet, _ := net.ParseCIDR("192.168.0.1/31")
|
_, ipnet, _ := net.ParseCIDR("192.168.0.1/31")
|
||||||
_, err := New(ipnet, 10)
|
_, err := New(ipnet, 10, nil)
|
||||||
|
|
||||||
assert.Error(t, err)
|
assert.Error(t, err)
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,7 @@ package socks5
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
@ -62,6 +63,25 @@ func (a Addr) String() string {
|
|||||||
return net.JoinHostPort(host, port)
|
return net.JoinHostPort(host, port)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UDPAddr converts a socks5.Addr to *net.UDPAddr
|
||||||
|
func (a Addr) UDPAddr() *net.UDPAddr {
|
||||||
|
if len(a) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch a[0] {
|
||||||
|
case AtypIPv4:
|
||||||
|
var ip [net.IPv4len]byte
|
||||||
|
copy(ip[0:], a[1:1+net.IPv4len])
|
||||||
|
return &net.UDPAddr{IP: net.IP(ip[:]), Port: int(binary.BigEndian.Uint16(a[1+net.IPv4len : 1+net.IPv4len+2]))}
|
||||||
|
case AtypIPv6:
|
||||||
|
var ip [net.IPv6len]byte
|
||||||
|
copy(ip[0:], a[1:1+net.IPv6len])
|
||||||
|
return &net.UDPAddr{IP: net.IP(ip[:]), Port: int(binary.BigEndian.Uint16(a[1+net.IPv6len : 1+net.IPv6len+2]))}
|
||||||
|
}
|
||||||
|
// Other Atyp
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// SOCKS errors as defined in RFC 1928 section 6.
|
// SOCKS errors as defined in RFC 1928 section 6.
|
||||||
const (
|
const (
|
||||||
ErrGeneralFailure = Error(1)
|
ErrGeneralFailure = Error(1)
|
||||||
@ -338,6 +358,40 @@ func ParseAddr(s string) Addr {
|
|||||||
return addr
|
return addr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ParseAddrToSocksAddr parse a socks addr from net.addr
|
||||||
|
// This is a fast path of ParseAddr(addr.String())
|
||||||
|
func ParseAddrToSocksAddr(addr net.Addr) Addr {
|
||||||
|
var hostip net.IP
|
||||||
|
var port int
|
||||||
|
if udpaddr, ok := addr.(*net.UDPAddr); ok {
|
||||||
|
hostip = udpaddr.IP
|
||||||
|
port = udpaddr.Port
|
||||||
|
} else if tcpaddr, ok := addr.(*net.TCPAddr); ok {
|
||||||
|
hostip = tcpaddr.IP
|
||||||
|
port = tcpaddr.Port
|
||||||
|
}
|
||||||
|
|
||||||
|
// fallback parse
|
||||||
|
if hostip == nil {
|
||||||
|
return ParseAddr(addr.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed Addr
|
||||||
|
if ip4 := hostip.To4(); ip4.DefaultMask() != nil {
|
||||||
|
parsed = make([]byte, 1+net.IPv4len+2)
|
||||||
|
parsed[0] = AtypIPv4
|
||||||
|
copy(parsed[1:], ip4)
|
||||||
|
binary.BigEndian.PutUint16(parsed[1+net.IPv4len:], uint16(port))
|
||||||
|
|
||||||
|
} else {
|
||||||
|
parsed = make([]byte, 1+net.IPv6len+2)
|
||||||
|
parsed[0] = AtypIPv6
|
||||||
|
copy(parsed[1:], hostip)
|
||||||
|
binary.BigEndian.PutUint16(parsed[1+net.IPv6len:], uint16(port))
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
// DecodeUDPPacket split `packet` to addr payload, and this function is mutable with `packet`
|
// DecodeUDPPacket split `packet` to addr payload, and this function is mutable with `packet`
|
||||||
func DecodeUDPPacket(packet []byte) (addr Addr, payload []byte, err error) {
|
func DecodeUDPPacket(packet []byte) (addr Addr, payload []byte, err error) {
|
||||||
if len(packet) < 5 {
|
if len(packet) < 5 {
|
||||||
|
@ -52,7 +52,7 @@ func (m *Mux) Read(b []byte) (int, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
m.remain = m.remain - n
|
m.remain -= n
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,6 +8,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
@ -17,6 +18,10 @@ type websocketConn struct {
|
|||||||
conn *websocket.Conn
|
conn *websocket.Conn
|
||||||
reader io.Reader
|
reader io.Reader
|
||||||
remoteAddr net.Addr
|
remoteAddr net.Addr
|
||||||
|
|
||||||
|
// https://godoc.org/github.com/gorilla/websocket#hdr-Concurrency
|
||||||
|
rMux sync.Mutex
|
||||||
|
wMux sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
type WebsocketConfig struct {
|
type WebsocketConfig struct {
|
||||||
@ -29,6 +34,8 @@ type WebsocketConfig struct {
|
|||||||
|
|
||||||
// Read implements net.Conn.Read()
|
// Read implements net.Conn.Read()
|
||||||
func (wsc *websocketConn) Read(b []byte) (int, error) {
|
func (wsc *websocketConn) Read(b []byte) (int, error) {
|
||||||
|
wsc.rMux.Lock()
|
||||||
|
defer wsc.rMux.Unlock()
|
||||||
for {
|
for {
|
||||||
reader, err := wsc.getReader()
|
reader, err := wsc.getReader()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -46,6 +53,8 @@ func (wsc *websocketConn) Read(b []byte) (int, error) {
|
|||||||
|
|
||||||
// Write implements io.Writer.
|
// Write implements io.Writer.
|
||||||
func (wsc *websocketConn) Write(b []byte) (int, error) {
|
func (wsc *websocketConn) Write(b []byte) (int, error) {
|
||||||
|
wsc.wMux.Lock()
|
||||||
|
defer wsc.wMux.Unlock()
|
||||||
if err := wsc.conn.WriteMessage(websocket.BinaryMessage, b); err != nil {
|
if err := wsc.conn.WriteMessage(websocket.BinaryMessage, b); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
|
303
config/config.go
303
config/config.go
@ -2,15 +2,14 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
|
||||||
"net"
|
"net"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/adapters/outboundgroup"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
"github.com/Dreamacro/clash/component/auth"
|
"github.com/Dreamacro/clash/component/auth"
|
||||||
trie "github.com/Dreamacro/clash/component/domain-trie"
|
trie "github.com/Dreamacro/clash/component/domain-trie"
|
||||||
"github.com/Dreamacro/clash/component/fakeip"
|
"github.com/Dreamacro/clash/component/fakeip"
|
||||||
@ -70,6 +69,7 @@ type Config struct {
|
|||||||
Rules []C.Rule
|
Rules []C.Rule
|
||||||
Users []auth.AuthUser
|
Users []auth.AuthUser
|
||||||
Proxies map[string]C.Proxy
|
Proxies map[string]C.Proxy
|
||||||
|
Providers map[string]provider.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
type rawDNS struct {
|
type rawDNS struct {
|
||||||
@ -81,6 +81,7 @@ type rawDNS struct {
|
|||||||
Listen string `yaml:"listen"`
|
Listen string `yaml:"listen"`
|
||||||
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
EnhancedMode dns.EnhancedMode `yaml:"enhanced-mode"`
|
||||||
FakeIPRange string `yaml:"fake-ip-range"`
|
FakeIPRange string `yaml:"fake-ip-range"`
|
||||||
|
FakeIPFilter []string `yaml:"fake-ip-filter"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type rawFallbackFilter struct {
|
type rawFallbackFilter struct {
|
||||||
@ -101,6 +102,7 @@ type rawConfig struct {
|
|||||||
ExternalUI string `yaml:"external-ui"`
|
ExternalUI string `yaml:"external-ui"`
|
||||||
Secret string `yaml:"secret"`
|
Secret string `yaml:"secret"`
|
||||||
|
|
||||||
|
ProxyProvider map[string]map[string]interface{} `yaml:"proxy-provider"`
|
||||||
Hosts map[string]string `yaml:"hosts"`
|
Hosts map[string]string `yaml:"hosts"`
|
||||||
DNS rawDNS `yaml:"dns"`
|
DNS rawDNS `yaml:"dns"`
|
||||||
Experimental Experimental `yaml:"experimental"`
|
Experimental Experimental `yaml:"experimental"`
|
||||||
@ -109,40 +111,12 @@ type rawConfig struct {
|
|||||||
Rule []string `yaml:"Rule"`
|
Rule []string `yaml:"Rule"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// forward compatibility before 1.0
|
// Parse config
|
||||||
func readRawConfig(path string) ([]byte, error) {
|
func Parse(buf []byte) (*Config, error) {
|
||||||
data, err := ioutil.ReadFile(path)
|
config := &Config{}
|
||||||
if err == nil && len(data) != 0 {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if filepath.Ext(path) != ".yaml" {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
path = path[:len(path)-5] + ".yml"
|
|
||||||
if _, err = os.Stat(path); err == nil {
|
|
||||||
return ioutil.ReadFile(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func readConfig(path string) (*rawConfig, error) {
|
|
||||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
data, err := readRawConfig(path)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(data) == 0 {
|
|
||||||
return nil, fmt.Errorf("Configuration file %s is empty", path)
|
|
||||||
}
|
|
||||||
|
|
||||||
// config with some default value
|
// config with some default value
|
||||||
rawConfig := &rawConfig{
|
rawCfg := &rawConfig{
|
||||||
AllowLan: false,
|
AllowLan: false,
|
||||||
BindAddress: "*",
|
BindAddress: "*",
|
||||||
Mode: T.Rule,
|
Mode: T.Rule,
|
||||||
@ -164,18 +138,10 @@ func readConfig(path string) (*rawConfig, error) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
err = yaml.Unmarshal([]byte(data), &rawConfig)
|
if err := yaml.Unmarshal(buf, &rawCfg); err != nil {
|
||||||
return rawConfig, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse config
|
|
||||||
func Parse(path string) (*Config, error) {
|
|
||||||
config := &Config{}
|
|
||||||
|
|
||||||
rawCfg, err := readConfig(path)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
config.Experimental = &rawCfg.Experimental
|
config.Experimental = &rawCfg.Experimental
|
||||||
|
|
||||||
general, err := parseGeneral(rawCfg)
|
general, err := parseGeneral(rawCfg)
|
||||||
@ -184,11 +150,12 @@ func Parse(path string) (*Config, error) {
|
|||||||
}
|
}
|
||||||
config.General = general
|
config.General = general
|
||||||
|
|
||||||
proxies, err := parseProxies(rawCfg)
|
proxies, providers, err := parseProxies(rawCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
config.Proxies = proxies
|
config.Proxies = proxies
|
||||||
|
config.Providers = providers
|
||||||
|
|
||||||
rules, err := parseRules(rawCfg, proxies)
|
rules, err := parseRules(rawCfg, proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -209,7 +176,6 @@ func Parse(path string) (*Config, error) {
|
|||||||
config.Hosts = hosts
|
config.Hosts = hosts
|
||||||
|
|
||||||
config.Users = parseAuthentication(rawCfg.Authentication)
|
config.Users = parseAuthentication(rawCfg.Authentication)
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -226,9 +192,7 @@ func parseGeneral(cfg *rawConfig) (*General, error) {
|
|||||||
logLevel := cfg.LogLevel
|
logLevel := cfg.LogLevel
|
||||||
|
|
||||||
if externalUI != "" {
|
if externalUI != "" {
|
||||||
if !filepath.IsAbs(externalUI) {
|
externalUI = C.Path.Reslove(externalUI)
|
||||||
externalUI = filepath.Join(C.Path.HomeDir(), externalUI)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := os.Stat(externalUI); os.IsNotExist(err) {
|
if _, err := os.Stat(externalUI); os.IsNotExist(err) {
|
||||||
return nil, fmt.Errorf("external-ui: %s not exist", externalUI)
|
return nil, fmt.Errorf("external-ui: %s not exist", externalUI)
|
||||||
@ -250,75 +214,38 @@ func parseGeneral(cfg *rawConfig) (*General, error) {
|
|||||||
return general, nil
|
return general, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
func parseProxies(cfg *rawConfig) (proxies map[string]C.Proxy, providersMap map[string]provider.ProxyProvider, err error) {
|
||||||
proxies := make(map[string]C.Proxy)
|
proxies = make(map[string]C.Proxy)
|
||||||
|
providersMap = make(map[string]provider.ProxyProvider)
|
||||||
proxyList := []string{}
|
proxyList := []string{}
|
||||||
proxiesConfig := cfg.Proxy
|
proxiesConfig := cfg.Proxy
|
||||||
groupsConfig := cfg.ProxyGroup
|
groupsConfig := cfg.ProxyGroup
|
||||||
|
providersConfig := cfg.ProxyProvider
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
defer func() {
|
||||||
|
// Destroy already created provider when err != nil
|
||||||
|
if err != nil {
|
||||||
|
for _, provider := range providersMap {
|
||||||
|
provider.Destroy()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
proxies["DIRECT"] = adapters.NewProxy(adapters.NewDirect())
|
proxies["DIRECT"] = outbound.NewProxy(outbound.NewDirect())
|
||||||
proxies["REJECT"] = adapters.NewProxy(adapters.NewReject())
|
proxies["REJECT"] = outbound.NewProxy(outbound.NewReject())
|
||||||
proxyList = append(proxyList, "DIRECT", "REJECT")
|
proxyList = append(proxyList, "DIRECT", "REJECT")
|
||||||
|
|
||||||
// parse proxy
|
// parse proxy
|
||||||
for idx, mapping := range proxiesConfig {
|
for idx, mapping := range proxiesConfig {
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxy, err := outbound.ParseProxy(mapping)
|
||||||
if !existType {
|
|
||||||
return nil, fmt.Errorf("Proxy %d missing type", idx)
|
|
||||||
}
|
|
||||||
|
|
||||||
var proxy C.ProxyAdapter
|
|
||||||
err := fmt.Errorf("cannot parse")
|
|
||||||
switch proxyType {
|
|
||||||
case "ss":
|
|
||||||
ssOption := &adapters.ShadowSocksOption{}
|
|
||||||
err = decoder.Decode(mapping, ssOption)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
return nil, nil, fmt.Errorf("Proxy %d: %w", idx, err)
|
||||||
}
|
|
||||||
proxy, err = adapters.NewShadowSocks(*ssOption)
|
|
||||||
case "socks5":
|
|
||||||
socksOption := &adapters.Socks5Option{}
|
|
||||||
err = decoder.Decode(mapping, socksOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy = adapters.NewSocks5(*socksOption)
|
|
||||||
case "http":
|
|
||||||
httpOption := &adapters.HttpOption{}
|
|
||||||
err = decoder.Decode(mapping, httpOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy = adapters.NewHttp(*httpOption)
|
|
||||||
case "vmess":
|
|
||||||
vmessOption := &adapters.VmessOption{}
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = adapters.NewVmess(*vmessOption)
|
|
||||||
case "snell":
|
|
||||||
snellOption := &adapters.SnellOption{}
|
|
||||||
err = decoder.Decode(mapping, snellOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
proxy, err = adapters.NewSnell(*snellOption)
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("Unsupport proxy type: %s", proxyType)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Proxy [%d]: %s", idx, err.Error())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, exist := proxies[proxy.Name()]; exist {
|
if _, exist := proxies[proxy.Name()]; exist {
|
||||||
return nil, fmt.Errorf("Proxy %s is the duplicate name", proxy.Name())
|
return nil, nil, fmt.Errorf("Proxy %s is the duplicate name", proxy.Name())
|
||||||
}
|
}
|
||||||
proxies[proxy.Name()] = adapters.NewProxy(proxy)
|
proxies[proxy.Name()] = proxy
|
||||||
proxyList = append(proxyList, proxy.Name())
|
proxyList = append(proxyList, proxy.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -326,95 +253,75 @@ func parseProxies(cfg *rawConfig) (map[string]C.Proxy, error) {
|
|||||||
for idx, mapping := range groupsConfig {
|
for idx, mapping := range groupsConfig {
|
||||||
groupName, existName := mapping["name"].(string)
|
groupName, existName := mapping["name"].(string)
|
||||||
if !existName {
|
if !existName {
|
||||||
return nil, fmt.Errorf("ProxyGroup %d: missing name", idx)
|
return nil, nil, fmt.Errorf("ProxyGroup %d: missing name", idx)
|
||||||
}
|
}
|
||||||
proxyList = append(proxyList, groupName)
|
proxyList = append(proxyList, groupName)
|
||||||
}
|
}
|
||||||
|
|
||||||
// check if any loop exists and sort the ProxyGroups
|
// check if any loop exists and sort the ProxyGroups
|
||||||
if err := proxyGroupsDagSort(groupsConfig, decoder); err != nil {
|
if err := proxyGroupsDagSort(groupsConfig); err != nil {
|
||||||
return nil, err
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse and initial providers
|
||||||
|
for name, mapping := range providersConfig {
|
||||||
|
if name == provider.ReservedName {
|
||||||
|
return nil, nil, fmt.Errorf("can not defined a provider called `%s`", provider.ReservedName)
|
||||||
|
}
|
||||||
|
|
||||||
|
pd, err := provider.ParseProxyProvider(name, mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
providersMap[name] = pd
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, provider := range providersMap {
|
||||||
|
log.Infoln("Start initial provider %s", provider.Name())
|
||||||
|
if err := provider.Initial(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse proxy group
|
// parse proxy group
|
||||||
for _, mapping := range groupsConfig {
|
for idx, mapping := range groupsConfig {
|
||||||
groupType, existType := mapping["type"].(string)
|
group, err := outboundgroup.ParseProxyGroup(mapping, proxies, providersMap)
|
||||||
groupName, _ := mapping["name"].(string)
|
if err != nil {
|
||||||
if !existType {
|
return nil, nil, fmt.Errorf("ProxyGroup[%d]: %w", idx, err)
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: missing type", groupName)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
groupName := group.Name()
|
||||||
if _, exist := proxies[groupName]; exist {
|
if _, exist := proxies[groupName]; exist {
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: the duplicate name", groupName)
|
return nil, nil, fmt.Errorf("ProxyGroup %s: the duplicate name", groupName)
|
||||||
}
|
|
||||||
var group C.ProxyAdapter
|
|
||||||
ps := []C.Proxy{}
|
|
||||||
|
|
||||||
err := fmt.Errorf("cannot parse")
|
|
||||||
switch groupType {
|
|
||||||
case "url-test":
|
|
||||||
urlTestOption := &adapters.URLTestOption{}
|
|
||||||
err = decoder.Decode(mapping, urlTestOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ps, err = getProxies(proxies, urlTestOption.Proxies)
|
proxies[groupName] = outbound.NewProxy(group)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
|
||||||
}
|
|
||||||
group, err = adapters.NewURLTest(*urlTestOption, ps)
|
|
||||||
case "select":
|
|
||||||
selectorOption := &adapters.SelectorOption{}
|
|
||||||
err = decoder.Decode(mapping, selectorOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ps, err = getProxies(proxies, selectorOption.Proxies)
|
// initial compatible provier
|
||||||
if err != nil {
|
for _, pd := range providersMap {
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
if pd.VehicleType() != provider.Compatible {
|
||||||
}
|
continue
|
||||||
group, err = adapters.NewSelector(selectorOption.Name, ps)
|
|
||||||
case "fallback":
|
|
||||||
fallbackOption := &adapters.FallbackOption{}
|
|
||||||
err = decoder.Decode(mapping, fallbackOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ps, err = getProxies(proxies, fallbackOption.Proxies)
|
log.Infoln("Start initial compatible provider %s", pd.Name())
|
||||||
if err != nil {
|
if err := pd.Initial(); err != nil {
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
group, err = adapters.NewFallback(*fallbackOption, ps)
|
|
||||||
case "load-balance":
|
|
||||||
loadBalanceOption := &adapters.LoadBalanceOption{}
|
|
||||||
err = decoder.Decode(mapping, loadBalanceOption)
|
|
||||||
if err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
ps, err = getProxies(proxies, loadBalanceOption.Proxies)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
|
||||||
}
|
|
||||||
group, err = adapters.NewLoadBalance(*loadBalanceOption, ps)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Proxy %s: %s", groupName, err.Error())
|
|
||||||
}
|
|
||||||
proxies[groupName] = adapters.NewProxy(group)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ps := []C.Proxy{}
|
ps := []C.Proxy{}
|
||||||
for _, v := range proxyList {
|
for _, v := range proxyList {
|
||||||
ps = append(ps, proxies[v])
|
ps = append(ps, proxies[v])
|
||||||
}
|
}
|
||||||
|
hc := provider.NewHealthCheck(ps, "", 0)
|
||||||
|
pd, _ := provider.NewCompatibleProvier(provider.ReservedName, ps, hc)
|
||||||
|
providersMap[provider.ReservedName] = pd
|
||||||
|
|
||||||
global, _ := adapters.NewSelector("GLOBAL", ps)
|
global := outboundgroup.NewSelector("GLOBAL", []provider.ProxyProvider{pd})
|
||||||
proxies["GLOBAL"] = adapters.NewProxy(global)
|
proxies["GLOBAL"] = outbound.NewProxy(global)
|
||||||
return proxies, nil
|
return proxies, providersMap, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRules(cfg *rawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
func parseRules(cfg *rawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
||||||
@ -427,14 +334,19 @@ func parseRules(cfg *rawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
|||||||
var (
|
var (
|
||||||
payload string
|
payload string
|
||||||
target string
|
target string
|
||||||
|
params = []string{}
|
||||||
)
|
)
|
||||||
|
|
||||||
switch len(rule) {
|
switch l := len(rule); {
|
||||||
case 2:
|
case l == 2:
|
||||||
target = rule[1]
|
target = rule[1]
|
||||||
case 3:
|
case l == 3:
|
||||||
payload = rule[1]
|
payload = rule[1]
|
||||||
target = rule[2]
|
target = rule[2]
|
||||||
|
case l >= 4:
|
||||||
|
payload = rule[1]
|
||||||
|
target = rule[2]
|
||||||
|
params = rule[3:]
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("Rules[%d] [%s] error: format invalid", idx, line)
|
return nil, fmt.Errorf("Rules[%d] [%s] error: format invalid", idx, line)
|
||||||
}
|
}
|
||||||
@ -444,7 +356,12 @@ func parseRules(cfg *rawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rule = trimArr(rule)
|
rule = trimArr(rule)
|
||||||
var parsed C.Rule
|
params = trimArr(params)
|
||||||
|
var (
|
||||||
|
parseErr error
|
||||||
|
parsed C.Rule
|
||||||
|
)
|
||||||
|
|
||||||
switch rule[0] {
|
switch rule[0] {
|
||||||
case "DOMAIN":
|
case "DOMAIN":
|
||||||
parsed = R.NewDomain(payload, target)
|
parsed = R.NewDomain(payload, target)
|
||||||
@ -453,35 +370,31 @@ func parseRules(cfg *rawConfig, proxies map[string]C.Proxy) ([]C.Rule, error) {
|
|||||||
case "DOMAIN-KEYWORD":
|
case "DOMAIN-KEYWORD":
|
||||||
parsed = R.NewDomainKeyword(payload, target)
|
parsed = R.NewDomainKeyword(payload, target)
|
||||||
case "GEOIP":
|
case "GEOIP":
|
||||||
parsed = R.NewGEOIP(payload, target)
|
noResolve := R.HasNoResolve(params)
|
||||||
|
parsed = R.NewGEOIP(payload, target, noResolve)
|
||||||
case "IP-CIDR", "IP-CIDR6":
|
case "IP-CIDR", "IP-CIDR6":
|
||||||
if rule := R.NewIPCIDR(payload, target, false); rule != nil {
|
noResolve := R.HasNoResolve(params)
|
||||||
parsed = rule
|
parsed, parseErr = R.NewIPCIDR(payload, target, R.WithIPCIDRNoResolve(noResolve))
|
||||||
}
|
|
||||||
// deprecated when bump to 1.0
|
// deprecated when bump to 1.0
|
||||||
case "SOURCE-IP-CIDR":
|
case "SOURCE-IP-CIDR":
|
||||||
fallthrough
|
fallthrough
|
||||||
case "SRC-IP-CIDR":
|
case "SRC-IP-CIDR":
|
||||||
if rule := R.NewIPCIDR(payload, target, true); rule != nil {
|
parsed, parseErr = R.NewIPCIDR(payload, target, R.WithIPCIDRSourceIP(true), R.WithIPCIDRNoResolve(true))
|
||||||
parsed = rule
|
|
||||||
}
|
|
||||||
case "SRC-PORT":
|
case "SRC-PORT":
|
||||||
if rule := R.NewPort(payload, target, true); rule != nil {
|
parsed, parseErr = R.NewPort(payload, target, true)
|
||||||
parsed = rule
|
|
||||||
}
|
|
||||||
case "DST-PORT":
|
case "DST-PORT":
|
||||||
if rule := R.NewPort(payload, target, false); rule != nil {
|
parsed, parseErr = R.NewPort(payload, target, false)
|
||||||
parsed = rule
|
|
||||||
}
|
|
||||||
case "MATCH":
|
case "MATCH":
|
||||||
fallthrough
|
fallthrough
|
||||||
// deprecated when bump to 1.0
|
// deprecated when bump to 1.0
|
||||||
case "FINAL":
|
case "FINAL":
|
||||||
parsed = R.NewMatch(target)
|
parsed = R.NewMatch(target)
|
||||||
|
default:
|
||||||
|
parseErr = fmt.Errorf("unsupported rule type %s", rule[0])
|
||||||
}
|
}
|
||||||
|
|
||||||
if parsed == nil {
|
if parseErr != nil {
|
||||||
return nil, fmt.Errorf("Rules[%d] [%s] error: payload invalid", idx, line)
|
return nil, fmt.Errorf("Rules[%d] [%s] error: %s", idx, line, parseErr.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
rules = append(rules, parsed)
|
rules = append(rules, parsed)
|
||||||
@ -611,7 +524,17 @@ func parseDNS(cfg rawDNS) (*DNS, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pool, err := fakeip.New(ipnet, 1000)
|
|
||||||
|
var host *trie.Trie
|
||||||
|
// fake ip skip host filter
|
||||||
|
if len(cfg.FakeIPFilter) != 0 {
|
||||||
|
host = trie.New()
|
||||||
|
for _, domain := range cfg.FakeIPFilter {
|
||||||
|
host.Insert(domain, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pool, err := fakeip.New(ipnet, 1000, host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -10,8 +10,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func downloadMMDB(path string) (err error) {
|
func downloadMMDB(path string) (err error) {
|
||||||
@ -65,13 +64,13 @@ func Init(dir string) error {
|
|||||||
|
|
||||||
// initial config.yaml
|
// initial config.yaml
|
||||||
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.Config()); os.IsNotExist(err) {
|
||||||
log.Info("Can't find config, create an empty file")
|
log.Infoln("Can't find config, create an empty file")
|
||||||
os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
|
os.OpenFile(C.Path.Config(), os.O_CREATE|os.O_WRONLY, 0644)
|
||||||
}
|
}
|
||||||
|
|
||||||
// initial mmdb
|
// initial mmdb
|
||||||
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
if _, err := os.Stat(C.Path.MMDB()); os.IsNotExist(err) {
|
||||||
log.Info("Can't find MMDB, start download")
|
log.Infoln("Can't find MMDB, start download")
|
||||||
err := downloadMMDB(C.Path.MMDB())
|
err := downloadMMDB(C.Path.MMDB())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("Can't download MMDB: %s", err.Error())
|
return fmt.Errorf("Can't download MMDB: %s", err.Error())
|
||||||
|
@ -4,9 +4,8 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
adapters "github.com/Dreamacro/clash/adapters/outbound"
|
"github.com/Dreamacro/clash/adapters/outboundgroup"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func trimArr(arr []string) (r []string) {
|
func trimArr(arr []string) (r []string) {
|
||||||
@ -16,18 +15,6 @@ func trimArr(arr []string) (r []string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
|
||||||
var ps []C.Proxy
|
|
||||||
for _, name := range list {
|
|
||||||
p, ok := mapping[name]
|
|
||||||
if !ok {
|
|
||||||
return nil, fmt.Errorf("'%s' not found", name)
|
|
||||||
}
|
|
||||||
ps = append(ps, p)
|
|
||||||
}
|
|
||||||
return ps, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func or(pointers ...*int) *int {
|
func or(pointers ...*int) *int {
|
||||||
for _, p := range pointers {
|
for _, p := range pointers {
|
||||||
if p != nil {
|
if p != nil {
|
||||||
@ -40,8 +27,7 @@ func or(pointers ...*int) *int {
|
|||||||
// Check if ProxyGroups form DAG(Directed Acyclic Graph), and sort all ProxyGroups by dependency order.
|
// Check if ProxyGroups form DAG(Directed Acyclic Graph), and sort all ProxyGroups by dependency order.
|
||||||
// Meanwhile, record the original index in the config file.
|
// Meanwhile, record the original index in the config file.
|
||||||
// If loop is detected, return an error with location of loop.
|
// If loop is detected, return an error with location of loop.
|
||||||
func proxyGroupsDagSort(groupsConfig []map[string]interface{}, decoder *structure.Decoder) error {
|
func proxyGroupsDagSort(groupsConfig []map[string]interface{}) error {
|
||||||
|
|
||||||
type graphNode struct {
|
type graphNode struct {
|
||||||
indegree int
|
indegree int
|
||||||
// topological order
|
// topological order
|
||||||
@ -50,34 +36,36 @@ func proxyGroupsDagSort(groupsConfig []map[string]interface{}, decoder *structur
|
|||||||
data map[string]interface{}
|
data map[string]interface{}
|
||||||
// `outdegree` and `from` are used in loop locating
|
// `outdegree` and `from` are used in loop locating
|
||||||
outdegree int
|
outdegree int
|
||||||
|
option *outboundgroup.GroupCommonOption
|
||||||
from []string
|
from []string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
graph := make(map[string]*graphNode)
|
graph := make(map[string]*graphNode)
|
||||||
|
|
||||||
// Step 1.1 build dependency graph
|
// Step 1.1 build dependency graph
|
||||||
for _, mapping := range groupsConfig {
|
for _, mapping := range groupsConfig {
|
||||||
option := &adapters.ProxyGroupOption{}
|
option := &outboundgroup.GroupCommonOption{}
|
||||||
err := decoder.Decode(mapping, option)
|
if err := decoder.Decode(mapping, option); err != nil {
|
||||||
groupName := option.Name
|
return fmt.Errorf("ProxyGroup %s: %s", option.Name, err.Error())
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("ProxyGroup %s: %s", groupName, err.Error())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
groupName := option.Name
|
||||||
if node, ok := graph[groupName]; ok {
|
if node, ok := graph[groupName]; ok {
|
||||||
if node.data != nil {
|
if node.data != nil {
|
||||||
return fmt.Errorf("ProxyGroup %s: duplicate group name", groupName)
|
return fmt.Errorf("ProxyGroup %s: duplicate group name", groupName)
|
||||||
}
|
}
|
||||||
node.data = mapping
|
node.data = mapping
|
||||||
|
node.option = option
|
||||||
} else {
|
} else {
|
||||||
graph[groupName] = &graphNode{0, -1, mapping, 0, nil}
|
graph[groupName] = &graphNode{0, -1, mapping, 0, option, nil}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, proxy := range option.Proxies {
|
for _, proxy := range option.Proxies {
|
||||||
if node, ex := graph[proxy]; ex {
|
if node, ex := graph[proxy]; ex {
|
||||||
node.indegree++
|
node.indegree++
|
||||||
} else {
|
} else {
|
||||||
graph[proxy] = &graphNode{1, -1, nil, 0, nil}
|
graph[proxy] = &graphNode{1, -1, nil, 0, nil, nil}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -95,14 +83,19 @@ func proxyGroupsDagSort(groupsConfig []map[string]interface{}, decoder *structur
|
|||||||
for ; len(queue) > 0; queue = queue[1:] {
|
for ; len(queue) > 0; queue = queue[1:] {
|
||||||
name := queue[0]
|
name := queue[0]
|
||||||
node := graph[name]
|
node := graph[name]
|
||||||
if node.data != nil {
|
if node.option != nil {
|
||||||
index++
|
index++
|
||||||
groupsConfig[len(groupsConfig)-index] = node.data
|
groupsConfig[len(groupsConfig)-index] = node.data
|
||||||
for _, proxy := range node.data["proxies"].([]interface{}) {
|
if len(node.option.Proxies) == 0 {
|
||||||
child := graph[proxy.(string)]
|
delete(graph, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, proxy := range node.option.Proxies {
|
||||||
|
child := graph[proxy]
|
||||||
child.indegree--
|
child.indegree--
|
||||||
if child.indegree == 0 {
|
if child.indegree == 0 {
|
||||||
queue = append(queue, proxy.(string))
|
queue = append(queue, proxy)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -117,12 +110,17 @@ func proxyGroupsDagSort(groupsConfig []map[string]interface{}, decoder *structur
|
|||||||
// if loop is detected, locate the loop and throw an error
|
// if loop is detected, locate the loop and throw an error
|
||||||
// Step 2.1 rebuild the graph, fill `outdegree` and `from` filed
|
// Step 2.1 rebuild the graph, fill `outdegree` and `from` filed
|
||||||
for name, node := range graph {
|
for name, node := range graph {
|
||||||
if node.data == nil {
|
if node.option == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for _, proxy := range node.data["proxies"].([]interface{}) {
|
|
||||||
|
if len(node.option.Proxies) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, proxy := range node.option.Proxies {
|
||||||
node.outdegree++
|
node.outdegree++
|
||||||
child := graph[proxy.(string)]
|
child := graph[proxy]
|
||||||
if child.from == nil {
|
if child.from == nil {
|
||||||
child.from = make([]string, 0, child.indegree)
|
child.from = make([]string, 0, child.indegree)
|
||||||
}
|
}
|
||||||
|
@ -61,7 +61,6 @@ type ProxyAdapter interface {
|
|||||||
DialContext(ctx context.Context, metadata *Metadata) (Conn, error)
|
DialContext(ctx context.Context, metadata *Metadata) (Conn, error)
|
||||||
DialUDP(metadata *Metadata) (PacketConn, net.Addr, error)
|
DialUDP(metadata *Metadata) (PacketConn, net.Addr, error)
|
||||||
SupportUDP() bool
|
SupportUDP() bool
|
||||||
Destroy()
|
|
||||||
MarshalJSON() ([]byte, error)
|
MarshalJSON() ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -110,3 +109,21 @@ func (at AdapterType) String() string {
|
|||||||
return "Unknown"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UDPPacket contains the data of UDP packet, and offers control/info of UDP packet's source
|
||||||
|
type UDPPacket interface {
|
||||||
|
// Data get the payload of UDP Packet
|
||||||
|
Data() []byte
|
||||||
|
|
||||||
|
// WriteBack writes the payload with source IP/Port equals addr
|
||||||
|
// - variable source IP/Port is important to STUN
|
||||||
|
// - if addr is not provided, WriteBack will wirte out UDP packet with SourceIP/Prot equals to origional Target,
|
||||||
|
// this is important when using Fake-IP.
|
||||||
|
WriteBack(b []byte, addr net.Addr) (n int, err error)
|
||||||
|
|
||||||
|
// Close closes the underlaying connection.
|
||||||
|
Close() error
|
||||||
|
|
||||||
|
// LocalAddr returns the source IP/Port of packet
|
||||||
|
LocalAddr() net.Addr
|
||||||
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package constant
|
package constant
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"net"
|
"net"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -14,6 +15,7 @@ const (
|
|||||||
UDP
|
UDP
|
||||||
|
|
||||||
HTTP Type = iota
|
HTTP Type = iota
|
||||||
|
HTTPCONNECT
|
||||||
SOCKS
|
SOCKS
|
||||||
REDIR
|
REDIR
|
||||||
)
|
)
|
||||||
@ -27,18 +29,41 @@ func (n *NetWork) String() string {
|
|||||||
return "udp"
|
return "udp"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (n NetWork) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(n.String())
|
||||||
|
}
|
||||||
|
|
||||||
type Type int
|
type Type int
|
||||||
|
|
||||||
|
func (t Type) String() string {
|
||||||
|
switch t {
|
||||||
|
case HTTP:
|
||||||
|
return "HTTP"
|
||||||
|
case HTTPCONNECT:
|
||||||
|
return "HTTP Connect"
|
||||||
|
case SOCKS:
|
||||||
|
return "Socks5"
|
||||||
|
case REDIR:
|
||||||
|
return "Redir"
|
||||||
|
default:
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t Type) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(t.String())
|
||||||
|
}
|
||||||
|
|
||||||
// Metadata is used to store connection address
|
// Metadata is used to store connection address
|
||||||
type Metadata struct {
|
type Metadata struct {
|
||||||
NetWork NetWork
|
NetWork NetWork `json:"network"`
|
||||||
Type Type
|
Type Type `json:"type"`
|
||||||
SrcIP *net.IP
|
SrcIP net.IP `json:"sourceIP"`
|
||||||
DstIP *net.IP
|
DstIP net.IP `json:"destinationIP"`
|
||||||
SrcPort string
|
SrcPort string `json:"sourcePort"`
|
||||||
DstPort string
|
DstPort string `json:"destinationPort"`
|
||||||
AddrType int
|
AddrType int `json:"-"`
|
||||||
Host string
|
Host string `json:"host"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Metadata) RemoteAddress() string {
|
func (m *Metadata) RemoteAddress() string {
|
||||||
|
@ -3,6 +3,7 @@ package constant
|
|||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
P "path"
|
P "path"
|
||||||
|
"path/filepath"
|
||||||
)
|
)
|
||||||
|
|
||||||
const Name = "clash"
|
const Name = "clash"
|
||||||
@ -11,32 +12,47 @@ const Name = "clash"
|
|||||||
var Path *path
|
var Path *path
|
||||||
|
|
||||||
type path struct {
|
type path struct {
|
||||||
homedir string
|
homeDir string
|
||||||
|
configFile string
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
homedir, err := os.UserHomeDir()
|
homeDir, err := os.UserHomeDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
homedir, _ = os.Getwd()
|
homeDir, _ = os.Getwd()
|
||||||
}
|
}
|
||||||
|
|
||||||
homedir = P.Join(homedir, ".config", Name)
|
homeDir = P.Join(homeDir, ".config", Name)
|
||||||
Path = &path{homedir: homedir}
|
Path = &path{homeDir: homeDir, configFile: "config.yaml"}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetHomeDir is used to set the configuration path
|
// SetHomeDir is used to set the configuration path
|
||||||
func SetHomeDir(root string) {
|
func SetHomeDir(root string) {
|
||||||
Path = &path{homedir: root}
|
Path.homeDir = root
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetConfig is used to set the configuration file
|
||||||
|
func SetConfig(file string) {
|
||||||
|
Path.configFile = file
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) HomeDir() string {
|
func (p *path) HomeDir() string {
|
||||||
return p.homedir
|
return p.homeDir
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) Config() string {
|
func (p *path) Config() string {
|
||||||
return P.Join(p.homedir, "config.yaml")
|
return p.configFile
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reslove return a absolute path or a relative path with homedir
|
||||||
|
func (p *path) Reslove(path string) string {
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
return filepath.Join(p.HomeDir(), path)
|
||||||
|
}
|
||||||
|
|
||||||
|
return path
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *path) MMDB() string {
|
func (p *path) MMDB() string {
|
||||||
return P.Join(p.homedir, "Country.mmdb")
|
return P.Join(p.homeDir, "Country.mmdb")
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ func (rt RuleType) String() string {
|
|||||||
case DomainKeyword:
|
case DomainKeyword:
|
||||||
return "DomainKeyword"
|
return "DomainKeyword"
|
||||||
case GEOIP:
|
case GEOIP:
|
||||||
return "GEOIP"
|
return "GeoIP"
|
||||||
case IPCIDR:
|
case IPCIDR:
|
||||||
return "IPCIDR"
|
return "IPCIDR"
|
||||||
case SrcIPCIDR:
|
case SrcIPCIDR:
|
||||||
@ -34,7 +34,7 @@ func (rt RuleType) String() string {
|
|||||||
case DstPort:
|
case DstPort:
|
||||||
return "DstPort"
|
return "DstPort"
|
||||||
case MATCH:
|
case MATCH:
|
||||||
return "MATCH"
|
return "Match"
|
||||||
default:
|
default:
|
||||||
return "Unknown"
|
return "Unknown"
|
||||||
}
|
}
|
||||||
@ -42,7 +42,8 @@ func (rt RuleType) String() string {
|
|||||||
|
|
||||||
type Rule interface {
|
type Rule interface {
|
||||||
RuleType() RuleType
|
RuleType() RuleType
|
||||||
IsMatch(metadata *Metadata) bool
|
Match(metadata *Metadata) bool
|
||||||
Adapter() string
|
Adapter() string
|
||||||
Payload() string
|
Payload() string
|
||||||
|
NoResolveIP() bool
|
||||||
}
|
}
|
||||||
|
@ -1,55 +0,0 @@
|
|||||||
package constant
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Traffic struct {
|
|
||||||
up chan int64
|
|
||||||
down chan int64
|
|
||||||
upCount int64
|
|
||||||
downCount int64
|
|
||||||
upTotal int64
|
|
||||||
downTotal int64
|
|
||||||
interval time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) Up() chan<- int64 {
|
|
||||||
return t.up
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) Down() chan<- int64 {
|
|
||||||
return t.down
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) Now() (up int64, down int64) {
|
|
||||||
return t.upTotal, t.downTotal
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) handle() {
|
|
||||||
go t.handleCh(t.up, &t.upCount, &t.upTotal)
|
|
||||||
go t.handleCh(t.down, &t.downCount, &t.downTotal)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *Traffic) handleCh(ch <-chan int64, count *int64, total *int64) {
|
|
||||||
ticker := time.NewTicker(t.interval)
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case n := <-ch:
|
|
||||||
*count += n
|
|
||||||
case <-ticker.C:
|
|
||||||
*total = *count
|
|
||||||
*count = 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTraffic(interval time.Duration) *Traffic {
|
|
||||||
t := &Traffic{
|
|
||||||
up: make(chan int64),
|
|
||||||
down: make(chan int64),
|
|
||||||
interval: interval,
|
|
||||||
}
|
|
||||||
go t.handle()
|
|
||||||
return t
|
|
||||||
}
|
|
@ -13,9 +13,6 @@ import (
|
|||||||
const (
|
const (
|
||||||
// dotMimeType is the DoH mimetype that should be used.
|
// dotMimeType is the DoH mimetype that should be used.
|
||||||
dotMimeType = "application/dns-message"
|
dotMimeType = "application/dns-message"
|
||||||
|
|
||||||
// dotPath is the URL path that should be used.
|
|
||||||
dotPath = "/dns-query"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var dohTransport = &http.Transport{
|
var dohTransport = &http.Transport{
|
||||||
|
@ -7,7 +7,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errIPNotFound = errors.New("cannot found ip")
|
errIPNotFound = errors.New("couldn't find ip")
|
||||||
errIPVersion = errors.New("ip version error")
|
errIPVersion = errors.New("ip version error")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -26,6 +26,10 @@ func withFakeIP(fakePool *fakeip.Pool) middleware {
|
|||||||
}
|
}
|
||||||
|
|
||||||
host := strings.TrimRight(q.Name, ".")
|
host := strings.TrimRight(q.Name, ".")
|
||||||
|
if fakePool.LookupHost(host) {
|
||||||
|
next(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
rr := &D.A{}
|
rr := &D.A{}
|
||||||
rr.Hdr = D.RR_Header{Name: q.Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: dnsDefaultTTL}
|
rr.Hdr = D.RR_Header{Name: q.Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: dnsDefaultTTL}
|
||||||
@ -71,7 +75,7 @@ func compose(middlewares []middleware, endpoint handler) handler {
|
|||||||
func newHandler(resolver *Resolver) handler {
|
func newHandler(resolver *Resolver) handler {
|
||||||
middlewares := []middleware{}
|
middlewares := []middleware{}
|
||||||
|
|
||||||
if resolver.IsFakeIP() {
|
if resolver.FakeIPEnabled() {
|
||||||
middlewares = append(middlewares, withFakeIP(resolver.pool))
|
middlewares = append(middlewares, withFakeIP(resolver.pool))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -166,10 +166,19 @@ func (r *Resolver) IsMapping() bool {
|
|||||||
return r.mapping
|
return r.mapping
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Resolver) IsFakeIP() bool {
|
// FakeIPEnabled returns if fake-ip is enabled
|
||||||
|
func (r *Resolver) FakeIPEnabled() bool {
|
||||||
return r.fakeip
|
return r.fakeip
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsFakeIP determine if given ip is a fake-ip
|
||||||
|
func (r *Resolver) IsFakeIP(ip net.IP) bool {
|
||||||
|
if r.FakeIPEnabled() {
|
||||||
|
return r.pool.Exist(ip)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func (r *Resolver) batchExchange(clients []resolver, m *D.Msg) (msg *D.Msg, err error) {
|
func (r *Resolver) batchExchange(clients []resolver, m *D.Msg) (msg *D.Msg, err error) {
|
||||||
fast, ctx := picker.WithTimeout(context.Background(), time.Second)
|
fast, ctx := picker.WithTimeout(context.Background(), time.Second)
|
||||||
for _, client := range clients {
|
for _, client := range clients {
|
||||||
|
@ -81,13 +81,14 @@ func (e EnhancedMode) String() string {
|
|||||||
|
|
||||||
func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) {
|
func putMsgToCache(c *cache.Cache, key string, msg *D.Msg) {
|
||||||
var ttl time.Duration
|
var ttl time.Duration
|
||||||
if len(msg.Answer) != 0 {
|
switch {
|
||||||
|
case len(msg.Answer) != 0:
|
||||||
ttl = time.Duration(msg.Answer[0].Header().Ttl) * time.Second
|
ttl = time.Duration(msg.Answer[0].Header().Ttl) * time.Second
|
||||||
} else if len(msg.Ns) != 0 {
|
case len(msg.Ns) != 0:
|
||||||
ttl = time.Duration(msg.Ns[0].Header().Ttl) * time.Second
|
ttl = time.Duration(msg.Ns[0].Header().Ttl) * time.Second
|
||||||
} else if len(msg.Extra) != 0 {
|
case len(msg.Extra) != 0:
|
||||||
ttl = time.Duration(msg.Extra[0].Header().Ttl) * time.Second
|
ttl = time.Duration(msg.Extra[0].Header().Ttl) * time.Second
|
||||||
} else {
|
default:
|
||||||
log.Debugln("[DNS] response msg error: %#v", msg)
|
log.Debugln("[DNS] response msg error: %#v", msg)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
10
go.mod
10
go.mod
@ -3,21 +3,21 @@ module github.com/Dreamacro/clash
|
|||||||
go 1.13
|
go 1.13
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/Dreamacro/go-shadowsocks2 v0.1.5-0.20191012162057-46254afc8b68
|
github.com/Dreamacro/go-shadowsocks2 v0.1.5
|
||||||
github.com/eapache/queue v1.1.0 // indirect
|
github.com/eapache/queue v1.1.0 // indirect
|
||||||
github.com/go-chi/chi v4.0.2+incompatible
|
github.com/go-chi/chi v4.0.2+incompatible
|
||||||
github.com/go-chi/cors v1.0.0
|
github.com/go-chi/cors v1.0.0
|
||||||
github.com/go-chi/render v1.0.1
|
github.com/go-chi/render v1.0.1
|
||||||
github.com/gofrs/uuid v3.2.0+incompatible
|
github.com/gofrs/uuid v3.2.0+incompatible
|
||||||
github.com/gorilla/websocket v1.4.1
|
github.com/gorilla/websocket v1.4.1
|
||||||
github.com/miekg/dns v1.1.22
|
github.com/miekg/dns v1.1.24
|
||||||
github.com/oschwald/geoip2-golang v1.3.0
|
github.com/oschwald/geoip2-golang v1.3.0
|
||||||
github.com/oschwald/maxminddb-golang v1.5.0 // indirect
|
github.com/oschwald/maxminddb-golang v1.5.0 // indirect
|
||||||
github.com/sirupsen/logrus v1.4.2
|
github.com/sirupsen/logrus v1.4.2
|
||||||
github.com/stretchr/testify v1.4.0
|
github.com/stretchr/testify v1.4.0
|
||||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550
|
golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413
|
||||||
golang.org/x/net v0.0.0-20191011234655-491137f69257
|
golang.org/x/net v0.0.0-20191207000613-e7e4b65ae663
|
||||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e
|
||||||
gopkg.in/eapache/channels.v1 v1.1.0
|
gopkg.in/eapache/channels.v1 v1.1.0
|
||||||
gopkg.in/yaml.v2 v2.2.2
|
gopkg.in/yaml.v2 v2.2.7
|
||||||
)
|
)
|
||||||
|
20
go.sum
20
go.sum
@ -1,7 +1,5 @@
|
|||||||
github.com/Dreamacro/go-shadowsocks2 v0.1.5-0.20191012162057-46254afc8b68 h1:UBDLpj1IGVkUcUBuZWE6DmZApPTZcnmcV6AfyDN/yhg=
|
github.com/Dreamacro/go-shadowsocks2 v0.1.5 h1:BizWSjmwzAyQoslz6YhJYMiAGT99j9cnm9zlxVr+kyI=
|
||||||
github.com/Dreamacro/go-shadowsocks2 v0.1.5-0.20191012162057-46254afc8b68/go.mod h1:Y8obOtHDOqxMGHjPglfCiXZBKExOA9VL6I6sJagOwYM=
|
github.com/Dreamacro/go-shadowsocks2 v0.1.5/go.mod h1:LSXCjyHesPY3pLjhwff1mQX72ItcBT/N2xNC685cYeU=
|
||||||
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:KjTM2ks9d14ZYCvmHS9iAKVt9AyzRSqNU1qabPih5BY=
|
|
||||||
github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA=
|
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
@ -19,8 +17,8 @@ github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvK
|
|||||||
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||||
github.com/miekg/dns v1.1.22 h1:Jm64b3bO9kP43ddLjL2EY3Io6bmy1qGb9Xxz6TqS6rc=
|
github.com/miekg/dns v1.1.24 h1:6G8Eop/HM8hpagajbn0rFQvAKZWiiCa8P6N2I07+wwI=
|
||||||
github.com/miekg/dns v1.1.22/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso=
|
github.com/miekg/dns v1.1.24/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso=
|
||||||
github.com/oschwald/geoip2-golang v1.3.0 h1:D+Hsdos1NARPbzZ2aInUHZL+dApIzo8E0ErJVsWcku8=
|
github.com/oschwald/geoip2-golang v1.3.0 h1:D+Hsdos1NARPbzZ2aInUHZL+dApIzo8E0ErJVsWcku8=
|
||||||
github.com/oschwald/geoip2-golang v1.3.0/go.mod h1:0LTTzix/Ao1uMvOhAV4iLU0Lz7eCrP94qZWBTDKf0iE=
|
github.com/oschwald/geoip2-golang v1.3.0/go.mod h1:0LTTzix/Ao1uMvOhAV4iLU0Lz7eCrP94qZWBTDKf0iE=
|
||||||
github.com/oschwald/maxminddb-golang v1.5.0 h1:rmyoIV6z2/s9TCJedUuDiKht2RN12LWJ1L7iRGtWY64=
|
github.com/oschwald/maxminddb-golang v1.5.0 h1:rmyoIV6z2/s9TCJedUuDiKht2RN12LWJ1L7iRGtWY64=
|
||||||
@ -39,15 +37,15 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
|
|||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392 h1:ACG4HJsFiNMf47Y4PeRoebLNy/2lXT9EtprMuTFWt1M=
|
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392 h1:ACG4HJsFiNMf47Y4PeRoebLNy/2lXT9EtprMuTFWt1M=
|
||||||
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY=
|
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY=
|
||||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=
|
golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413 h1:ULYEB3JvPRE/IfO+9uO7vKV/xzVTO7XPAwm8xbf4w2g=
|
||||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/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-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g=
|
golang.org/x/net v0.0.0-20190923162816-aa69164e4478 h1:l5EDrHhldLYb3ZRHDUhXF7Om7MvYXnkV9/iQNo1lX6g=
|
||||||
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20191011234655-491137f69257 h1:ry8e2D+cwaV6hk7lb3aRTjjZo24shrbK0e11QEOkTIg=
|
golang.org/x/net v0.0.0-20191207000613-e7e4b65ae663 h1:Dd5RoEW+yQi+9DMybroBctIdyiwuNT7sJFMC27/6KxI=
|
||||||
golang.org/x/net v0.0.0-20191011234655-491137f69257/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20191207000613-e7e4b65ae663/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/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-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
|
||||||
@ -71,3 +69,5 @@ gopkg.in/eapache/channels.v1 v1.1.0 h1:5bGAyKKvyCTWjSj7mhefG6Lc68VyN4MH1v8/7Ooee
|
|||||||
gopkg.in/eapache/channels.v1 v1.1.0/go.mod h1:BHIBujSvu9yMTrTYbTCjDD43gUhtmaOtTWDe7sTv1js=
|
gopkg.in/eapache/channels.v1 v1.1.0/go.mod h1:BHIBujSvu9yMTrTYbTCjDD43gUhtmaOtTWDe7sTv1js=
|
||||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo=
|
||||||
|
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
@ -1,6 +1,12 @@
|
|||||||
package executor
|
package executor
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
"github.com/Dreamacro/clash/component/auth"
|
"github.com/Dreamacro/clash/component/auth"
|
||||||
trie "github.com/Dreamacro/clash/component/domain-trie"
|
trie "github.com/Dreamacro/clash/component/domain-trie"
|
||||||
"github.com/Dreamacro/clash/config"
|
"github.com/Dreamacro/clash/config"
|
||||||
@ -12,6 +18,41 @@ import (
|
|||||||
T "github.com/Dreamacro/clash/tunnel"
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// forward compatibility before 1.0
|
||||||
|
func readRawConfig(path string) ([]byte, error) {
|
||||||
|
data, err := ioutil.ReadFile(path)
|
||||||
|
if err == nil && len(data) != 0 {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if filepath.Ext(path) != ".yaml" {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
path = path[:len(path)-5] + ".yml"
|
||||||
|
if _, fallbackErr := os.Stat(path); fallbackErr == nil {
|
||||||
|
return ioutil.ReadFile(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
return data, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func readConfig(path string) ([]byte, error) {
|
||||||
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
data, err := readRawConfig(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(data) == 0 {
|
||||||
|
return nil, fmt.Errorf("Configuration file %s is empty", path)
|
||||||
|
}
|
||||||
|
|
||||||
|
return data, err
|
||||||
|
}
|
||||||
|
|
||||||
// Parse config with default config path
|
// Parse config with default config path
|
||||||
func Parse() (*config.Config, error) {
|
func Parse() (*config.Config, error) {
|
||||||
return ParseWithPath(C.Path.Config())
|
return ParseWithPath(C.Path.Config())
|
||||||
@ -19,7 +60,17 @@ func Parse() (*config.Config, error) {
|
|||||||
|
|
||||||
// ParseWithPath parse config with custom config path
|
// ParseWithPath parse config with custom config path
|
||||||
func ParseWithPath(path string) (*config.Config, error) {
|
func ParseWithPath(path string) (*config.Config, error) {
|
||||||
return config.Parse(path)
|
buf, err := readConfig(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return ParseWithBytes(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseWithBytes config with buffer
|
||||||
|
func ParseWithBytes(buf []byte) (*config.Config, error) {
|
||||||
|
return config.Parse(buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ApplyConfig dispatch configure to all parts
|
// ApplyConfig dispatch configure to all parts
|
||||||
@ -28,7 +79,7 @@ func ApplyConfig(cfg *config.Config, force bool) {
|
|||||||
if force {
|
if force {
|
||||||
updateGeneral(cfg.General)
|
updateGeneral(cfg.General)
|
||||||
}
|
}
|
||||||
updateProxies(cfg.Proxies)
|
updateProxies(cfg.Proxies, cfg.Providers)
|
||||||
updateRules(cfg.Rules)
|
updateRules(cfg.Rules)
|
||||||
updateDNS(cfg.DNS)
|
updateDNS(cfg.DNS)
|
||||||
updateHosts(cfg.Hosts)
|
updateHosts(cfg.Hosts)
|
||||||
@ -92,16 +143,16 @@ func updateHosts(tree *trie.Trie) {
|
|||||||
dns.DefaultHosts = tree
|
dns.DefaultHosts = tree
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateProxies(proxies map[string]C.Proxy) {
|
func updateProxies(proxies map[string]C.Proxy, providers map[string]provider.ProxyProvider) {
|
||||||
tunnel := T.Instance()
|
tunnel := T.Instance()
|
||||||
oldProxies := tunnel.Proxies()
|
oldProviders := tunnel.Providers()
|
||||||
|
|
||||||
// close proxy group goroutine
|
// close providers goroutine
|
||||||
for _, proxy := range oldProxies {
|
for _, provider := range oldProviders {
|
||||||
proxy.Destroy()
|
provider.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
tunnel.UpdateProxies(proxies)
|
tunnel.UpdateProxies(proxies, providers)
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateRules(rules []C.Rule) {
|
func updateRules(rules []C.Rule) {
|
||||||
|
17
hub/route/common.go
Normal file
17
hub/route/common.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package route
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi"
|
||||||
|
)
|
||||||
|
|
||||||
|
// When name is composed of a partial escape string, Golang does not unescape it
|
||||||
|
func getEscapeParam(r *http.Request, paramName string) string {
|
||||||
|
param := chi.URLParam(r, paramName)
|
||||||
|
if newParam, err := url.PathUnescape(param); err == nil {
|
||||||
|
param = newParam
|
||||||
|
}
|
||||||
|
return param
|
||||||
|
}
|
@ -4,6 +4,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/config"
|
||||||
"github.com/Dreamacro/clash/hub/executor"
|
"github.com/Dreamacro/clash/hub/executor"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
P "github.com/Dreamacro/clash/proxy"
|
P "github.com/Dreamacro/clash/proxy"
|
||||||
@ -78,6 +79,7 @@ func patchConfigs(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
type updateConfigRequest struct {
|
type updateConfigRequest struct {
|
||||||
Path string `json:"path"`
|
Path string `json:"path"`
|
||||||
|
Payload string `json:"payload"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateConfigs(w http.ResponseWriter, r *http.Request) {
|
func updateConfigs(w http.ResponseWriter, r *http.Request) {
|
||||||
@ -88,19 +90,31 @@ func updateConfigs(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
force := r.URL.Query().Get("force") == "true"
|
||||||
|
var cfg *config.Config
|
||||||
|
var err error
|
||||||
|
|
||||||
|
if req.Payload != "" {
|
||||||
|
cfg, err = executor.ParseWithBytes([]byte(req.Payload))
|
||||||
|
if err != nil {
|
||||||
|
render.Status(r, http.StatusBadRequest)
|
||||||
|
render.JSON(w, r, newError(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
if !filepath.IsAbs(req.Path) {
|
if !filepath.IsAbs(req.Path) {
|
||||||
render.Status(r, http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.JSON(w, r, newError("path is not a absoluted path"))
|
render.JSON(w, r, newError("path is not a absoluted path"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
force := r.URL.Query().Get("force") == "true"
|
cfg, err = executor.ParseWithPath(req.Path)
|
||||||
cfg, err := executor.ParseWithPath(req.Path)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
render.Status(r, http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.JSON(w, r, newError(err.Error()))
|
render.JSON(w, r, newError(err.Error()))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
executor.ApplyConfig(cfg, force)
|
executor.ApplyConfig(cfg, force)
|
||||||
render.NoContent(w, r)
|
render.NoContent(w, r)
|
||||||
|
91
hub/route/connections.go
Normal file
91
hub/route/connections.go
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
package route
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi"
|
||||||
|
"github.com/go-chi/render"
|
||||||
|
)
|
||||||
|
|
||||||
|
func connectionRouter() http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Get("/", getConnections)
|
||||||
|
r.Delete("/", closeAllConnections)
|
||||||
|
r.Delete("/{id}", closeConnection)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func getConnections(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !websocket.IsWebSocketUpgrade(r) {
|
||||||
|
snapshot := T.DefaultManager.Snapshot()
|
||||||
|
render.JSON(w, r, snapshot)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := upgrader.Upgrade(w, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
intervalStr := r.URL.Query().Get("interval")
|
||||||
|
interval := 1000
|
||||||
|
if intervalStr != "" {
|
||||||
|
t, err := strconv.Atoi(intervalStr)
|
||||||
|
if err != nil {
|
||||||
|
render.Status(r, http.StatusBadRequest)
|
||||||
|
render.JSON(w, r, ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
interval = t
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
sendSnapshot := func() error {
|
||||||
|
buf.Reset()
|
||||||
|
snapshot := T.DefaultManager.Snapshot()
|
||||||
|
if err := json.NewEncoder(buf).Encode(snapshot); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return conn.WriteMessage(websocket.TextMessage, buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := sendSnapshot(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tick := time.NewTicker(time.Millisecond * time.Duration(interval))
|
||||||
|
for range tick.C {
|
||||||
|
if err := sendSnapshot(); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeConnection(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id := chi.URLParam(r, "id")
|
||||||
|
snapshot := T.DefaultManager.Snapshot()
|
||||||
|
for _, c := range snapshot.Connections {
|
||||||
|
if id == c.ID() {
|
||||||
|
c.Close()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
render.NoContent(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeAllConnections(w http.ResponseWriter, r *http.Request) {
|
||||||
|
snapshot := T.DefaultManager.Snapshot()
|
||||||
|
for _, c := range snapshot.Connections {
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
render.NoContent(w, r)
|
||||||
|
}
|
@ -2,7 +2,9 @@ package route
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
CtxKeyProxyName = contextKey("proxy name")
|
CtxKeyProxyName = contextKey("proxy name")
|
||||||
|
CtxKeyProviderName = contextKey("provider name")
|
||||||
CtxKeyProxy = contextKey("proxy")
|
CtxKeyProxy = contextKey("proxy")
|
||||||
|
CtxKeyProvider = contextKey("provider")
|
||||||
)
|
)
|
||||||
|
|
||||||
type contextKey string
|
type contextKey string
|
||||||
|
77
hub/route/provider.go
Normal file
77
hub/route/provider.go
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
package route
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi"
|
||||||
|
"github.com/go-chi/render"
|
||||||
|
)
|
||||||
|
|
||||||
|
func proxyProviderRouter() http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Get("/", getProviders)
|
||||||
|
|
||||||
|
r.Route("/{name}", func(r chi.Router) {
|
||||||
|
r.Use(parseProviderName, findProviderByName)
|
||||||
|
r.Get("/", getProvider)
|
||||||
|
r.Put("/", updateProvider)
|
||||||
|
r.Get("/healthcheck", healthCheckProvider)
|
||||||
|
})
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProviders(w http.ResponseWriter, r *http.Request) {
|
||||||
|
providers := T.Instance().Providers()
|
||||||
|
render.JSON(w, r, render.M{
|
||||||
|
"providers": providers,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func getProvider(w http.ResponseWriter, r *http.Request) {
|
||||||
|
provider := r.Context().Value(CtxKeyProvider).(provider.ProxyProvider)
|
||||||
|
render.JSON(w, r, provider)
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateProvider(w http.ResponseWriter, r *http.Request) {
|
||||||
|
provider := r.Context().Value(CtxKeyProvider).(provider.ProxyProvider)
|
||||||
|
if err := provider.Update(); err != nil {
|
||||||
|
render.Status(r, http.StatusServiceUnavailable)
|
||||||
|
render.JSON(w, r, newError(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
render.NoContent(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func healthCheckProvider(w http.ResponseWriter, r *http.Request) {
|
||||||
|
provider := r.Context().Value(CtxKeyProvider).(provider.ProxyProvider)
|
||||||
|
provider.HealthCheck()
|
||||||
|
render.NoContent(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseProviderName(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
name := getEscapeParam(r, "name")
|
||||||
|
ctx := context.WithValue(r.Context(), CtxKeyProviderName, name)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func findProviderByName(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
name := r.Context().Value(CtxKeyProviderName).(string)
|
||||||
|
providers := T.Instance().Providers()
|
||||||
|
provider, exist := providers[name]
|
||||||
|
if !exist {
|
||||||
|
render.Status(r, http.StatusNotFound)
|
||||||
|
render.JSON(w, r, ErrNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.WithValue(r.Context(), CtxKeyProvider, provider)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
@ -4,11 +4,11 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
A "github.com/Dreamacro/clash/adapters/outbound"
|
"github.com/Dreamacro/clash/adapters/outbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/outboundgroup"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
T "github.com/Dreamacro/clash/tunnel"
|
T "github.com/Dreamacro/clash/tunnel"
|
||||||
|
|
||||||
@ -29,13 +29,9 @@ func proxyRouter() http.Handler {
|
|||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
// When name is composed of a partial escape string, Golang does not unescape it
|
|
||||||
func parseProxyName(next http.Handler) http.Handler {
|
func parseProxyName(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
name := chi.URLParam(r, "name")
|
name := getEscapeParam(r, "name")
|
||||||
if newName, err := url.PathUnescape(name); err == nil {
|
|
||||||
name = newName
|
|
||||||
}
|
|
||||||
ctx := context.WithValue(r.Context(), CtxKeyProxyName, name)
|
ctx := context.WithValue(r.Context(), CtxKeyProxyName, name)
|
||||||
next.ServeHTTP(w, r.WithContext(ctx))
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
})
|
})
|
||||||
@ -81,8 +77,8 @@ func updateProxy(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
proxy := r.Context().Value(CtxKeyProxy).(*A.Proxy)
|
proxy := r.Context().Value(CtxKeyProxy).(*outbound.Proxy)
|
||||||
selector, ok := proxy.ProxyAdapter.(*A.Selector)
|
selector, ok := proxy.ProxyAdapter.(*outboundgroup.Selector)
|
||||||
if !ok {
|
if !ok {
|
||||||
render.Status(r, http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
render.JSON(w, r, newError("Must be a Selector"))
|
render.JSON(w, r, newError("Must be a Selector"))
|
||||||
|
@ -67,6 +67,8 @@ func Start(addr string, secret string) {
|
|||||||
r.Mount("/configs", configRouter())
|
r.Mount("/configs", configRouter())
|
||||||
r.Mount("/proxies", proxyRouter())
|
r.Mount("/proxies", proxyRouter())
|
||||||
r.Mount("/rules", ruleRouter())
|
r.Mount("/rules", ruleRouter())
|
||||||
|
r.Mount("/connections", connectionRouter())
|
||||||
|
r.Mount("/providers/proxies", proxyProviderRouter())
|
||||||
})
|
})
|
||||||
|
|
||||||
if uiPath != "" {
|
if uiPath != "" {
|
||||||
@ -140,7 +142,7 @@ func traffic(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
tick := time.NewTicker(time.Second)
|
tick := time.NewTicker(time.Second)
|
||||||
t := T.Instance().Traffic()
|
t := T.DefaultManager
|
||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
var err error
|
var err error
|
||||||
for range tick.C {
|
for range tick.C {
|
||||||
|
32
main.go
32
main.go
@ -12,17 +12,18 @@ import (
|
|||||||
"github.com/Dreamacro/clash/config"
|
"github.com/Dreamacro/clash/config"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/hub"
|
"github.com/Dreamacro/clash/hub"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
version bool
|
version bool
|
||||||
homedir string
|
homeDir string
|
||||||
|
configFile string
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
flag.StringVar(&homedir, "d", "", "set configuration directory")
|
flag.StringVar(&homeDir, "d", "", "set configuration directory")
|
||||||
|
flag.StringVar(&configFile, "f", "", "specify configuration file")
|
||||||
flag.BoolVar(&version, "v", false, "show current version of clash")
|
flag.BoolVar(&version, "v", false, "show current version of clash")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
}
|
}
|
||||||
@ -33,20 +34,31 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if homedir != "" {
|
if homeDir != "" {
|
||||||
if !filepath.IsAbs(homedir) {
|
if !filepath.IsAbs(homeDir) {
|
||||||
currentDir, _ := os.Getwd()
|
currentDir, _ := os.Getwd()
|
||||||
homedir = filepath.Join(currentDir, homedir)
|
homeDir = filepath.Join(currentDir, homeDir)
|
||||||
}
|
}
|
||||||
C.SetHomeDir(homedir)
|
C.SetHomeDir(homeDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
if configFile != "" {
|
||||||
|
if !filepath.IsAbs(configFile) {
|
||||||
|
currentDir, _ := os.Getwd()
|
||||||
|
configFile = filepath.Join(currentDir, configFile)
|
||||||
|
}
|
||||||
|
C.SetConfig(configFile)
|
||||||
|
} else {
|
||||||
|
configFile := filepath.Join(C.Path.HomeDir(), C.Path.Config())
|
||||||
|
C.SetConfig(configFile)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := config.Init(C.Path.HomeDir()); err != nil {
|
if err := config.Init(C.Path.HomeDir()); err != nil {
|
||||||
log.Fatalf("Initial configuration directory error: %s", err.Error())
|
log.Fatalln("Initial configuration directory error: %s", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := hub.Parse(); err != nil {
|
if err := hub.Parse(); err != nil {
|
||||||
log.Fatalf("Parse config error: %s", err.Error())
|
log.Fatalln("Parse config error: %s", err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
sigCh := make(chan os.Signal, 1)
|
sigCh := make(chan os.Signal, 1)
|
||||||
|
@ -74,42 +74,49 @@ func ReCreateHTTP(port int) error {
|
|||||||
func ReCreateSocks(port int) error {
|
func ReCreateSocks(port int) error {
|
||||||
addr := genAddr(bindAddress, port, allowLan)
|
addr := genAddr(bindAddress, port, allowLan)
|
||||||
|
|
||||||
|
shouldTCPIgnore := false
|
||||||
|
shouldUDPIgnore := false
|
||||||
|
|
||||||
if socksListener != nil {
|
if socksListener != nil {
|
||||||
if socksListener.Address() == addr {
|
if socksListener.Address() != addr {
|
||||||
return nil
|
|
||||||
}
|
|
||||||
socksListener.Close()
|
socksListener.Close()
|
||||||
socksListener = nil
|
socksListener = nil
|
||||||
|
} else {
|
||||||
|
shouldTCPIgnore = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if socksUDPListener != nil {
|
||||||
|
if socksUDPListener.Address() != addr {
|
||||||
|
socksUDPListener.Close()
|
||||||
|
socksUDPListener = nil
|
||||||
|
} else {
|
||||||
|
shouldUDPIgnore = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if shouldTCPIgnore && shouldUDPIgnore {
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if portIsZero(addr) {
|
if portIsZero(addr) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
tcpListener, err := socks.NewSocksProxy(addr)
|
||||||
socksListener, err = socks.NewSocksProxy(addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return reCreateSocksUDP(addr)
|
udpListener, err := socks.NewSocksUDPProxy(addr)
|
||||||
}
|
|
||||||
|
|
||||||
func reCreateSocksUDP(addr string) error {
|
|
||||||
if socksUDPListener != nil {
|
|
||||||
if socksUDPListener.Address() == addr {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
socksUDPListener.Close()
|
|
||||||
socksUDPListener = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
|
||||||
socksUDPListener, err = socks.NewSocksUDPProxy(addr)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
tcpListener.Close()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
socksListener = tcpListener
|
||||||
|
socksUDPListener = udpListener
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -59,5 +59,5 @@ func handleRedir(conn net.Conn) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
conn.(*net.TCPConn).SetKeepAlive(true)
|
conn.(*net.TCPConn).SetKeepAlive(true)
|
||||||
tun.Add(adapters.NewSocket(target, conn, C.REDIR, C.TCP))
|
tun.Add(inbound.NewSocket(target, conn, C.REDIR, C.TCP))
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package socks
|
package socks
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
||||||
@ -57,12 +56,12 @@ func handleSocksUDP(pc net.PacketConn, buf []byte, addr net.Addr) {
|
|||||||
pool.BufPool.Put(buf[:cap(buf)])
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
conn := &fakeConn{
|
packet := &fakeConn{
|
||||||
PacketConn: pc,
|
PacketConn: pc,
|
||||||
remoteAddr: addr,
|
remoteAddr: addr,
|
||||||
targetAddr: target,
|
targetAddr: target,
|
||||||
buffer: bytes.NewBuffer(payload),
|
payload: payload,
|
||||||
bufRef: buf,
|
bufRef: buf,
|
||||||
}
|
}
|
||||||
tun.Add(adapters.NewSocket(target, conn, C.SOCKS, C.UDP))
|
tun.AddPacket(adapters.NewPacket(target, packet, C.SOCKS, C.UDP))
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package socks
|
package socks
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
@ -12,23 +11,30 @@ type fakeConn struct {
|
|||||||
net.PacketConn
|
net.PacketConn
|
||||||
remoteAddr net.Addr
|
remoteAddr net.Addr
|
||||||
targetAddr socks5.Addr
|
targetAddr socks5.Addr
|
||||||
buffer *bytes.Buffer
|
payload []byte
|
||||||
bufRef []byte
|
bufRef []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *fakeConn) Read(b []byte) (n int, err error) {
|
func (c *fakeConn) Data() []byte {
|
||||||
return c.buffer.Read(b)
|
return c.payload
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *fakeConn) Write(b []byte) (n int, err error) {
|
// WriteBack wirtes UDP packet with source(ip, port) = `addr`
|
||||||
packet, err := socks5.EncodeUDPPacket(c.targetAddr, b)
|
func (c *fakeConn) WriteBack(b []byte, addr net.Addr) (n int, err error) {
|
||||||
|
from := c.targetAddr
|
||||||
|
if addr != nil {
|
||||||
|
// if addr is provided, use the parsed addr
|
||||||
|
from = socks5.ParseAddrToSocksAddr(addr)
|
||||||
|
}
|
||||||
|
packet, err := socks5.EncodeUDPPacket(from, b)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
return c.PacketConn.WriteTo(packet, c.remoteAddr)
|
return c.PacketConn.WriteTo(packet, c.remoteAddr)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *fakeConn) RemoteAddr() net.Addr {
|
// LocalAddr returns the source IP/Port of UDP Packet
|
||||||
|
func (c *fakeConn) LocalAddr() net.Addr {
|
||||||
return c.remoteAddr
|
return c.remoteAddr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
21
rules/base.go
Normal file
21
rules/base.go
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package rules
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errPayload = errors.New("payload error")
|
||||||
|
errParams = errors.New("params error")
|
||||||
|
|
||||||
|
noResolve = "no-resolve"
|
||||||
|
)
|
||||||
|
|
||||||
|
func HasNoResolve(params []string) bool {
|
||||||
|
for _, p := range params {
|
||||||
|
if p == noResolve {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
@ -15,7 +15,7 @@ func (d *Domain) RuleType() C.RuleType {
|
|||||||
return C.Domain
|
return C.Domain
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Domain) IsMatch(metadata *C.Metadata) bool {
|
func (d *Domain) Match(metadata *C.Metadata) bool {
|
||||||
if metadata.AddrType != C.AtypDomainName {
|
if metadata.AddrType != C.AtypDomainName {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@ -30,6 +30,10 @@ func (d *Domain) Payload() string {
|
|||||||
return d.domain
|
return d.domain
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *Domain) NoResolveIP() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func NewDomain(domain string, adapter string) *Domain {
|
func NewDomain(domain string, adapter string) *Domain {
|
||||||
return &Domain{
|
return &Domain{
|
||||||
domain: strings.ToLower(domain),
|
domain: strings.ToLower(domain),
|
||||||
|
@ -15,7 +15,7 @@ func (dk *DomainKeyword) RuleType() C.RuleType {
|
|||||||
return C.DomainKeyword
|
return C.DomainKeyword
|
||||||
}
|
}
|
||||||
|
|
||||||
func (dk *DomainKeyword) IsMatch(metadata *C.Metadata) bool {
|
func (dk *DomainKeyword) Match(metadata *C.Metadata) bool {
|
||||||
if metadata.AddrType != C.AtypDomainName {
|
if metadata.AddrType != C.AtypDomainName {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@ -31,6 +31,10 @@ func (dk *DomainKeyword) Payload() string {
|
|||||||
return dk.keyword
|
return dk.keyword
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (dk *DomainKeyword) NoResolveIP() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func NewDomainKeyword(keyword string, adapter string) *DomainKeyword {
|
func NewDomainKeyword(keyword string, adapter string) *DomainKeyword {
|
||||||
return &DomainKeyword{
|
return &DomainKeyword{
|
||||||
keyword: strings.ToLower(keyword),
|
keyword: strings.ToLower(keyword),
|
||||||
|
@ -15,7 +15,7 @@ func (ds *DomainSuffix) RuleType() C.RuleType {
|
|||||||
return C.DomainSuffix
|
return C.DomainSuffix
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ds *DomainSuffix) IsMatch(metadata *C.Metadata) bool {
|
func (ds *DomainSuffix) Match(metadata *C.Metadata) bool {
|
||||||
if metadata.AddrType != C.AtypDomainName {
|
if metadata.AddrType != C.AtypDomainName {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@ -31,6 +31,10 @@ func (ds *DomainSuffix) Payload() string {
|
|||||||
return ds.suffix
|
return ds.suffix
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ds *DomainSuffix) NoResolveIP() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func NewDomainSuffix(suffix string, adapter string) *DomainSuffix {
|
func NewDomainSuffix(suffix string, adapter string) *DomainSuffix {
|
||||||
return &DomainSuffix{
|
return &DomainSuffix{
|
||||||
suffix: strings.ToLower(suffix),
|
suffix: strings.ToLower(suffix),
|
||||||
|
@ -12,7 +12,7 @@ func (f *Match) RuleType() C.RuleType {
|
|||||||
return C.MATCH
|
return C.MATCH
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Match) IsMatch(metadata *C.Metadata) bool {
|
func (f *Match) Match(metadata *C.Metadata) bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -24,6 +24,10 @@ func (f *Match) Payload() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *Match) NoResolveIP() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func NewMatch(adapter string) *Match {
|
func NewMatch(adapter string) *Match {
|
||||||
return &Match{
|
return &Match{
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
|
@ -4,9 +4,9 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"github.com/oschwald/geoip2-golang"
|
"github.com/oschwald/geoip2-golang"
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -17,17 +17,19 @@ var (
|
|||||||
type GEOIP struct {
|
type GEOIP struct {
|
||||||
country string
|
country string
|
||||||
adapter string
|
adapter string
|
||||||
|
noResolveIP bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *GEOIP) RuleType() C.RuleType {
|
func (g *GEOIP) RuleType() C.RuleType {
|
||||||
return C.GEOIP
|
return C.GEOIP
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *GEOIP) IsMatch(metadata *C.Metadata) bool {
|
func (g *GEOIP) Match(metadata *C.Metadata) bool {
|
||||||
if metadata.DstIP == nil {
|
ip := metadata.DstIP
|
||||||
|
if ip == nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
record, _ := mmdb.Country(*metadata.DstIP)
|
record, _ := mmdb.Country(ip)
|
||||||
return record.Country.IsoCode == g.country
|
return record.Country.IsoCode == g.country
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -39,16 +41,24 @@ func (g *GEOIP) Payload() string {
|
|||||||
return g.country
|
return g.country
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGEOIP(country string, adapter string) *GEOIP {
|
func (g *GEOIP) NoResolveIP() bool {
|
||||||
|
return g.noResolveIP
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGEOIP(country string, adapter string, noResolveIP bool) *GEOIP {
|
||||||
once.Do(func() {
|
once.Do(func() {
|
||||||
var err error
|
var err error
|
||||||
mmdb, err = geoip2.Open(C.Path.MMDB())
|
mmdb, err = geoip2.Open(C.Path.MMDB())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Can't load mmdb: %s", err.Error())
|
log.Fatalln("Can't load mmdb: %s", err.Error())
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
return &GEOIP{
|
|
||||||
|
geoip := &GEOIP{
|
||||||
country: country,
|
country: country,
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
|
noResolveIP: noResolveIP,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return geoip
|
||||||
}
|
}
|
||||||
|
@ -6,10 +6,25 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type IPCIDROption func(*IPCIDR)
|
||||||
|
|
||||||
|
func WithIPCIDRSourceIP(b bool) IPCIDROption {
|
||||||
|
return func(i *IPCIDR) {
|
||||||
|
i.isSourceIP = b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithIPCIDRNoResolve(noResolve bool) IPCIDROption {
|
||||||
|
return func(i *IPCIDR) {
|
||||||
|
i.noResolveIP = noResolve
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type IPCIDR struct {
|
type IPCIDR struct {
|
||||||
ipnet *net.IPNet
|
ipnet *net.IPNet
|
||||||
adapter string
|
adapter string
|
||||||
isSourceIP bool
|
isSourceIP bool
|
||||||
|
noResolveIP bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *IPCIDR) RuleType() C.RuleType {
|
func (i *IPCIDR) RuleType() C.RuleType {
|
||||||
@ -19,12 +34,12 @@ func (i *IPCIDR) RuleType() C.RuleType {
|
|||||||
return C.IPCIDR
|
return C.IPCIDR
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *IPCIDR) IsMatch(metadata *C.Metadata) bool {
|
func (i *IPCIDR) Match(metadata *C.Metadata) bool {
|
||||||
ip := metadata.DstIP
|
ip := metadata.DstIP
|
||||||
if i.isSourceIP {
|
if i.isSourceIP {
|
||||||
ip = metadata.SrcIP
|
ip = metadata.SrcIP
|
||||||
}
|
}
|
||||||
return ip != nil && i.ipnet.Contains(*ip)
|
return ip != nil && i.ipnet.Contains(ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *IPCIDR) Adapter() string {
|
func (i *IPCIDR) Adapter() string {
|
||||||
@ -35,14 +50,24 @@ func (i *IPCIDR) Payload() string {
|
|||||||
return i.ipnet.String()
|
return i.ipnet.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewIPCIDR(s string, adapter string, isSourceIP bool) *IPCIDR {
|
func (i *IPCIDR) NoResolveIP() bool {
|
||||||
|
return i.noResolveIP
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewIPCIDR(s string, adapter string, opts ...IPCIDROption) (*IPCIDR, error) {
|
||||||
_, ipnet, err := net.ParseCIDR(s)
|
_, ipnet, err := net.ParseCIDR(s)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil
|
return nil, errPayload
|
||||||
}
|
}
|
||||||
return &IPCIDR{
|
|
||||||
|
ipcidr := &IPCIDR{
|
||||||
ipnet: ipnet,
|
ipnet: ipnet,
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
isSourceIP: isSourceIP,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for _, o := range opts {
|
||||||
|
o(ipcidr)
|
||||||
|
}
|
||||||
|
|
||||||
|
return ipcidr, nil
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,7 @@ func (p *Port) RuleType() C.RuleType {
|
|||||||
return C.DstPort
|
return C.DstPort
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Port) IsMatch(metadata *C.Metadata) bool {
|
func (p *Port) Match(metadata *C.Metadata) bool {
|
||||||
if p.isSource {
|
if p.isSource {
|
||||||
return metadata.SrcPort == p.port
|
return metadata.SrcPort == p.port
|
||||||
}
|
}
|
||||||
@ -34,14 +34,18 @@ func (p *Port) Payload() string {
|
|||||||
return p.port
|
return p.port
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPort(port string, adapter string, isSource bool) *Port {
|
func (p *Port) NoResolveIP() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPort(port string, adapter string, isSource bool) (*Port, error) {
|
||||||
_, err := strconv.Atoi(port)
|
_, err := strconv.Atoi(port)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil
|
return nil, errPayload
|
||||||
}
|
}
|
||||||
return &Port{
|
return &Port{
|
||||||
adapter: adapter,
|
adapter: adapter,
|
||||||
port: port,
|
port: port,
|
||||||
isSource: isSource,
|
isSource: isSource,
|
||||||
}
|
}, nil
|
||||||
}
|
}
|
||||||
|
@ -9,16 +9,17 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
adapters "github.com/Dreamacro/clash/adapters/inbound"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/pool"
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, outbound net.Conn) {
|
func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, outbound net.Conn) {
|
||||||
conn := newTrafficTrack(outbound, t.traffic)
|
|
||||||
req := request.R
|
req := request.R
|
||||||
host := req.Host
|
host := req.Host
|
||||||
|
|
||||||
inboundReeder := bufio.NewReader(request)
|
inboundReeder := bufio.NewReader(request)
|
||||||
outboundReeder := bufio.NewReader(conn)
|
outboundReeder := bufio.NewReader(outbound)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
keepAlive := strings.TrimSpace(strings.ToLower(req.Header.Get("Proxy-Connection"))) == "keep-alive"
|
keepAlive := strings.TrimSpace(strings.ToLower(req.Header.Get("Proxy-Connection"))) == "keep-alive"
|
||||||
@ -26,7 +27,7 @@ func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, outbound net.Conn) {
|
|||||||
req.Header.Set("Connection", "close")
|
req.Header.Set("Connection", "close")
|
||||||
req.RequestURI = ""
|
req.RequestURI = ""
|
||||||
adapters.RemoveHopByHopHeaders(req.Header)
|
adapters.RemoveHopByHopHeaders(req.Header)
|
||||||
err := req.Write(conn)
|
err := req.Write(outbound)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@ -59,6 +60,14 @@ func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, outbound net.Conn) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// even if resp.Write write body to the connection, but some http request have to Copy to close it
|
||||||
|
buf := pool.BufPool.Get().([]byte)
|
||||||
|
_, err = io.CopyBuffer(request, resp.Body, buf)
|
||||||
|
pool.BufPool.Put(buf[:cap(buf)])
|
||||||
|
if err != nil && err != io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
req, err = http.ReadRequest(inboundReeder)
|
req, err = http.ReadRequest(inboundReeder)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
@ -72,21 +81,14 @@ func (t *Tunnel) handleHTTP(request *adapters.HTTPAdapter, outbound net.Conn) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) handleUDPToRemote(conn net.Conn, pc net.PacketConn, addr net.Addr) {
|
func (t *Tunnel) handleUDPToRemote(packet C.UDPPacket, pc net.PacketConn, addr net.Addr) {
|
||||||
buf := pool.BufPool.Get().([]byte)
|
if _, err := pc.WriteTo(packet.Data(), addr); err != nil {
|
||||||
defer pool.BufPool.Put(buf[:cap(buf)])
|
|
||||||
|
|
||||||
n, err := conn.Read(buf)
|
|
||||||
if err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, err = pc.WriteTo(buf[:n], addr); err != nil {
|
DefaultManager.Upload() <- int64(len(packet.Data()))
|
||||||
return
|
|
||||||
}
|
|
||||||
t.traffic.Up() <- int64(n)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) handleUDPToLocal(conn net.Conn, pc net.PacketConn, key string, timeout time.Duration) {
|
func (t *Tunnel) handleUDPToLocal(packet C.UDPPacket, pc net.PacketConn, key string, omitSrcAddr bool, timeout time.Duration) {
|
||||||
buf := pool.BufPool.Get().([]byte)
|
buf := pool.BufPool.Get().([]byte)
|
||||||
defer pool.BufPool.Put(buf[:cap(buf)])
|
defer pool.BufPool.Put(buf[:cap(buf)])
|
||||||
defer t.natTable.Delete(key)
|
defer t.natTable.Delete(key)
|
||||||
@ -94,22 +96,24 @@ func (t *Tunnel) handleUDPToLocal(conn net.Conn, pc net.PacketConn, key string,
|
|||||||
|
|
||||||
for {
|
for {
|
||||||
pc.SetReadDeadline(time.Now().Add(timeout))
|
pc.SetReadDeadline(time.Now().Add(timeout))
|
||||||
n, _, err := pc.ReadFrom(buf)
|
n, from, err := pc.ReadFrom(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if from != nil && omitSrcAddr {
|
||||||
|
from = nil
|
||||||
|
}
|
||||||
|
|
||||||
n, err = conn.Write(buf[:n])
|
n, err = packet.WriteBack(buf[:n], from)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
t.traffic.Down() <- int64(n)
|
DefaultManager.Download() <- int64(n)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) handleSocket(request *adapters.SocketAdapter, outbound net.Conn) {
|
func (t *Tunnel) handleSocket(request *adapters.SocketAdapter, outbound net.Conn) {
|
||||||
conn := newTrafficTrack(outbound, t.traffic)
|
relay(request, outbound)
|
||||||
relay(request, conn)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// relay copies between left and right bidirectionally.
|
// relay copies between left and right bidirectionally.
|
||||||
|
87
tunnel/manager.go
Normal file
87
tunnel/manager.go
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
package tunnel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var DefaultManager *Manager
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
DefaultManager = &Manager{
|
||||||
|
upload: make(chan int64),
|
||||||
|
download: make(chan int64),
|
||||||
|
}
|
||||||
|
DefaultManager.handle()
|
||||||
|
}
|
||||||
|
|
||||||
|
type Manager struct {
|
||||||
|
connections sync.Map
|
||||||
|
upload chan int64
|
||||||
|
download chan int64
|
||||||
|
uploadTemp int64
|
||||||
|
downloadTemp int64
|
||||||
|
uploadBlip int64
|
||||||
|
downloadBlip int64
|
||||||
|
uploadTotal int64
|
||||||
|
downloadTotal int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) Join(c tracker) {
|
||||||
|
m.connections.Store(c.ID(), c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) Leave(c tracker) {
|
||||||
|
m.connections.Delete(c.ID())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) Upload() chan<- int64 {
|
||||||
|
return m.upload
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) Download() chan<- int64 {
|
||||||
|
return m.download
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) Now() (up int64, down int64) {
|
||||||
|
return m.uploadBlip, m.downloadBlip
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) Snapshot() *Snapshot {
|
||||||
|
connections := []tracker{}
|
||||||
|
m.connections.Range(func(key, value interface{}) bool {
|
||||||
|
connections = append(connections, value.(tracker))
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
return &Snapshot{
|
||||||
|
UploadTotal: m.uploadTotal,
|
||||||
|
DownloadTotal: m.downloadTotal,
|
||||||
|
Connections: connections,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) handle() {
|
||||||
|
go m.handleCh(m.upload, &m.uploadTemp, &m.uploadBlip, &m.uploadTotal)
|
||||||
|
go m.handleCh(m.download, &m.downloadTemp, &m.downloadBlip, &m.downloadTotal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) handleCh(ch <-chan int64, temp *int64, blip *int64, total *int64) {
|
||||||
|
ticker := time.NewTicker(time.Second)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case n := <-ch:
|
||||||
|
*temp += n
|
||||||
|
*total += n
|
||||||
|
case <-ticker.C:
|
||||||
|
*blip = *temp
|
||||||
|
*temp = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Snapshot struct {
|
||||||
|
DownloadTotal int64 `json:"downloadTotal"`
|
||||||
|
UploadTotal int64 `json:"uploadTotal"`
|
||||||
|
Connections []tracker `json:"connections"`
|
||||||
|
}
|
132
tunnel/tracker.go
Normal file
132
tunnel/tracker.go
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
package tunnel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type tracker interface {
|
||||||
|
ID() string
|
||||||
|
Close() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type trackerInfo struct {
|
||||||
|
UUID uuid.UUID `json:"id"`
|
||||||
|
Metadata *C.Metadata `json:"metadata"`
|
||||||
|
UploadTotal int64 `json:"upload"`
|
||||||
|
DownloadTotal int64 `json:"download"`
|
||||||
|
Start time.Time `json:"start"`
|
||||||
|
Chain C.Chain `json:"chains"`
|
||||||
|
Rule string `json:"rule"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type tcpTracker struct {
|
||||||
|
C.Conn `json:"-"`
|
||||||
|
*trackerInfo
|
||||||
|
manager *Manager
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tt *tcpTracker) ID() string {
|
||||||
|
return tt.UUID.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tt *tcpTracker) Read(b []byte) (int, error) {
|
||||||
|
n, err := tt.Conn.Read(b)
|
||||||
|
download := int64(n)
|
||||||
|
tt.manager.Download() <- download
|
||||||
|
tt.DownloadTotal += download
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tt *tcpTracker) Write(b []byte) (int, error) {
|
||||||
|
n, err := tt.Conn.Write(b)
|
||||||
|
upload := int64(n)
|
||||||
|
tt.manager.Upload() <- upload
|
||||||
|
tt.UploadTotal += upload
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tt *tcpTracker) Close() error {
|
||||||
|
tt.manager.Leave(tt)
|
||||||
|
return tt.Conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTCPTracker(conn C.Conn, manager *Manager, metadata *C.Metadata, rule C.Rule) *tcpTracker {
|
||||||
|
uuid, _ := uuid.NewV4()
|
||||||
|
ruleType := ""
|
||||||
|
if rule != nil {
|
||||||
|
ruleType = rule.RuleType().String()
|
||||||
|
}
|
||||||
|
|
||||||
|
t := &tcpTracker{
|
||||||
|
Conn: conn,
|
||||||
|
manager: manager,
|
||||||
|
trackerInfo: &trackerInfo{
|
||||||
|
UUID: uuid,
|
||||||
|
Start: time.Now(),
|
||||||
|
Metadata: metadata,
|
||||||
|
Chain: conn.Chains(),
|
||||||
|
Rule: ruleType,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
manager.Join(t)
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
type udpTracker struct {
|
||||||
|
C.PacketConn `json:"-"`
|
||||||
|
*trackerInfo
|
||||||
|
manager *Manager
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ut *udpTracker) ID() string {
|
||||||
|
return ut.UUID.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ut *udpTracker) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, addr, err := ut.PacketConn.ReadFrom(b)
|
||||||
|
download := int64(n)
|
||||||
|
ut.manager.Download() <- download
|
||||||
|
ut.DownloadTotal += download
|
||||||
|
return n, addr, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ut *udpTracker) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
n, err := ut.PacketConn.WriteTo(b, addr)
|
||||||
|
upload := int64(n)
|
||||||
|
ut.manager.Upload() <- upload
|
||||||
|
ut.UploadTotal += upload
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ut *udpTracker) Close() error {
|
||||||
|
ut.manager.Leave(ut)
|
||||||
|
return ut.PacketConn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func newUDPTracker(conn C.PacketConn, manager *Manager, metadata *C.Metadata, rule C.Rule) *udpTracker {
|
||||||
|
uuid, _ := uuid.NewV4()
|
||||||
|
ruleType := ""
|
||||||
|
if rule != nil {
|
||||||
|
ruleType = rule.RuleType().String()
|
||||||
|
}
|
||||||
|
|
||||||
|
ut := &udpTracker{
|
||||||
|
PacketConn: conn,
|
||||||
|
manager: manager,
|
||||||
|
trackerInfo: &trackerInfo{
|
||||||
|
UUID: uuid,
|
||||||
|
Start: time.Now(),
|
||||||
|
Metadata: metadata,
|
||||||
|
Chain: conn.Chains(),
|
||||||
|
Rule: ruleType,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
manager.Join(ut)
|
||||||
|
return ut
|
||||||
|
}
|
@ -3,10 +3,12 @@ package tunnel
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"runtime"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
InboundAdapter "github.com/Dreamacro/clash/adapters/inbound"
|
"github.com/Dreamacro/clash/adapters/inbound"
|
||||||
|
"github.com/Dreamacro/clash/adapters/provider"
|
||||||
"github.com/Dreamacro/clash/component/nat"
|
"github.com/Dreamacro/clash/component/nat"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/dns"
|
"github.com/Dreamacro/clash/dns"
|
||||||
@ -30,8 +32,8 @@ type Tunnel struct {
|
|||||||
natTable *nat.Table
|
natTable *nat.Table
|
||||||
rules []C.Rule
|
rules []C.Rule
|
||||||
proxies map[string]C.Proxy
|
proxies map[string]C.Proxy
|
||||||
configMux *sync.RWMutex
|
providers map[string]provider.ProxyProvider
|
||||||
traffic *C.Traffic
|
configMux sync.RWMutex
|
||||||
|
|
||||||
// experimental features
|
// experimental features
|
||||||
ignoreResolveFail bool
|
ignoreResolveFail bool
|
||||||
@ -42,17 +44,12 @@ type Tunnel struct {
|
|||||||
|
|
||||||
// Add request to queue
|
// Add request to queue
|
||||||
func (t *Tunnel) Add(req C.ServerAdapter) {
|
func (t *Tunnel) Add(req C.ServerAdapter) {
|
||||||
switch req.Metadata().NetWork {
|
|
||||||
case C.TCP:
|
|
||||||
t.tcpQueue.In() <- req
|
t.tcpQueue.In() <- req
|
||||||
case C.UDP:
|
|
||||||
t.udpQueue.In() <- req
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Traffic return traffic of all connections
|
// AddPacket add udp Packet to queue
|
||||||
func (t *Tunnel) Traffic() *C.Traffic {
|
func (t *Tunnel) AddPacket(packet *inbound.PacketAdapter) {
|
||||||
return t.traffic
|
t.udpQueue.In() <- packet
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rules return all rules
|
// Rules return all rules
|
||||||
@ -72,10 +69,16 @@ func (t *Tunnel) Proxies() map[string]C.Proxy {
|
|||||||
return t.proxies
|
return t.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Providers return all compatible providers
|
||||||
|
func (t *Tunnel) Providers() map[string]provider.ProxyProvider {
|
||||||
|
return t.providers
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateProxies handle update proxies
|
// UpdateProxies handle update proxies
|
||||||
func (t *Tunnel) UpdateProxies(proxies map[string]C.Proxy) {
|
func (t *Tunnel) UpdateProxies(proxies map[string]C.Proxy, providers map[string]provider.ProxyProvider) {
|
||||||
t.configMux.Lock()
|
t.configMux.Lock()
|
||||||
t.proxies = proxies
|
t.proxies = proxies
|
||||||
|
t.providers = providers
|
||||||
t.configMux.Unlock()
|
t.configMux.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -96,14 +99,23 @@ func (t *Tunnel) SetMode(mode Mode) {
|
|||||||
t.mode = mode
|
t.mode = mode
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) process() {
|
// processUDP starts a loop to handle udp packet
|
||||||
go func() {
|
func (t *Tunnel) processUDP() {
|
||||||
queue := t.udpQueue.Out()
|
queue := t.udpQueue.Out()
|
||||||
for elm := range queue {
|
for elm := range queue {
|
||||||
conn := elm.(C.ServerAdapter)
|
conn := elm.(*inbound.PacketAdapter)
|
||||||
t.handleUDPConn(conn)
|
t.handleUDPConn(conn)
|
||||||
}
|
}
|
||||||
}()
|
}
|
||||||
|
|
||||||
|
func (t *Tunnel) process() {
|
||||||
|
numUDPWorkers := 4
|
||||||
|
if runtime.NumCPU() > numUDPWorkers {
|
||||||
|
numUDPWorkers = runtime.NumCPU()
|
||||||
|
}
|
||||||
|
for i := 0; i < numUDPWorkers; i++ {
|
||||||
|
go t.processUDP()
|
||||||
|
}
|
||||||
|
|
||||||
queue := t.tcpQueue.Out()
|
queue := t.tcpQueue.Out()
|
||||||
for elm := range queue {
|
for elm := range queue {
|
||||||
@ -117,17 +129,22 @@ func (t *Tunnel) resolveIP(host string) (net.IP, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) needLookupIP(metadata *C.Metadata) bool {
|
func (t *Tunnel) needLookupIP(metadata *C.Metadata) bool {
|
||||||
return dns.DefaultResolver != nil && (dns.DefaultResolver.IsMapping() || dns.DefaultResolver.IsFakeIP()) && metadata.Host == "" && metadata.DstIP != nil
|
return dns.DefaultResolver != nil && (dns.DefaultResolver.IsMapping() || dns.DefaultResolver.FakeIPEnabled()) && metadata.Host == "" && metadata.DstIP != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) resolveMetadata(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
|
func (t *Tunnel) resolveMetadata(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
|
||||||
|
// handle host equal IP string
|
||||||
|
if ip := net.ParseIP(metadata.Host); ip != nil {
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
// preprocess enhanced-mode metadata
|
// preprocess enhanced-mode metadata
|
||||||
if t.needLookupIP(metadata) {
|
if t.needLookupIP(metadata) {
|
||||||
host, exist := dns.DefaultResolver.IPToHost(*metadata.DstIP)
|
host, exist := dns.DefaultResolver.IPToHost(metadata.DstIP)
|
||||||
if exist {
|
if exist {
|
||||||
metadata.Host = host
|
metadata.Host = host
|
||||||
metadata.AddrType = C.AtypDomainName
|
metadata.AddrType = C.AtypDomainName
|
||||||
if dns.DefaultResolver.IsFakeIP() {
|
if dns.DefaultResolver.FakeIPEnabled() {
|
||||||
metadata.DstIP = nil
|
metadata.DstIP = nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -151,31 +168,34 @@ func (t *Tunnel) resolveMetadata(metadata *C.Metadata) (C.Proxy, C.Rule, error)
|
|||||||
return proxy, rule, nil
|
return proxy, rule, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) handleUDPConn(localConn C.ServerAdapter) {
|
func (t *Tunnel) handleUDPConn(packet *inbound.PacketAdapter) {
|
||||||
metadata := localConn.Metadata()
|
metadata := packet.Metadata()
|
||||||
if !metadata.Valid() {
|
if !metadata.Valid() {
|
||||||
log.Warnln("[Metadata] not valid: %#v", metadata)
|
log.Warnln("[Metadata] not valid: %#v", metadata)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
src := localConn.RemoteAddr().String()
|
src := packet.LocalAddr().String()
|
||||||
dst := metadata.RemoteAddress()
|
dst := metadata.RemoteAddress()
|
||||||
key := src + "-" + dst
|
key := src + "-" + dst
|
||||||
|
|
||||||
pc, addr := t.natTable.Get(key)
|
pc, addr := t.natTable.Get(key)
|
||||||
if pc != nil {
|
if pc != nil {
|
||||||
t.handleUDPToRemote(localConn, pc, addr)
|
t.handleUDPToRemote(packet, pc, addr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
lockKey := key + "-lock"
|
lockKey := key + "-lock"
|
||||||
wg, loaded := t.natTable.GetOrCreateLock(lockKey)
|
wg, loaded := t.natTable.GetOrCreateLock(lockKey)
|
||||||
|
|
||||||
|
isFakeIP := dns.DefaultResolver.IsFakeIP(metadata.DstIP)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
if !loaded {
|
if !loaded {
|
||||||
wg.Add(1)
|
wg.Add(1)
|
||||||
proxy, rule, err := t.resolveMetadata(metadata)
|
proxy, rule, err := t.resolveMetadata(metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnln("Parse metadata failed: %s", err.Error())
|
log.Warnln("[UDP] Parse metadata failed: %s", err.Error())
|
||||||
t.natTable.Delete(lockKey)
|
t.natTable.Delete(lockKey)
|
||||||
wg.Done()
|
wg.Done()
|
||||||
return
|
return
|
||||||
@ -183,30 +203,31 @@ func (t *Tunnel) handleUDPConn(localConn C.ServerAdapter) {
|
|||||||
|
|
||||||
rawPc, nAddr, err := proxy.DialUDP(metadata)
|
rawPc, nAddr, err := proxy.DialUDP(metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnln("dial %s error: %s", proxy.Name(), err.Error())
|
log.Warnln("[UDP] dial %s error: %s", proxy.Name(), err.Error())
|
||||||
t.natTable.Delete(lockKey)
|
t.natTable.Delete(lockKey)
|
||||||
wg.Done()
|
wg.Done()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
pc = rawPc
|
|
||||||
addr = nAddr
|
addr = nAddr
|
||||||
|
pc = newUDPTracker(rawPc, DefaultManager, metadata, rule)
|
||||||
|
|
||||||
if rule != nil {
|
if rule != nil {
|
||||||
log.Infoln("%s --> %v match %s using %s", metadata.SrcIP.String(), metadata.String(), rule.RuleType().String(), rawPc.Chains().String())
|
log.Infoln("[UDP] %s --> %v match %s using %s", metadata.SrcIP.String(), metadata.String(), rule.RuleType().String(), rawPc.Chains().String())
|
||||||
} else {
|
} else {
|
||||||
log.Infoln("%s --> %v doesn't match any rule using DIRECT", metadata.SrcIP.String(), metadata.String())
|
log.Infoln("[UDP] %s --> %v doesn't match any rule using DIRECT", metadata.SrcIP.String(), metadata.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
t.natTable.Set(key, pc, addr)
|
t.natTable.Set(key, pc, addr)
|
||||||
t.natTable.Delete(lockKey)
|
t.natTable.Delete(lockKey)
|
||||||
wg.Done()
|
wg.Done()
|
||||||
go t.handleUDPToLocal(localConn, pc, key, udpTimeout)
|
// in fake-ip mode, Full-Cone NAT can never achieve, fallback to omitting src Addr
|
||||||
|
go t.handleUDPToLocal(packet.UDPPacket, pc, key, isFakeIP, udpTimeout)
|
||||||
}
|
}
|
||||||
|
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
pc, addr := t.natTable.Get(key)
|
pc, addr := t.natTable.Get(key)
|
||||||
if pc != nil {
|
if pc != nil {
|
||||||
t.handleUDPToRemote(localConn, pc, addr)
|
t.handleUDPToRemote(packet, pc, addr)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
@ -231,6 +252,7 @@ func (t *Tunnel) handleTCPConn(localConn C.ServerAdapter) {
|
|||||||
log.Warnln("dial %s error: %s", proxy.Name(), err.Error())
|
log.Warnln("dial %s error: %s", proxy.Name(), err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
remoteConn = newTCPTracker(remoteConn, DefaultManager, metadata, rule)
|
||||||
defer remoteConn.Close()
|
defer remoteConn.Close()
|
||||||
|
|
||||||
if rule != nil {
|
if rule != nil {
|
||||||
@ -240,15 +262,15 @@ func (t *Tunnel) handleTCPConn(localConn C.ServerAdapter) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch adapter := localConn.(type) {
|
switch adapter := localConn.(type) {
|
||||||
case *InboundAdapter.HTTPAdapter:
|
case *inbound.HTTPAdapter:
|
||||||
t.handleHTTP(adapter, remoteConn)
|
t.handleHTTP(adapter, remoteConn)
|
||||||
case *InboundAdapter.SocketAdapter:
|
case *inbound.SocketAdapter:
|
||||||
t.handleSocket(adapter, remoteConn)
|
t.handleSocket(adapter, remoteConn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) shouldResolveIP(rule C.Rule, metadata *C.Metadata) bool {
|
func (t *Tunnel) shouldResolveIP(rule C.Rule, metadata *C.Metadata) bool {
|
||||||
return (rule.RuleType() == C.GEOIP || rule.RuleType() == C.IPCIDR) && metadata.Host != "" && metadata.DstIP == nil
|
return !rule.NoResolveIP() && metadata.Host != "" && metadata.DstIP == nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Tunnel) match(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
|
func (t *Tunnel) match(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
|
||||||
@ -259,7 +281,7 @@ func (t *Tunnel) match(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
|
|||||||
|
|
||||||
if node := dns.DefaultHosts.Search(metadata.Host); node != nil {
|
if node := dns.DefaultHosts.Search(metadata.Host); node != nil {
|
||||||
ip := node.Data.(net.IP)
|
ip := node.Data.(net.IP)
|
||||||
metadata.DstIP = &ip
|
metadata.DstIP = ip
|
||||||
resolved = true
|
resolved = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -273,12 +295,12 @@ func (t *Tunnel) match(metadata *C.Metadata) (C.Proxy, C.Rule, error) {
|
|||||||
log.Debugln("[DNS] resolve %s error: %s", metadata.Host, err.Error())
|
log.Debugln("[DNS] resolve %s error: %s", metadata.Host, err.Error())
|
||||||
} else {
|
} else {
|
||||||
log.Debugln("[DNS] %s --> %s", metadata.Host, ip.String())
|
log.Debugln("[DNS] %s --> %s", metadata.Host, ip.String())
|
||||||
metadata.DstIP = &ip
|
metadata.DstIP = ip
|
||||||
}
|
}
|
||||||
resolved = true
|
resolved = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if rule.IsMatch(metadata) {
|
if rule.Match(metadata) {
|
||||||
adapter, ok := t.proxies[rule.Adapter()]
|
adapter, ok := t.proxies[rule.Adapter()]
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
@ -300,8 +322,6 @@ func newTunnel() *Tunnel {
|
|||||||
udpQueue: channels.NewInfiniteChannel(),
|
udpQueue: channels.NewInfiniteChannel(),
|
||||||
natTable: nat.New(),
|
natTable: nat.New(),
|
||||||
proxies: make(map[string]C.Proxy),
|
proxies: make(map[string]C.Proxy),
|
||||||
configMux: &sync.RWMutex{},
|
|
||||||
traffic: C.NewTraffic(time.Second),
|
|
||||||
mode: Rule,
|
mode: Rule,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,29 +0,0 @@
|
|||||||
package tunnel
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TrafficTrack record traffic of net.Conn
|
|
||||||
type TrafficTrack struct {
|
|
||||||
net.Conn
|
|
||||||
traffic *C.Traffic
|
|
||||||
}
|
|
||||||
|
|
||||||
func (tt *TrafficTrack) Read(b []byte) (int, error) {
|
|
||||||
n, err := tt.Conn.Read(b)
|
|
||||||
tt.traffic.Down() <- int64(n)
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (tt *TrafficTrack) Write(b []byte) (int, error) {
|
|
||||||
n, err := tt.Conn.Write(b)
|
|
||||||
tt.traffic.Up() <- int64(n)
|
|
||||||
return n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTrafficTrack(conn net.Conn, traffic *C.Traffic) *TrafficTrack {
|
|
||||||
return &TrafficTrack{traffic: traffic, Conn: conn}
|
|
||||||
}
|
|
Reference in New Issue
Block a user