Compare commits

...

795 Commits

Author SHA1 Message Date
a76yyyy
c7e34bdc11
Docs(locales): add chinese locale support (#2772) 2023-07-14 22:20:15 +08:00
Dreamacro
24186a488a Chore: update dependencies 2023-06-30 21:03:58 +08:00
Kr328
5212aaf445
Fix: process resolving for udp (#2806) 2023-06-25 09:19:06 +08:00
MoonStrider
e26bed43de
Change: replace std regex with regexp2 (#2802) 2023-06-21 17:06:29 +08:00
Dreamacro
700ceed194 Fix: proxy health check should check not alive proxy on lazy 2023-06-18 18:30:02 +08:00
Kr328
154cb1d1f0
Improve: alloc using make if alloc size > 65536 (#2796) 2023-06-18 11:19:35 +08:00
Kr328
295b0da0e5
Fix: should check originDst is nil (#2797) 2023-06-18 11:16:40 +08:00
Dreamacro
31fe77ee69 Chore: add alive for proxy api 2023-06-16 21:19:10 +08:00
Kr328
9177645a89
Fix: windows process panic (#2793) 2023-06-15 21:37:26 +08:00
Kr328
355eb491ad
Fix: windows process panic (#2791) 2023-06-15 17:51:55 +08:00
Terry Chan
18c666a1ab
Fix: aysnc exchange with new context (#2788) 2023-06-13 23:44:48 +08:00
Kr328
13d9e960f7
Refactor: refactor find process (#2781) 2023-06-13 23:25:32 +08:00
Dreamacro
289025c6ee Fix: filterable provider should be touch 2023-05-28 14:12:03 +08:00
Dreamacro
369f2735a0 Fix: linter fix 2023-05-28 13:52:17 +08:00
Yonas Yanfa
2b6dd2a909
Feature: add REDIRECT IPv6 support for FreeBSD. (#2768)
Upstream patch from FreeBSD ports which adds IPv6 support.
2023-05-25 21:13:42 +08:00
znley
ccd6d321cd
Feature: add loong64 build (#2762) 2023-05-24 09:44:43 +08:00
a76yyyy
4d66da2277
Chore: update wiki URL in issue_template (#2763) 2023-05-23 19:46:01 +08:00
Akariln
1ab615852e
Docs: fix some mistakes (#2761) 2023-05-21 21:26:10 +08:00
Birkhoff Lee
46bb6c38ff
Docs(shortcuts): add expr and starlark (#2759)
Signed-off-by: Birkhoff Lee <git@birkhoff.me>
2023-05-21 21:24:21 +08:00
Birkhoff Lee
c244229ffb
Docs(faq): add docs about amd64-v3 (#2752) 2023-05-21 21:23:35 +08:00
Birkhoff Lee
e8b2d0ecc8
Docs: fix previous/next page button (#2760)
Signed-off-by: Birkhoff Lee <git@birkhoff.me>
2023-05-21 21:22:52 +08:00
Birkhoff Lee
acec0f5c89
Docs(rules): update about no-resolve (#2758) 2023-05-21 21:22:12 +08:00
Birkhoff Lee
4655bd4da8
Docs(script-shortcuts): add expr engine (#2757) 2023-05-20 22:52:50 +08:00
Birkhoff Lee
6b17fd2595
Docs(rules): fix IPSET example (#2756) 2023-05-20 22:52:31 +08:00
Birkhoff Lee
cbcbd0e085
Docs(outbound): fix some typos (#2755) 2023-05-20 22:52:11 +08:00
Birkhoff Lee
75c0254703
Docs(ebpf): add tailscaled conflict (#2754) 2023-05-20 22:51:46 +08:00
Dreamacro
e02d556bf4 Chore: upgrade test deps 2023-05-19 22:10:26 +08:00
Dreamacro
d006b0f2b4 Chore: update dependencies 2023-05-19 21:55:04 +08:00
Birkhoff Lee
d9753efe23
Docs: link logo to public directory (#2748)
Signed-off-by: Birkhoff Lee <git@birkhoff.me>
2023-05-19 21:14:03 +08:00
Birkhoff Lee
6ecd96e5ac
Docs: fix logo url and update README (#2747)
Signed-off-by: Birkhoff Lee <git@birkhoff.me>
2023-05-17 21:07:23 +08:00
Dreamacro
fdb1456c69 Fix: docs build path 2023-05-15 22:35:03 +08:00
Dreamacro
7d9723662c Chore: upgrade actions/deploy-pages version 2023-05-15 21:55:52 +08:00
Birkhoff Lee
ca42ca2ca8
Docs: new documentation site (#2723)
This commit adds a VitePress build to the main repository,
aiming to ditch GitHub Wiki. Moving further, we're going to
host our own documentation site eithor on GitHub Pages or
something alike.
2023-05-15 21:47:01 +08:00
江湖风轻
10dcb7a3ad
Fix: PacketConn's internal remote address is overwritten (#2727)
When using vmess + fake-ip, after receiving the first UDP response,
PacketConn's internal address will be rewritten to fake-ip, causing all
subsequent sending operations to return "ErrUDPRemoteAddrMismatch".

Signed-off-by: Hackerl <490021209@qq.com>
2023-05-11 18:42:24 +08:00
Dreamacro
4c3c64a34a Fix: potential token time attack 2023-05-06 14:51:28 +08:00
KaitoHH
257fcef0b8
Fix: adjust DNS TTL values based on minimum value (#2706)
This commit adds an updated function that adjusts
the TTL values of DNS records are based on the minimum TTL
the value found in the records list so that all records share the
same TTL value. This ensures consistency in the cache
expiry time for all records to prevent caching issues.
2023-04-30 12:18:20 +08:00
Georeth Chow
7f1b50f4a7
Chore: Fix ISSUE_TEMPLATE (DEBUG -> debug) (#2711) 2023-04-28 17:23:00 +08:00
Birkhoff Lee
4f5e74dad9
Chore: update bug_report.yml (#2708)
Signed-off-by: Birkhoff Lee <git@birkhoff.me>
2023-04-27 18:19:31 +08:00
yaling888
48b77b2847
Fix: socks4 server handshake (#2700) 2023-04-25 20:16:11 +08:00
major1201
6eee226965
Feature: support IPSET rule (#2693) 2023-04-22 20:07:47 +08:00
Dreamacro
765982e86a Chore: add new lint-fix for Makefile 2023-04-22 20:03:57 +08:00
yaling888
c5fe5235f7
Feature: add provider proxies API (#2668) 2023-04-22 19:16:51 +08:00
Dreamacro
63770b328f Fix: direct require protobytes 2023-04-21 21:13:13 +08:00
Dreamacro
85f4cb23fc Fix: put correctly pool 2023-04-20 11:07:21 +08:00
Xiaochao Dong
d71324069d
Feature: support basic authentication for DoH (#2684) 2023-04-19 11:30:57 +08:00
Dreamacro
b7aade5e11 Chore: use protobytes replace most of bytes.Buffer 2023-04-17 14:08:39 +08:00
M4rtin Hsu
df61a586c9
Fix: potential vulnerability in http provider (#2680) 2023-04-16 20:14:36 +08:00
Dreamacro
8e05fbfd6d Chore: update dependencies 2023-04-13 20:51:13 +08:00
yaling888
9b2b7c662d
Feature: add filter option to proxy group (#2518) 2023-04-08 19:23:19 +08:00
yaling888
20a521f02d
Feature: bind socket to interface by native API on Windows (#2662) 2023-04-08 19:20:14 +08:00
yaling888
95bbfe3945
Fix: should always drop packet when handle UDP packet (#2659) 2023-04-05 14:05:23 +08:00
Dreamacro
4cd4912749 Chore: more parse proxy group error detail 2023-04-04 16:50:41 +08:00
Dreamacro
5045ca4574 Chore: add some linters and clean up the code 2023-04-04 14:53:59 +08:00
RommHui
a7252a1576
Feature: allow http outbound to set custom headers (#2647) 2023-03-31 20:33:41 +08:00
包布丁
7e2974f02f
Fix: return pooled buffer when simple-obfs tls read error (#2643) 2023-03-26 16:22:23 +08:00
Jiahao Lu
8f9b39c62e
Fix: potential panic in putMsgToCache (#2634)
When the upstream DNS server returns a message that contains no
questions (i.e. QDCOUNT == 0), `putMsgToCache` will trigger an
out-of-range panic.

Issue: #2524
Comment: https://github.com/Dreamacro/clash/issues/2524#issuecomment-1477477601
2023-03-21 19:36:49 +08:00
Dreamacro
d808576f98 Chore: use the number of cpus in parallel make 2023-03-18 20:19:34 +08:00
Dreamacro
fcbe2f06cc Chore: update docker workflow 2023-03-18 19:57:31 +08:00
Dreamacro
148ebccb60 Fix: ignore meanDelay error 2023-03-17 16:35:50 +08:00
Jeff An
3b1d319820
Feature: add support for dns search domains (#2597) 2023-03-17 15:53:06 +08:00
Dreamacro
ff2f2b667b Chore: make test linter happy 2023-03-14 21:24:15 +08:00
Dreamacro
e5a2dbd9b5 Chore: update uuid to v5 2023-03-14 21:18:09 +08:00
Dreamacro
4d14dd65fa Chore: update dependencies 2023-03-14 21:08:09 +08:00
Dave Yu
4ffc999617
Fix: modify local ip to pass all test (#2595) 2023-03-09 10:44:36 +08:00
Dreamacro
71f8f0667f Fix: fakeip 4in 6 unmap 2023-03-04 16:27:36 +08:00
Dreamacro
f78a7cb2cb Feature: add meanDelay on URLTest 2023-02-28 13:28:42 +08:00
Dreamacro
8173d6681b Migration: go1.20 2023-02-16 21:43:40 +08:00
Dreamacro
fbf2f26516 Chore: update bug report template 2023-02-03 21:19:06 +08:00
Dreamacro
9af6d498e7 Change: remove redir-host as config 2023-02-01 15:19:36 +08:00
bobo liu
81b1e9f931
Feature: support vmess 'zero' security (#2513) 2023-01-30 14:14:42 +08:00
Dreamacro
58732ee8b1 Chore: update dependencies 2023-01-29 18:46:47 +08:00
yaling888
d16727e2bd
Fix: dns api panic on disable dns section (#2498) 2023-01-18 16:58:03 +08:00
Dreamacro
876653ebc8 Feature: add riscv64 build 2023-01-18 12:06:06 +08:00
Dreamacro
a26b670420 Feature: add dns query json api 2023-01-16 15:25:34 +08:00
Dreamacro
0489a7391b Chore: update test dependencies 2023-01-11 14:44:38 +08:00
Dreamacro
0c0d18a01c Chore: update dependencies 2023-01-11 14:43:34 +08:00
Dreamacro
e1fa343088 Change: set false as udp-fallback-match default value 2023-01-04 17:43:14 +08:00
Dreamacro
a5d54884e0 Feature: add udp-fallback-match option 2023-01-01 20:12:17 +08:00
Dreamacro
2301b909d2 Fix: immediately update provider when modtime too old 2022-12-31 16:32:30 +08:00
embeddedlove
fbca37c42b
Feature: REDIRECT support IPv6 (#2473) 2022-12-22 19:25:30 +08:00
ALICE
4a57917783
Chore: skip cache acme challenge dns msg (#2469) 2022-12-22 13:30:23 +08:00
wwqgtxx
cdc7d449a6
Fix: safeConnClose not working (#2463) 2022-12-22 12:42:38 +08:00
igoogolx
d8ac82be36
Fix: broken build badge (#2470) 2022-12-22 12:09:24 +08:00
Dreamacro
a6c144038b Chore: improve redir getorigdst 2022-12-22 12:00:56 +08:00
Sizhe Sun
90b40a8e5a
Fix: drop UDP packet which mismatched destination for VMess (#2410)
Co-authored-by: SUN Sizhe <sunsizhe@cmi.chinamobile.com>
2022-11-26 11:27:24 +08:00
Dreamacro
ed988dcdc5 Chore: update dependencies 2022-11-25 20:42:28 +08:00
Dreamacro
efa4b9e0b8 Fix: lint warning 2022-11-22 21:01:51 +08:00
Dreamacro
8c6e205c5a Fix: tunnel proxy match 2022-11-22 19:16:08 +08:00
Dreamacro
5b07d7b776 Feature: add tunnels 2022-11-20 21:30:55 +08:00
Dreamacro
de264c42a8 Chore: update test dependencies 2022-11-04 13:31:20 +08:00
Dreamacro
c2469162fb Chore: update dependencies 2022-11-04 13:28:51 +08:00
wwqgtxx
19b7c7f52a
Fix: a shared fastSingle.Do() may cause providers untouched (#2378) 2022-11-04 13:11:01 +08:00
Dreamacro
c8bc11d61d Fix: amd64 macOS Ventura process name match 2022-10-27 15:36:09 +08:00
Dreamacro
f29b54898f Fix: macOS Ventura process name match 2022-10-27 11:25:18 +08:00
Pan
3e2b08f9d0
Chore: upgrade go.mod go version to 1.19 (#2331) 2022-09-29 11:47:30 +08:00
AndyChen
fb85691fb9
Fix: uncorrect README link (#2325) 2022-09-27 14:22:21 +08:00
Dreamacro
d411394482 Chore: rename linux-armv8 to linux-arm64, windows-arm32v7 to windows-armv7 2022-09-21 21:18:24 +08:00
Adrian Gąsior
827d5289bc
Refactor: improve Dockerfile (#2246) 2022-09-21 21:09:11 +08:00
Kr328
6995e98181
Refactor: linux process resolving (#2305) 2022-09-18 12:53:51 +08:00
x2c3z4
4f291fa513
Chore: show the source ip in log (#2284)
Co-authored-by: Li Feng <fengli@smartx.com>
2022-09-02 16:59:00 +08:00
Kr328
22b9befbda
Fix: fake ip pool offset calculate (#2281) 2022-09-01 11:33:47 +08:00
Birkhoff Lee
425b6e0dc0
Chore: update README (#2276) 2022-08-27 12:16:25 +08:00
Dreamacro
2516169f61 Chore: update dependencies 2022-08-26 21:18:16 +08:00
Dreamacro
a3281712e2 Chore: reduce dhcp dns client cost 2022-08-24 21:36:19 +08:00
Dreamacro
bf079742cb Clean: use go 1.19 Appendf 2022-08-24 20:21:06 +08:00
Dreamacro
6e058f8581 Chore: remove old cache implementation 2022-08-17 11:43:20 +08:00
Dreamacro
3946d771e5 Feature: sync missing resolver logic from premium, but still net.IP on opensource 2022-08-13 13:07:35 +08:00
Dreamacro
5940f62794 Chore: http2 should use DialTLSContext and some tls handshake should with context 2022-08-13 12:35:39 +08:00
bobo liu
71cad51e8f
Fix: satisfy RFC4343 - DNS case insensitivity (#2260) 2022-08-12 13:47:51 +08:00
Dreamacro
50105f0559 Migration: go1.19 2022-08-07 21:45:50 +08:00
Dreamacro
6648793e40 Chore: reenable latest golangci-lint 2022-08-05 10:52:36 +08:00
archzi
95e3a88608
Chore: update bug_report.yml (#2240) 2022-07-28 20:27:53 +08:00
Kaming Chan
bec4df7b12
Fix: handle parse socks5 udp address properly (#2220) 2022-07-25 12:44:00 +08:00
Skyxim
93400cf44d
Fix: ALPN should on DoH instead of DoT (#2232) 2022-07-25 12:41:22 +08:00
Dreamacro
a794819869 Chore: upgrade actions and fixed golangci-lint version 2022-07-21 15:15:14 +08:00
Dreamacro
be8d63ba8f Fix: macOS udp find process should use unspecified fallback 2022-07-15 17:00:41 +08:00
Dreamacro
3b90e18047 Chore: update test dependencies 2022-07-15 16:07:18 +08:00
LJea
f0952b55d0
Fix: query string parse on ws-opts (#2213) 2022-07-10 14:56:34 +08:00
Dreamacro
8c7c8f4374 Chore: update dependencies 2022-07-07 22:15:50 +08:00
Kaming Chan
65a8e8f59c
Fix: process rule type (#2206) 2022-07-06 13:44:04 +08:00
Dreamacro
5497adaba1 Fix: fakeip udp should not replace with another ip 2022-07-05 21:09:29 +08:00
Dreamacro
aaf08dadff
Change: remove AddrType on Metadata (#2199) 2022-07-05 20:26:43 +08:00
Dreamacro
557297ac9a Chore: load balance hash need to have fallback strategy 2022-07-04 21:36:33 +08:00
Dreamacro
77a1e3a653 Chore: cleanup bind mark code 2022-06-30 17:27:57 +08:00
Dreamacro
27e1d6cdae Chore: cleanup code 2022-06-30 17:12:06 +08:00
Kaming Chan
91c22b16bf
Fix: proxy provider filter validation (#2198) 2022-06-30 17:08:53 +08:00
Dreamacro
fc5c9b931b Fix: try to unmap lAddr on tproxy udp listener 2022-06-29 23:36:45 +08:00
Dreamacro
c231fd1466 Chore: update dependencies 2022-06-19 13:01:43 +08:00
Dreamacro
fbb27b84d1 Chore: add redir-host deprecated warnning 2022-06-14 11:26:04 +08:00
Dreamacro
e0c5a85314 Fix: missing import 2022-06-12 21:22:02 +08:00
Dreamacro
2fa1a5c4b9 Chore: update tproxy udp packet read logic 2022-06-12 19:37:51 +08:00
Dreamacro
06d75da257 Chore: adjust Relay copy memory alloc logic 2022-06-11 20:38:16 +08:00
Dreamacro
09d49bac95 Chore: embed shadowsocks2 2022-06-01 21:43:20 +08:00
Dreamacro
3360839fe3 Chore: make CodeQL happy 2022-06-01 21:38:05 +08:00
Hongqi Yu
c1285adbf8
Feature: can set custom interface for dns nameserver (#2126) 2022-06-01 10:50:54 +08:00
Dreamacro
9d2fc976e2 Chore: upgrade to yaml v3 2022-05-26 17:47:05 +08:00
Dreamacro
7f41f94fff Fix: benchmark read bytes 2022-05-23 12:58:18 +08:00
Dreamacro
d1f0dac302 Fix: test broken on opensource repo 2022-05-23 12:30:54 +08:00
Dreamacro
afb3e00067 Chore: add benchmark r/w 2022-05-23 12:27:52 +08:00
Dreamacro
9a31ad6151 Chore: cleanup test go.mod 2022-05-21 17:46:34 +08:00
Dreamacro
09cc6b69e3 Chore: cleanup test code 2022-05-21 17:38:17 +08:00
Dreamacro
8603ac40a1 Chore: make linter happy 2022-05-17 19:58:33 +08:00
Kr328
b384449717
Fix: fix upgrade header detect (#2134) 2022-05-15 09:12:53 +08:00
Kaming Chan
da7ffc0da9
Fix: add length check for ssr auth_aes128_sha1 (#2129) 2022-05-13 11:21:39 +08:00
Dreamacro
5dd94c8298 Chore: update dependencies 2022-05-07 21:08:15 +08:00
Kaming Chan
412b44a981
Fix: decode nil value in slice decoder (#2102) 2022-05-07 11:00:58 +08:00
Dreamacro
aef4dd3fe7 Fix: make log api unblocked 2022-04-26 22:36:10 +08:00
Kr328
6a92c6af4e
Fix: http proxy Upgrade behavior (#2097) 2022-04-25 19:50:20 +08:00
Kr328
e010940b61
Improve: replace bootstrap dns (#2080) 2022-04-16 15:31:26 +08:00
Dreamacro
2c9a4d276a Chore: add more github action cache 2022-04-14 23:37:41 +08:00
Dreamacro
4dfba73e5c Fix: SyscallN should not use nargs 2022-04-14 23:37:19 +08:00
Dreamacro
c282d662ca Fix: make golangci lint support multi GOOS 2022-04-13 17:51:21 +08:00
Anankke
b3d7594813
Chore: add none alias to dummy on ShadowsocksR (#2056) 2022-04-13 10:06:06 +08:00
Guowei Zhao
dd9bdf4e2f
Fix: convert size to unit32 in getoridst to solve some mips64 devices cannot get redirect origin dst (#2041)
Change-Id: I40aa73dcea692132e38db980320a8a07ed427fe6

Co-authored-by: Zhao Guowei <zhaoguowei@bytedance.com>
2022-03-28 14:48:51 +08:00
落心
275cc7edf3
Chore: structure support weakly type from float to int (#2042) 2022-03-25 15:22:31 +08:00
Dreamacro
8c9e0b3884 Chore: use GOAMD64 v1 on build docker image 2022-03-20 11:32:18 +08:00
Kr328
30d4668008
Chore: fix typo (#2033) 2022-03-19 13:58:51 +08:00
Dreamacro
02333a859a Chore: split amd64 v3 to special release 2022-03-19 13:42:06 +08:00
risetechlab
f9cc1cc363
Fix: routing-mark option doesn't work on proxies (#2028) 2022-03-19 13:29:30 +08:00
Dreamacro
fb7d340233 Fix: docker build makefile 2022-03-16 12:13:59 +08:00
Dreamacro
6a661bff0c Migration: go 1.18 2022-03-16 12:10:13 +08:00
suyar
d1dd21417b
Feature: add tzdata to Dockerfile (#2027)
Co-authored-by: suyaqi <suyaqi@wy.net>
2022-03-15 11:30:52 +08:00
Kr328
b866f06414
Chore: move find connection process to tunnel (#2016) 2022-03-12 19:07:53 +08:00
Kr328
9683c297a7
Chore: add more details to process resolving (#2017) 2022-03-09 13:41:50 +08:00
Dreamacro
f6c7281bb7 Chore: update github action workflow 2022-03-06 21:48:37 +08:00
Kr328
83bfe521b1
Fix: should split linux process name with space (#2008) 2022-03-05 18:25:16 +08:00
Dreamacro
b52d0c16e9 Chore: vmess test remove all alterid 2022-02-27 18:00:04 +08:00
Kaming Chan
132a6a6a2f
Fix: listener tcp keepalive & reuse net.BufferedConn (#1987) 2022-02-23 11:22:46 +08:00
Dreamacro
03e4b5d525 Chore: use golangci-lint config file 2022-02-19 00:08:51 +08:00
Dreamacro
a0221bf897 Fix: routing-mark should effect on root 2022-02-17 14:23:47 +08:00
Dreamacro
b1a639feae Fix: domain trie search 2022-01-26 22:28:13 +08:00
Kr328
cfe7354c07
Improve: change provider file modify time when updated (#1918) 2022-01-18 13:32:47 +08:00
thank243
9732efe938
Fix: tls handshake requires a timeout (#1893) 2022-01-15 19:33:21 +08:00
Digital Pencil
8f3385bbb6
Feature: support snell v3 (#1884) 2022-01-10 20:24:20 +08:00
Dreamacro
d237b041b3 Fix: ignore empty dns server error 2022-01-05 11:41:31 +08:00
Dreamacro
3cb87e083c Fix: duplicate provider err typo 2022-01-03 17:21:27 +08:00
Dreamacro
8c6d0c6757 Chore: fix docker dependencies security warning 2022-01-02 11:15:40 +08:00
Dreamacro
cb95326aca Chore: update dependencies 2022-01-02 01:15:49 +08:00
HamsterReserved
8679968ab0
Fix: multiple port string parsing overflow (#1868)
Ports in TCP and UDP should be parsed as an unsigned integer,
otherwise ports > 32767 get truncated to 32767. As this is
the case with Metadata.UDPAddr(), this fundamentally breaks
UDP connections where demand for high port numbers is high.

This commit fixes all known cases where ParseInt is used for ports,
and has been verified to fix Discord voice connections on port
50001~50004.

Fixes: d40e5e4fe6c11311ee1de82779a985c3ca47d03a

Co-authored-by: Hamster Tian <haotia@gmail.com>
2022-01-02 01:09:29 +08:00
Dreamacro
204a72bbd3 Chore: remove forward compatible code 2022-01-02 00:48:57 +08:00
Kr328
7267c58913
Chore: ReCreate* do side effect job (#1849) 2021-12-26 22:08:53 +08:00
Kr328
14ae87fcd0
Chore: remove reduce regex compile (#1855) 2021-12-26 20:47:12 +08:00
Fan
ee6fc12709
Fix: when both providers and proxies are present, use the health check configuration for proxies (#1821)
Co-authored-by: Ho <ho@fluidex.com>
2021-12-12 20:37:30 +08:00
bobo liu
78e105f3b2
Chore: builtin right mime of .js (#1808) 2021-12-08 13:38:25 +08:00
Rick
08607fb6b4
Feature: add linux/arm/v6 for the container image (#1771) 2021-12-02 21:12:45 +08:00
Dreamacro
075d8ed094 Fix: fakeip pool cycle used 2021-11-23 22:01:49 +08:00
Dreamacro
b1bed7623d Fix: provider filter potential panic 2021-11-21 17:44:03 +08:00
beyondkmp
1401a82bb0
Feature: add filter on proxy provider (#1511) 2021-11-20 23:38:49 +08:00
Dreamacro
4524cf4418 Fix: should return io.EOF immediately 2021-11-20 12:44:31 +08:00
Dreamacro
0db15d46c3 Change: use nop packet conn for reject 2021-11-20 12:34:14 +08:00
Dreamacro
08c43b8876 Fix: revert ssr udp fix 2021-11-14 14:48:00 +08:00
Dreamacro
499beb7344 Fix: bind iface should throw control error 2021-11-10 22:19:11 +08:00
Dreamacro
c9be614821 Fix: windows arm7 build 2021-11-08 21:24:39 +08:00
Dreamacro
b56d35040d Chore: update dependencies and rename profile props 2021-11-08 20:48:29 +08:00
bobo liu
bd2ea2b917
Feature: mark on socket (#1705) 2021-11-08 16:59:48 +08:00
Dreamacro
e622d8dd38 Fix: parse dial interface option 2021-11-08 13:31:08 +08:00
Dreamacro
d40e5e4fe6 Fix: codeql alerts 2021-11-08 00:32:21 +08:00
Dreamacro
1a7830f18e
Feature: dial different NIC for all proxies (#1714) 2021-11-07 16:48:51 +08:00
Dreamacro
bcb301b730 Chore: adjust all udp alloc size 2021-11-03 22:29:24 +08:00
Dreamacro
ebbc9604ce Chore: use uber max procs 2021-10-27 21:27:19 +08:00
Blaise Wang
a7aea12aa6
Fix: remove ResponseHeaderTimeout limitation (#1690) 2021-10-20 13:44:05 +08:00
Dreamacro
c6cceeb0c5 Chore: use alpn http 1.1 only on trojan websocket by default 2021-10-19 22:34:18 +08:00
Dreamacro
967932d02c Fix: set dnsmode behavior 2021-10-18 23:03:25 +08:00
Dreamacro
81d5da51a3 Fix: unexpected proxy dial behavior on mapping mode 2021-10-18 21:08:27 +08:00
Dreamacro
fea9d1c5e2 Fix: replace vmess grpc test image 2021-10-16 20:35:06 +08:00
Dreamacro
df3a491d40 Feature: support trojan websocket 2021-10-16 20:19:59 +08:00
Dreamacro
68753b4ae1 Chore: contexify ProxyAdapter ListenPacket 2021-10-15 21:44:53 +08:00
Dreamacro
583b2a5ace Change: use interface HardwareAddr for dhcp discovery 2021-10-14 22:54:43 +08:00
Dreamacro
13bd601cac Fix: #1660 panic 2021-10-11 21:05:38 +08:00
Dreamacro
3d5681cffd
Feature: persistence fakeip (#1662) 2021-10-11 20:48:58 +08:00
Dreamacro
a1c2478e74 Chore: actions split lint and release 2021-10-11 20:08:18 +08:00
Dreamacro
f1cf7e9269 Style: use gofumpt for fmt 2021-10-10 23:44:09 +08:00
Dreamacro
4ce35870fe Chore: remove deprecated ioutil 2021-10-09 20:35:06 +08:00
beyondkmp
1996bef9e6
Chore: doh request should with id 0 (#1660) 2021-10-07 22:57:55 +08:00
Dreamacro
66cb0b1218 Fix: cache kv db should not block on init 2021-10-05 22:47:26 +08:00
Dreamacro
b9d470cf79 Fix: dhcp client should request special interface 2021-10-05 13:31:19 +08:00
Dreamacro
4f1fac02ab Chore: add remove TODO 2021-10-05 12:42:21 +08:00
Dreamacro
537b672fcf Change: use bbolt as cache db 2021-10-04 19:20:11 +08:00
Kr328
ced9749104
Fix: http proxy should response correct http version (#1651) 2021-09-30 16:30:07 +08:00
bobo liu
9aeb4c8cfe
Improve: avoid bufconn twice (#1650) 2021-09-28 23:15:53 +08:00
Dreamacro
70c8605cca Improve: use one bytes.Buffer pool 2021-09-20 21:02:18 +08:00
Dreamacro
5b1a0a523f Chore: update README.md 2021-09-20 17:22:40 +08:00
Dreamacro
b398f1e6f3 Chore: force set latest go version to action 2021-09-18 00:18:47 +08:00
Dreamacro
b3cd4ebbd3 Fix: use 1.17.x on github actions 2021-09-15 20:21:30 +08:00
Excited Codes
b0f83e401f
Fix: socks4 request continues after authentication failed (#1624) 2021-09-15 16:45:57 +08:00
Xuen Li
f5806d9263
Fix: http/https proxy authentication (#1613) 2021-09-14 00:08:23 +08:00
Dreamacro
55600c49c9 Fix: potential pitfalls 2021-09-13 23:58:48 +08:00
Kr328
beb88cc46f
Fix: should not trust address of http.Client (#1616) 2021-09-13 23:46:39 +08:00
Kr328
d49b38b00f
Fix: should not unmarshal to pointer (#1615) 2021-09-13 23:43:28 +08:00
bobo liu
0c79d1207e
Fix: potential overflow in ssr (#1600) 2021-09-09 20:30:34 +08:00
maskedeken
400dc923e0
Fix: vmess ws headers not set properly (#1595) 2021-09-08 14:44:24 +08:00
Dreamacro
5b7f0de48b Chore: update dependencies 2021-09-07 20:16:07 +08:00
Kr328
a5b950a779
Feature: add dhcp type dns client (#1509) 2021-09-06 23:07:34 +08:00
Excited Codes
a2d59d6ef5
Feature: skip DIRECT proxies in relay (#1583) 2021-09-06 21:39:28 +08:00
Dreamacro
8ef5cdb8be Test: use local clash pkg 2021-09-05 14:38:07 +08:00
Dreamacro
c7b718f651 Test: release resources correctly 2021-09-05 14:25:55 +08:00
Dreamacro
ff56e5c5de Test: fix direct listen fail 2021-09-04 22:44:18 +08:00
Dreamacro
661c417fce Test: use shadowsocks-rust for ss benchmark 2021-09-04 22:31:08 +08:00
Dreamacro
7d20097465 Fix: ssr auth aes128 udp hmac verify 2021-08-30 00:15:57 +08:00
Loyalsoldier
a20b9a3960
Chore: make geoip match case-insensitive (#1574) 2021-08-29 22:19:22 +08:00
Dreamacro
e0d3f926b7 Feature: add geoip-code option 2021-08-25 15:15:13 +08:00
Dreamacro
121bc910f6 Chore: adjust vmess 0rtt code and split xray test 2021-08-22 16:16:45 +08:00
wwqgtxx
4522cdc551
Feature: support xray's ws-0rtt path (#1558) 2021-08-22 16:03:46 +08:00
Dreamacro
410772e81c Test: add vmess ws 0-rtt test 2021-08-22 01:17:29 +08:00
秋のかえで
0267b2efad
Feature: add vmess WebSocket early data (#1505)
Co-authored-by: ShinyGwyn <79344143+ShinyGwyn@users.noreply.github.com>
2021-08-22 00:25:29 +08:00
Digital Pencil
c6d375eda2
Fix: HTTP proxy internal linkage signature (#1555) 2021-08-20 23:38:47 +08:00
Dreamacro
847f41952e Fix: grpc transport path should not escape 2021-08-19 22:11:56 +08:00
Dreamacro
47044ec0d8 Fix: dependabot alerts 2021-08-18 20:20:00 +08:00
Dreamacro
426ca36118 Chore: upgrade test package 2021-08-18 13:31:34 +08:00
Dreamacro
571d2a0075 Migration: go 1.17 2021-08-18 13:26:23 +08:00
Dreamacro
1be09f5751 Chore: fix issue template render type 2021-08-13 22:44:22 +08:00
Dreamacro
2663cb2e6e Chore: update github issue template 2021-08-13 22:35:48 +08:00
Dreamacro
9b0bbb90ff Chore: upgrade github actions 2021-08-07 22:27:23 +08:00
Dreamacro
588645a2c3 Fix: interface nil check panic from previous commit 2021-08-04 23:52:50 +08:00
Dreamacro
1bfebd0d03 Fix: listener patch diff 2021-08-01 00:35:37 +08:00
xᴊᴀsᴏɴʟʏᴜ
3705996974
Chore: split SOCKS version inbound metadata type (#1513) 2021-07-27 13:58:29 +08:00
Dreamacro
09697b7679 Chore: adjust batch 2021-07-23 00:30:23 +08:00
duama
4578b2c826
Fix: remove Content-Length from CONNECT response (#1502) 2021-07-22 18:06:03 +08:00
Dreamacro
b3a293ab07 Chore: benchmark explanation 2021-07-22 00:01:11 +08:00
Dreamacro
507ba16065 Fix: incorrect use batch 2021-07-21 23:53:31 +08:00
Dreamacro
aa9f8a39a3 Fix: socks inbound packet typo 2021-07-21 23:08:52 +08:00
Dreamacro
8d37220566 Fix: limit concurrency number of provider health check 2021-07-21 17:01:15 +08:00
ayanamist
53e17a916b
Chore: logging remote port on request (#1494) 2021-07-19 15:31:38 +08:00
ayanamist
247dd84970
Chore: logging real listen port (#1492) 2021-07-19 14:07:51 +08:00
Dreamacro
c2f3111922 Test: add direct benchmark 2021-07-18 19:26:51 +08:00
Dreamacro
44872300e9 Test: ss use aes-256-gcm and vmess-aead for benchmark 2021-07-18 17:37:23 +08:00
Dreamacro
91ed0118f6 Test: add basic protocol benchmark 2021-07-18 17:23:30 +08:00
xᴊᴀsᴏɴʟʏᴜ
a461c2306a
Feature: SOCKS4/SOCKS4A Inbound Compatible Support (#1491) 2021-07-18 16:09:09 +08:00
Dreamacro
46f4f84442 Chore: use iife replace init in some cases 2021-07-11 19:43:25 +08:00
Dreamacro
250a9f4f84 Fix: reorder apply config to ensure update proxies and rules 2021-07-10 17:01:40 +08:00
Dreamacro
b4292d0972 Fix: staticcheck error 2021-07-06 00:33:13 +08:00
Dreamacro
d755383e39 Chore: move provider interface to constant 2021-07-06 00:31:13 +08:00
Dreamacro
dff1e8f1ce Chore: update dependencies 2021-07-03 21:01:41 +08:00
Dreamacro
995aa7a8fc Fix: remove ClientSessionCache and add NextProtos for vmess to fix #1468 2021-07-03 20:34:44 +08:00
Indust
3ca5d17c40
Fix: enable DNS server message compression (#1451) 2021-06-24 13:38:44 +08:00
ayanamist
244cb370a4
Change: config reload API use default path when both path and payload don't exist (#1447) 2021-06-21 17:33:34 +08:00
Dreamacro
c35cb24bda Chore: use unix.ByteSliceToString transform cstring 2021-06-15 21:03:47 +08:00
Kr328
b6ff08074c
Refactor: plain http proxy (#1443) 2021-06-15 17:13:40 +08:00
Dreamacro
70d53fd45a Chore: update development wiki to README.md 2021-06-13 23:11:49 +08:00
Dreamacro
f231a63e93 Chore: Listener should not expose original net.Listener 2021-06-13 23:05:22 +08:00
Dreamacro
6091fcdfec Style: code style 2021-06-13 17:23:10 +08:00
Fndroid
bcfc15e398
chore: expose udp field to proxies API (#1441) 2021-06-10 15:08:33 +08:00
Dreamacro
045edc188c Style: code style 2021-06-10 14:05:56 +08:00
Rusty Pen
0778591524
Feature: dns resolve domain through nameserver-policy (#1406) 2021-05-19 11:17:35 +08:00
Dreamacro
d5e52bed43 Feature: add protocol test 2021-05-17 20:33:00 +08:00
Dreamacro
06fdd3abe0 Fix: vmess http should use Host header on request 2021-05-16 20:05:41 +08:00
Dreamacro
4e5898197a Fix: build broken 2021-05-13 22:39:33 +08:00
Dreamacro
f96ebab99f Chore: split component to transport 2021-05-13 22:19:34 +08:00
Dreamacro
3c54f99fea Chore: update dependencies 2021-05-08 19:29:12 +08:00
Dreamacro
824f5bd731 Fix: reuse http connection broken on previous commit 2021-05-07 11:08:46 +08:00
Dreamacro
3f3db8476e Fix: HTTP inbound leak 2021-05-06 22:34:37 +08:00
fishg
f375f080da
Fix: skip deleted node from url-test group (#1378)
Co-authored-by: fish <fish@youme.im>
2021-05-01 17:21:09 +08:00
Dreamacro
e19e9ef5a4 Style: code style 2021-04-29 11:23:14 +08:00
Dreamacro
682e65cb54 Style: code style 2021-04-26 20:42:17 +08:00
cntrump
16a6d409d9
Feature: add freebsd arm64 to Makefile (#1370) 2021-04-22 16:38:13 +08:00
Kr328
4186bcf1b2
Fix: should write file if provider initialize from HTTP (#1365) 2021-04-19 17:40:38 +08:00
Kaming Chan
df5112175f
Fix: io timeout when snell v2 reuse connection (#1362) 2021-04-19 14:36:06 +08:00
Dreamacro
d9341a49ea Fix: trojan should safe close connection 2021-04-19 12:20:37 +08:00
Dreamacro
4e9e4b6cde Fix: grpc transport concurrent write 2021-04-14 21:46:05 +08:00
Rusty Pen
936b7012ba
Feature: PROCESS-NAME support freebsd 13, fix panic on unsupported platforms (#1351) 2021-04-14 17:57:17 +08:00
Dreamacro
a9cbd9ec98 Fix: use bufio.Reader on grpc to avoid panic 2021-04-14 00:16:59 +08:00
Dreamacro
c9943fb857 Fix: grpc implementation SetDeadline for udp issue 2021-04-13 23:34:33 +08:00
sprov
a40274e2a2
Fix: vmess aead writer concurrent write (#1350) 2021-04-13 23:32:53 +08:00
Serhat Şevki Dinçer
b59d45c660
Feature: add CodeQL security checks (#1349) 2021-04-13 21:25:55 +08:00
Dreamacro
7b01e103c2 Chore: use correctly vmess http2 default host 2021-04-10 12:10:10 +08:00
Dreamacro
93a8acecce Fix: vmess h2 use server as host if host option is empty 2021-04-09 18:15:46 +08:00
Dreamacro
586bb91c0c Fix: grpc transport panic 2021-04-09 18:11:07 +08:00
Dreamacro
baf03b81e3 Fix: remove unused function 2021-04-08 22:27:41 +08:00
Dreamacro
9807e1189c Chore: update dependencies 2021-04-08 22:15:30 +08:00
Dreamacro
3d5a0d9f73 Fix: trojan/vmess grpc broken 2021-04-07 22:57:46 +08:00
Dreamacro
cc96187f58 Fix: trojan grpc udp broken 2021-04-05 23:26:13 +08:00
Dreamacro
3aefa1d924 Chore: some chores 2021-04-05 13:31:10 +08:00
Dreamacro
42e21b3733 Chore: refine go import 2021-04-05 13:00:49 +08:00
Dreamacro
0a35237915 Fix: should reset fast node when tolerance enable and not alive on url-test group 2021-04-04 17:40:25 +08:00
Dreamacro
a1f3a5ea26 Chore: -v add golang version 2021-04-04 17:36:22 +08:00
Loyalsoldier
e63f995258
Chore: update dependencies (#1331) 2021-04-03 14:59:03 +08:00
Dreamacro
d0c829c578 Fix: domain dns should follow hosts config, close #1318 2021-04-01 21:20:44 +08:00
Dreamacro
4ad9761b32 Fix: don't resolve AAAA record when ipv6 is false and use go dns resolver 2021-04-01 18:03:30 +08:00
Coel Wu
1f593d37fb
Chore: use mixed-port instead of port when initial config (#1319) 2021-04-01 15:35:33 +08:00
Dreamacro
109bfcb0f9 Feature: add vmess aead header support 2021-03-30 17:34:16 +08:00
Dreamacro
7ee49f5171 Fix: HTTP server should close when Connection is close 2021-03-30 16:33:49 +08:00
Dreamacro
d759d16944 Style: cleanup code 2021-03-24 01:00:21 +08:00
Dreamacro
807d53c1e7 Chore: Clarify the definition of StreamConn and DialContext 2021-03-22 23:26:20 +08:00
Dreamacro
1355196b7c Fix: grpc connection panic 2021-03-18 23:19:00 +08:00
ShinyGwyn
573316bcde
Feature: add gRPC Transport for vmess/trojan (#1287)
Co-authored-by: eMeab <32988354+eMeab@users.noreply.github.com>
Co-authored-by: Dreamacro <8615343+Dreamacro@users.noreply.github.com>
2021-03-18 19:40:34 +08:00
Dreamacro
784c28266c Fix: vmess http broken 2021-03-18 17:11:10 +08:00
wwqgtxx
5da1b2a8aa
Fix: set metadata.AddrType if host is ip string after remove host (#1291) 2021-03-12 17:41:37 +08:00
Dreamacro
0976d27cb1 Fix: github actions remove prerelease option 2021-03-10 21:22:22 +08:00
Dreamacro
6c83ff3496 Chore: update dependencies 2021-03-10 21:13:23 +08:00
Dreamacro
f7f97ef625 Fix: some HTTP proxy request broken 2021-03-10 16:23:55 +08:00
Dreamacro
5acdd72a1d Fix: remove host if host is ip string 2021-03-10 12:49:30 +08:00
Jason Lyu
f53686103d
Chore: reset udp timeout after sending each packet (#1260) 2021-02-26 10:40:55 +08:00
Dreamacro
f63c9eb22f Chore: update staticcheck command on actions 2021-02-21 19:37:37 +08:00
Dreamacro
a37243cf30 Fix: store cache correctly 2021-02-21 01:07:22 +08:00
Dreamacro
b3c1b4a840 Chore: update dependencies 2021-02-19 20:35:10 +08:00
Dreamacro
14bbf6eedc Feature: support store group selected node to cache (enable by default) 2021-02-18 23:41:50 +08:00
peeweep
aa81193d5b
Feature: add darwin arm64 to Makefile (Apple Silicon) (#1234) 2021-02-18 18:15:09 +08:00
goomadao
9eb98e399d
Improve: refactor ssr and fix #995 (#1189)
Co-authored-by: goomada <madao@DESKTOP-IOEBS0C.localdomain>
2021-02-15 14:32:03 +08:00
Fndroid
d48cfecf60
Chore: API support patch ipv6 config (#1217) 2021-02-05 16:43:42 +08:00
Kr328
6036fb63ba
Chore: avoid provider unnecessary write file operations (#1210) 2021-02-02 17:52:46 +08:00
Kr328
cd48f69b1f
Fix: wrap net.Conn to avoid using *net.TCPConn.(ReadFrom) (#1209) 2021-02-01 20:06:45 +08:00
Loyalsoldier
fcc594ae26
Chore: use jsdelivr CDN for Country.mmdb (#1057) 2021-01-30 00:40:35 +08:00
Dreamacro
f4de055aa1 Refactor: make inbound request contextual 2021-01-23 14:58:09 +08:00
Junjie Yuan
35925cb3da
Chore: standardized Dockerfile label (#1191)
Signed-off-by: Junjie Yuan <yuan@junjie.pro>
2021-01-20 16:08:24 +08:00
goomadao
ff430df845
Fix: connectivity of ssr auth_chain_(ab) protocol (#1180) 2021-01-13 23:35:41 +08:00
Dreamacro
e4cdea2111 chore: use singleDo to get interface info 2021-01-13 17:30:54 +08:00
Fndroid
b6ee47a541
Fix: get general should return correct result (#1172) 2021-01-07 13:59:39 +08:00
Student414
b25009cde7
Fix: unnecessary write operation on provider (#1170) 2021-01-06 14:20:15 +08:00
Dreamacro
6fedd7ec84 Fix: dns client should not bind local address 2021-01-04 00:51:53 +08:00
Jason Lyu
9619c3fb20
Fix: support unspecified UDP bind address (#1159) 2020-12-31 18:58:03 +08:00
Keyi Xie
02d029dd2d
Fix: close http Response body on provider (#1154) 2020-12-29 11:28:22 +08:00
Dreamacro
09c28e0355 Fix: fallback bind fn should not bind global unicast 2020-12-28 22:24:58 +08:00
Dreamacro
3600077f3b Chore: update dependencies 2020-12-27 18:59:59 +08:00
Dreamacro
de7656a787 Chore: update premium README 2020-12-27 00:14:24 +08:00
Dreamacro
5dfe7f8561 Fix: handle keep alive on http connect proxy 2020-12-24 14:55:11 +08:00
Dreamacro
ed27898a33 Fix: snell should support the config without obfs 2020-12-24 13:47:56 +08:00
icpz
532396d25c
Fix: PROCESS-NAME rule for UDP sessions on Windows (#1140) 2020-12-22 15:13:44 +08:00
Dreamacro
4b1b494164 Chore: move find process name to a single part 2020-12-17 22:17:27 +08:00
Kr328
0d33dc3eb9
Chore: health checks return immediately if completed (#1097) 2020-11-24 22:52:23 +08:00
Dreamacro
994cbff215 Fix: should not log rule when rule = nil 2020-11-22 23:38:12 +08:00
Dreamacro
bea2ee8bf2 Chore: log rule msg on dial error 2020-11-22 19:12:36 +08:00
Dreamacro
1e5593f1a9 Chore: update dependencies 2020-11-20 20:36:20 +08:00
Dreamacro
34febc4579 Chore: more detailed error when dial failed 2020-11-20 00:27:37 +08:00
Dreamacro
97581148b5 Fix: static check 2020-11-19 00:56:36 +08:00
Dreamacro
0402878daa Feature: add lazy for proxy group and provider 2020-11-19 00:53:22 +08:00
Dreamacro
4735f61fd1 Feature: add disable-udp option for all proxy group 2020-11-13 21:48:52 +08:00
Dreamacro
16ae107e70 Chore: push image to github docker registry 2020-11-10 15:19:12 +08:00
maskedeken
83efe2ae57
Feature: add TCP TPROXY support (#1049) 2020-11-09 10:46:10 +08:00
Jason Lyu
87e4d94290
Fix: tunnel manager & tracker race condition (#1048) 2020-10-29 17:51:14 +08:00
Dreamacro
b98e9ea202 Improve: #1038 and #1041 2020-10-29 00:32:31 +08:00
uchuhimo
9a62b1081d
Feature: support round-robin strategy for load-balance group (#1044) 2020-10-28 22:35:02 +08:00
Jason Lyu
2cd1b890ce
Fix: tunnel UDP race condition (#1043) 2020-10-28 21:26:50 +08:00
Dreamacro
ba060bd0ee Fix: should not bind interface on local address 2020-10-25 20:31:01 +08:00
Dreamacro
b1795b1e3d Fix: stale typo 2020-10-25 11:53:03 +08:00
Dreamacro
76c9820065 Fix: undefined variable 2020-10-23 17:49:34 +08:00
Dreamacro
2db4ce57ef Chore: make stale time into 60 days 2020-10-23 00:30:17 +08:00
Dreamacro
50b3d497f6 Feature: use native syscall to bind interface on Linux and macOS 2020-10-22 22:32:03 +08:00
Dreamacro
2321e9139d Chore: deprecated eapache/channels 2020-10-20 17:44:39 +08:00
Dreamacro
baabf21340 Chore: update github workflow 2020-10-17 13:46:05 +08:00
Dreamacro
d3bb4c65a8 Fix: missing fake-ip record should return error 2020-10-17 12:52:43 +08:00
kongminhao
8c3e2a7559
Chore: fix typo (#1017) 2020-10-14 19:56:02 +08:00
Dreamacro
bc52f8e4fd Chore: return empty record in SVCB/HTTPSSVC on fake-ip mode 2020-10-13 00:15:49 +08:00
Dreamacro
d3b14c325f Fix: the priority of fake-ip-filter 2020-10-09 00:04:24 +08:00
Loyalsoldier
4859b158b4
Chore: make builds reproducible (#1006) 2020-10-08 17:54:38 +08:00
Dreamacro
d65b51c62b Feature: http support custom sni 2020-10-02 11:34:40 +08:00
Melvin
a6444bb449
Feature: support domain in fallback filter (#964) 2020-09-28 22:17:10 +08:00
Dreamacro
e09931dcf7 Chore: remove broken test temporarily 2020-09-26 20:36:52 +08:00
小傅Fox
5bd189f2d0
Feature: support VMess HTTP/2 transport (#903) 2020-09-26 20:33:57 +08:00
Dreamacro
8766287e72 Chore: sync necessary changes from premium 2020-09-21 22:22:07 +08:00
Dreamacro
10f9571c9e Fix: pool gc test 2020-09-21 00:44:47 +08:00
Kaming Chan
96a8259c42
Feature: support snell v2 (#952)
Co-authored-by: Dreamacro <8615343+Dreamacro@users.noreply.github.com>
2020-09-21 00:33:13 +08:00
Dreamacro
68dd0622b8 Chore: code style 2020-09-20 15:53:27 +08:00
Kr328
558ac6b965
Chore: split enhanced mode instance (#936)
Co-authored-by: Dreamacro <305009791@qq.com>
2020-09-17 10:48:42 +08:00
icpz
e773f95f21
Fix: PROCESS-NAME on FreeBSD 11.x (#947) 2020-09-07 17:43:34 +08:00
Dreamacro
314ce1c249 Feature: vmess network http support TLS (https) 2020-09-04 21:27:19 +08:00
Kr328
13275b1aa6
Chore: use only one goroutine to handle statistic (#940) 2020-09-03 10:30:18 +08:00
icpz
02d9169b5d
Fix: potential PCB buffer overflow on bsd systems (#941) 2020-09-03 10:27:20 +08:00
Kr328
7631bcc99e
Improve: use atomic for connection statistic (#938) 2020-09-02 16:34:12 +08:00
Dreamacro
a32ee13fc9 Feature: reuse dns resolver cache when hot reload 2020-08-31 00:32:18 +08:00
Dreamacro
b8ed738238 Chore: update actions version 2020-08-30 23:06:21 +08:00
Dreamacro
687c2a21cf Fix: vmess UDP option should be effect 2020-08-30 22:49:55 +08:00
Loyalsoldier
ad18064e6b
Chore: code style (#933) 2020-08-30 19:53:00 +08:00
Dreamacro
c9735ef75b Fix: static check 2020-08-25 22:36:38 +08:00
Dreamacro
b70882f01a Chore: add static check 2020-08-25 22:32:23 +08:00
Dreamacro
5805334ccd Chore: pass staticcheck 2020-08-25 22:19:59 +08:00
R3pl4c3r
c1b4382fe8
Feature: add Windows ARM32 build (#902)
Co-authored-by: MarksonHon <50002150+MarksonHon@users.noreply.github.com>
2020-08-16 13:50:56 +08:00
Dreamacro
008743f20b Chore: update dependencies 2020-08-16 11:32:51 +08:00
Kr328
50d778da3c
Chore: cache process name when resolve failed (#900) 2020-08-15 16:55:55 +08:00
goomadao
8b7c731fd6
Fix: ssr broken (#895) 2020-08-12 20:50:56 +08:00
Dreamacro
0b7918de9c Migration: go 1.15 2020-08-12 13:47:50 +08:00
maddie
4f61c04519
Fix: ssr typo (#887) 2020-08-11 10:35:30 +08:00
Kr328
89cf06036d
Feature: dns server could lookup hosts (#872) 2020-08-11 10:28:17 +08:00
goomadao
4ba6f248bc
Fix: ssr bounds out of range panic (#882) 2020-08-11 10:17:40 +08:00
Fndroid
83a684c551
Change: adjust tolerance logic (#864) 2020-08-06 20:12:03 +08:00
icpz
92a23f1eab
Feature: PROCESS-NAME for windows (#840) 2020-08-06 19:59:20 +08:00
Dreamacro
622ac45258 Feature: PROCESS-NAME for freebsd (#855) 2020-07-31 20:01:19 +08:00
icpz
791d203b5f
Fix: update cache if a process was found (#850) 2020-07-30 17:15:06 +08:00
icpz
77d6f9ae6f
Fix: handle snell server reported error message properly (#848) 2020-07-30 15:54:26 +08:00
icpz
b1d9dfd6bf
Improve: simplify macOS process searching 2020-07-29 11:27:18 +08:00
Kr328
6532947e71
Fix: invert should resolve ip (#836) 2020-07-27 13:47:00 +08:00
Dreamacro
6c5f23f552 Merge branch 'dev' of github.com:Dreamacro/clash into dev 2020-07-27 11:58:02 +08:00
Dreamacro
78c3034158 Chore: rename NoResolveIP to ShouldResolveIP 2020-07-27 11:57:55 +08:00
ayanamist
8f0098092d
Fix: protect alive with atomic value (#834) 2020-07-25 17:47:11 +08:00
goomadao
33a6579a3a
Feature: add ssr support (#805)
* Refactor ssr stream cipher to expose iv and key

References:
https://github.com/Dreamacro/go-shadowsocks2
https://github.com/sh4d0wfiend/go-shadowsocksr2

* Implement ssr obfs

Reference:
https://github.com/mzz2017/shadowsocksR

* Implement ssr protocol

References:
https://github.com/mzz2017/shadowsocksR
https://github.com/shadowsocksRb/shadowsocksr-libev
https://github.com/shadowsocksr-backup/shadowsocksr
2020-07-22 23:02:15 +08:00
Sandothers
b4221d4b74
Chore: README.md style fixed (#825)
make every item in TODO list has the same style
2020-07-22 21:34:37 +08:00
Dreamacro
0e4b9daaad Improve: add cache for macOS PROCESS-NAME 2020-07-22 20:35:27 +08:00
Dreamacro
ee72865f48 Fix: recycle buf on http obfs 2020-07-22 20:29:39 +08:00
Kr328
6521acf8f1
Improve: check uid on process search & fix typo (#824) 2020-07-22 20:22:34 +08:00
Kr328
4f73410618
Feature: add PROCESS-NAME rule for linux (#822) 2020-07-22 19:05:10 +08:00
Kr328
20eff200b1
Fix: dns should put msg to cache while exchangeWithoutCache (#820) 2020-07-20 21:16:36 +08:00
Dreamacro
ae1e1dc9f6 Feature: support PROCESS-NAME on macOS 2020-07-19 13:18:23 +08:00
Dreamacro
cf9e1545a4 Improve: fix go test race detect 2020-07-18 20:56:13 +08:00
Dreamacro
6c7a8fffe0 Chore: should not write file on file provider 2020-07-18 19:32:40 +08:00
Dreamacro
3a3e2c05af Chore: add rule payload in log 2020-07-18 19:22:09 +08:00
John Smith
02c7fd8d70
Fix: write msg cache multiple times (#812)
Co-authored-by: john.xu <john.xu@bytedance.com>
2020-07-17 17:34:40 +08:00
Dreamacro
e6aa452b51 Fix: ticker leak 2020-07-13 00:25:54 +08:00
Dreamacro
35449bfa17 Feature: add github stale action 2020-07-09 10:27:05 +08:00
Dreamacro
acd51bbc90 Fix: obfs host should not have 80 port 2020-07-01 00:01:36 +08:00
Birkhoff Lee
f44cd9180c
Chore: update GitHub issue template 2020-06-30 13:55:26 +08:00
Birkhoff Lee
93c987a6cb
Fix: typo in dialer.go (#767) 2020-06-28 10:59:04 +08:00
Birkhoff Lee
3f0584ac09
Chore: move documentations to wiki (#766) 2020-06-28 10:39:30 +08:00
Dreamacro
59968fff1c Fix: github actions tag build 2020-06-27 21:09:04 +08:00
Dreamacro
7c62fe41b4 Chore: remove forward compatibility code 2020-06-27 14:28:10 +08:00
Dreamacro
2781090405 Chore: move experimental features to stable 2020-06-27 14:19:31 +08:00
Kr328
14c9cf1b97
Fix: domain trie crash if not match in #758 (#762) 2020-06-24 19:46:37 +08:00
Kr328
3dfff84cc3
Fix: domain trie should backtrack to parent if match fail (#758) 2020-06-24 18:41:23 +08:00
Dreamacro
5f3db72422 Fix: docker multiplatform build 2020-06-21 12:38:14 +08:00
Dreamacro
18bb285a90 Fix: external-ui should relative with clash HomeDir 2020-06-18 21:33:57 +08:00
Dreamacro
60bad66bc3 Change: ipv6 logic 2020-06-18 18:11:02 +08:00
limgmk
99b34e8d8b
Fix: cannot listen socks5 port on wsl (#748) 2020-06-15 10:34:15 +08:00
Kr328
9f1d85ab6e
Fix: fake-ip-filter on fakeip mode should lookup ip-host mapping (#743) 2020-06-14 00:41:53 +08:00
Dreamacro
4323dd24d0 Fix: don't auto health check on provider health check disabled 2020-06-14 00:32:04 +08:00
Dreamacro
59bda1d547 Change: local resolve DNS in UDP request due to TURN failed 2020-06-12 23:39:03 +08:00
Dreamacro
1c760935f4 Chore: add error msg when dial vmess 2020-06-11 22:19:47 +08:00
Dreamacro
4f674755ce Fix: trim . for socks5 host 2020-06-11 12:11:44 +08:00
Dreamacro
f1b792bd26 Fix: trim FQDN on http proxy request 2020-06-11 11:10:08 +08:00
Dreamacro
58c077b45e Fix: actions tag replace 2020-06-08 13:53:04 +08:00
Dreamacro
1854199c47 Chore: update dependencies 2020-06-07 18:14:04 +08:00
Dreamacro
ecac8eb8e5 Fix: add lock for inbound proxy recreate 2020-06-07 17:57:41 +08:00
Dreamacro
48cff50a4c Feature: connections add rule payload 2020-06-07 17:28:56 +08:00
Dreamacro
fb628e9c62 Feature: add default hosts localhost 2020-06-07 17:25:51 +08:00
Dreamacro
2dece02df6 Chore: code adjustments 2020-06-07 16:54:41 +08:00
Dreamacro
8f32e6a60f Improve: safe write provider file 2020-06-07 00:36:54 +08:00
Dreamacro
98614a1f3f Chore: move rule parser to rules 2020-06-05 17:43:50 +08:00
Dreamacro
c1b4c94b9c Chore: remove unused hooks directory 2020-06-05 12:49:24 +08:00
Dreamacro
7ddbc12cdb Chore: rm unused Dockerfile 2020-06-04 10:57:43 +08:00
Dreamacro
1a217e21e9 Chore: use actions build docker image 2020-06-04 10:38:30 +08:00
Dreamacro
147a7ce779 Fix: panic of socks5 client missing authentication 2020-06-03 18:49:57 +08:00
Dreamacro
fb0289bb4c Chore: open ForceAttemptHTTP2 on DoH 2020-06-01 13:43:26 +08:00
Dreamacro
3e7970612a Chore: provider error adjust 2020-06-01 00:39:41 +08:00
Dreamacro
46244a6496 Chore: mode use lower case (backward compatible) 2020-06-01 00:32:37 +08:00
Dreamacro
71d30e6654 Feature: support vmess tls custom servername 2020-06-01 00:27:04 +08:00
Dreamacro
008731c249 Fix: make os.Stat return correct err on provider 2020-05-29 21:56:29 +08:00
Dreamacro
5628f97da1 Feature: add tolerance for url-test 2020-05-29 17:47:50 +08:00
Dreamacro
8d0c6c6e66 Feature: domain trie support wildcard alias 2020-05-28 12:13:05 +08:00
Dreamacro
5073c3cde8 Chore: add trimpath for go build 2020-05-20 15:13:33 +08:00
bytew021
3a27cfc4a1
Feature: add Mixed(http+socks5) proxy listening (#685) 2020-05-12 11:29:53 +08:00
Dreamacro
3638b077cd Chore: update premium link 2020-05-08 21:52:17 +08:00
Dreamacro
646bd4eeb4 Chore: update dependencies and README.md 2020-05-07 21:58:53 +08:00
duama
752f87a8dc
Feature: support proxy-group in relay (#597) 2020-05-07 21:42:52 +08:00
Comzyh
b979ff0bc2
Feature: implemented a strategy similar to optimistic DNS (#647) 2020-05-07 15:10:14 +08:00
Kr328
b085addbb0
Fix: use domain first on direct dial (#672) 2020-05-05 12:39:25 +08:00
Dreamacro
94e0e4b000 Fix: make selector react immediately 2020-04-30 20:13:27 +08:00
Kr328
7d51ab5846
Fix: dns return empty success for AAAA & recursion in fake ip mode (#663) 2020-04-29 11:21:37 +08:00
Richard Yu
41a9488cfa
Feature: add more command-line options (#656)
add command-line options to override `external-controller`, `secret` and `external-ui` (#531)
2020-04-27 22:23:09 +08:00
comwrg
51b6b8521b
Fix: typo (#657) 2020-04-27 22:20:35 +08:00
Dreamacro
e5379558f6 Fix: redir-host should lookup hosts 2020-04-27 21:28:24 +08:00
Dreamacro
d1fd57c432 Fix: select group can use provider real-time 2020-04-27 21:23:23 +08:00
Dreamacro
18603c9a46 Improve: provider can be auto GC 2020-04-26 22:38:15 +08:00
Dreamacro
5036f62a9c Chore: update dependencies 2020-04-25 00:43:32 +08:00
Kr328
2047b8eda1
Chore: remove unused parameter netType (#651) 2020-04-25 00:39:30 +08:00
Dreamacro
0e56c195bb Improve: pool buffer alloc 2020-04-25 00:30:40 +08:00
Dreamacro
2b33bfae6b Fix: API auth bypass 2020-04-24 23:49:35 +08:00
Dreamacro
3fc6d55003 Fix: domain wildcard behavior 2020-04-24 23:49:19 +08:00
Dreamacro
8eddcd77bf Chore: dialer hook should return a error 2020-04-24 23:48:55 +08:00
Siji
27dd1d7944
Improve: add basic auth support for provider URL (#645) 2020-04-20 21:22:23 +08:00
Texot
b1cf2ec837
Fix: dns tcp-tls X509.HostnameError (#638) 2020-04-17 11:29:59 +08:00
Dreamacro
84f627f302 Feature: verify mmdb on initial 2020-04-16 19:12:25 +08:00
Dreamacro
5c03613858 Chore: picker support get first error 2020-04-16 18:31:40 +08:00
Dreamacro
1825535abd Improve: recycle buffer after packet used 2020-04-16 18:19:36 +08:00
duama
2750c7ead0
Fix: set SO_REUSEADDR for UDP listeners on linux (#630) 2020-04-11 21:45:56 +08:00
black-desk
3ccd7def86
Fix: typo (#624) 2020-04-08 15:49:12 +08:00
Dreamacro
65dab4e34f Feature: domain trie support dot dot wildcard 2020-04-08 15:45:59 +08:00
Dreamacro
5591e15452 Fix: vmess pure TLS mode 2020-04-03 16:04:24 +08:00
Dreamacro
19f809b1c8 Feature: refactor vmess & add http network 2020-03-31 16:07:21 +08:00
Kr328
206767247e
Fix: udp traffic track (#608) 2020-03-28 20:05:38 +08:00
Dreamacro
518354e7eb Fix: dns request panic and close #527 2020-03-24 10:13:53 +08:00
Dreamacro
86dfb6562c Chore: update dependencies 2020-03-22 17:41:58 +08:00
duama
c0a2473160
Feature: support relay (proxy chains) (#539) 2020-03-21 23:46:49 +08:00
Birkhoff Lee
70a19b999d
Chore: update README to better describe what Clash do atm (#586) 2020-03-20 12:35:30 +08:00
Dreamacro
e54f51af81 Fix: trojan split udp packet 2020-03-20 00:02:05 +08:00
Dreamacro
b068466108 Improve: add session cache for trojan 2020-03-19 22:39:09 +08:00
Dreamacro
b562f28c1b Feature: support trojan 2020-03-19 20:26:53 +08:00
Dreamacro
230e01f078 Fix: config parse panic 2020-03-19 11:04:56 +08:00
Kaming Chan
082847b403
Chore: support MarshalYAML to some config filed (#581) 2020-03-15 19:40:39 +08:00
Dreamacro
9471d80785 Fix: dns fallback logic 2020-03-13 00:11:54 +08:00
duama
b263095533
Fix: TPROXY fakeip (#572) 2020-03-10 20:36:24 +08:00
Ti
14d5137703
Fix: rules parse (#568) 2020-03-09 10:40:21 +08:00
Dreamacro
d8a771916a Fix: provider parse 2020-03-08 23:34:46 +08:00
duama
f7f30d3406
Feature: add UDP TPROXY support on Linux (#562) 2020-03-08 21:58:49 +08:00
Dreamacro
b2c9cbb43e Chore: update dependencies 2020-03-08 13:01:06 +08:00
Dreamacro
c733f80793 Fix: #563 and fallback error return 2020-03-08 13:00:42 +08:00
Dreamacro
88d8f93793 Change: rename some field 2020-03-07 20:01:24 +08:00
Dreamacro
e57a13ed7a Fix: mutable SplitAddr cause panic 2020-03-02 23:47:23 +08:00
Dreamacro
23525ecc15 Migration: go 1.14 2020-03-01 01:48:08 +08:00
Dreamacro
814bd05315 Fix: ss udp return error when addr parse failed 2020-03-01 01:46:02 +08:00
Wu Haotian
e81b88fb94
Feature: add configuration test command (#524) 2020-02-29 17:48:26 +08:00
Dreamacro
c4994d6429 Fix: dns not cache RcodeServerFailure 2020-02-25 21:53:28 +08:00
Mac_Zhou
0740d20ba0
Chore: disable url-test http redirect (#536) 2020-02-25 16:08:13 +08:00
Dreamacro
9eaca6e4ab Fix: provider fallback should reparse proxies 2020-02-22 15:18:03 +08:00
Dreamacro
609869bf5a Change: make ping under authentication 2020-02-21 18:00:19 +08:00
Dreamacro
d68339cea7 Fix: socks5 inbound return remote udp addr for identity 2020-02-20 11:29:16 +08:00
Dreamacro
0f4cdbf187 Chore: remove unused code 2020-02-18 16:05:12 +08:00
Dreamacro
f3f8e7e52f Chore: remove println 2020-02-18 14:26:42 +08:00
Dreamacro
8d07c1eb3e Chore: initial config with port 2020-02-18 13:48:15 +08:00
Dreamacro
46edae9896 Fix: domain dns crash 2020-02-17 22:13:15 +08:00
Dreamacro
df0ab6aa8e Fix: ipv6 dns crash 2020-02-17 20:11:46 +08:00
Dreamacro
7b48138ad0 Fix: vmess udp crash 2020-02-17 17:34:19 +08:00
Dreamacro
e9032c55fa Chore: update dependencies 2020-02-17 12:25:55 +08:00
Dreamacro
d75cb069d9 Feature: add default-nameserver and outbound interface 2020-02-15 21:42:46 +08:00
Dreamacro
f69f635e0b Chore: add issue templates 2020-02-14 19:16:43 +08:00
Dreamacro
8b5e511426 Fix: use the fastest whether the result is successful 2020-02-14 16:36:20 +08:00
Dreamacro
6641bf7c07 Fix: vmessUDPConn should return a correctly address 2020-02-12 13:12:07 +08:00
Dreamacro
afc9f3f59a Chore: use custom dialer 2020-02-09 17:02:48 +08:00
Dreamacro
a55be58c01 Fix: provider should fallback to read remote when local file invalid 2020-02-08 16:21:52 +08:00
Dreamacro
dcf97ff5b4 Fix: should prehandle metadata before resolve 2020-02-07 20:53:43 +08:00
Dreamacro
72c0af9739 Chore: udp resolve ip on local 2020-01-31 19:26:33 +08:00
Dreamacro
b0f9c6afa8 Fix: should close socks udp PacketConn 2020-01-31 15:03:59 +08:00
Dreamacro
19bb0b655c Fix: match log display 2020-01-31 14:58:54 +08:00
Dreamacro
26ce3e8814 Improve: udp NAT type 2020-01-31 14:43:54 +08:00
Dreamacro
aa207ec664 Fix: qemu permission 2020-01-30 21:19:51 +08:00
Dreamacro
c626b988a6 Fix: add docker hub pre build 2020-01-30 17:25:55 +08:00
Jason Chen
82c387e92b
Chore: fix typo (#490) 2020-01-30 17:03:10 +08:00
Dreamacro
14fb789002 Feature: add arm32 and arm64 docker image 2020-01-28 16:39:52 +08:00
Kr328
9071351022 Chore: aggregate mmdb (#474) 2020-01-11 21:07:01 +08:00
comwrg
f688eda2c2 Chore: fix typo (#479) 2020-01-11 21:02:55 +08:00
Kr328
2810533df4 Chore: export raw config struct (#475) 2020-01-11 00:22:34 +08:00
Kr328
6b7144acce Chore: export reset manager statistic api (#476) 2020-01-11 00:20:10 +08:00
Comzyh
e68c0d088b Fix: upstream dns ExchangeContext workaround (#468) 2020-01-10 14:13:44 +08:00
Dreamacro
2c0cc374d3 Fix: README typo 2020-01-09 18:13:15 +08:00
Soff
86d3d77a7f Chore: increase DNS timeout (#464) 2020-01-01 19:23:34 +08:00
Dreamacro
14a3ff32f6 Chore: update dependencies 2020-01-01 18:30:26 +08:00
Dreamacro
50704eaeeb Fix: udp crash 2019-12-31 14:47:00 +08:00
Dreamacro
38458cc4d0 Migration: change geoip address 2019-12-31 12:30:42 +08:00
Dreamacro
b19a49335f Fix: http vehicle shouldn't save file 2019-12-30 23:01:24 +08:00
Dreamacro
9dda932494 Fix: reject should support udp and return dial error 2019-12-30 10:51:35 +08:00
Dreamacro
6ce7b6ef83 Chore: update TUN release 2019-12-28 22:42:30 +08:00
Comzyh
93ea037230 Improve: UDP relay refactor (#441)
Co-authored-by: Dreamacro <Dreamacro@vip.qq.com>
2019-12-28 18:44:01 +08:00
Dreamacro
3f592988a9 Fix: fake pool test 2019-12-28 00:19:40 +08:00
Dreamacro
96f490f84a Feature: add fake-ip-filter 2019-12-28 00:10:06 +08:00
Dreamacro
37603735bd Fix: missing health check instance 2019-12-27 20:12:15 +08:00
Dreamacro
af40048841 Feature: make every provider support health check 2019-12-27 20:12:09 +08:00
Dreamacro
3435c67e68 Fix: ParseWithBytes should recive buffer and parse buffer 2019-12-27 20:12:01 +08:00
Siji
ecb9e4f57d Chore: distinguish udp request in log (#449) 2019-12-27 20:11:51 +08:00
Dreamacro
dd61e8d19d Chore: aggregate logger 2019-12-20 17:22:24 +08:00
Dreamacro
eae06a4a7d Fix: valid proxy group and remove unused code 2019-12-14 18:13:33 +08:00
Dreamacro
0822b526d5 Improve: provider api 2019-12-13 00:29:24 +08:00
Dreamacro
95e9ae2d8d Feature: add basic api for proxy provider 2019-12-11 17:31:15 +08:00
Dreamacro
29cf3ca0ef Fix: should initial compatible provider 2019-12-10 17:27:07 +08:00
Dreamacro
36716ca695 Fix: singledo panic 2019-12-10 16:26:15 +08:00
Dreamacro
2334bafe68 Change: proxy gruop strategy improvement 2019-12-10 15:07:01 +08:00
Dreamacro
bd4302e096 Chore: update dependencies 2019-12-08 13:05:05 +08:00
Dreamacro
d8a1d88ded Chore: update README.md 2019-12-08 12:34:05 +08:00
Dreamacro
c427bc89ef Feature: add experimental provider 2019-12-08 12:17:24 +08:00
Dreamacro
4d7096f451 Fix: HTTP inbound proxy can't close correctly 2019-12-07 23:37:42 +08:00
Dreamacro
4525707048 Chore: remove unused http outbound proxy code 2019-12-05 18:22:07 +08:00
Dreamacro
b8267a69f6 Chore: throw more detail dial error 2019-12-05 17:51:21 +08:00
Dreamacro
ad53b42a68 Fix: vmess websocket udp crash 2019-12-05 14:12:29 +08:00
Dreamacro
93e0dbdc78 Feature: lru cache add evict callback 2019-12-05 00:17:24 +08:00
Dreamacro
3e4bc9f85c Feature: update config API support raw yaml payload 2019-12-01 13:22:47 +08:00
Dreamacro
8e10e67b89 Fix: throw correct error in read config 2019-11-12 10:09:12 +08:00
Dreamacro
3b0cc8548c Chore: add cache for github actions 2019-11-06 12:05:18 +08:00
Dreamacro
e48ccdd4c8 Fix: unsupported rule should throw error 2019-11-04 23:07:19 +08:00
Fndroid
e103040158 Fix: NoResolveIP should return current value (#390) 2019-11-04 10:42:39 +08:00
Comzyh
1948ea11ef Fix: refactor observable to solve a small-probability crash 2019-10-30 15:43:55 +08:00
Dreamacro
6d375ac37e Fix: new tracker crash when rule is nil 2019-10-28 12:58:39 +08:00
Fndroid
82a8c03953 Feature: add no-resolve for ip rules (#375) 2019-10-28 00:02:23 +08:00
Dreamacro
207371aeae Feature: add experimental connections API 2019-10-27 21:44:07 +08:00
Dreamacro
52cfa94652 Fix: HTTP proxy should copy body 2019-10-26 22:13:15 +08:00
Dreamacro
65f4a35e7f Fix: use difference dialer 2019-10-23 12:35:41 +08:00
Dreamacro
e5284cf647
License: use GPL 3.0 2019-10-18 11:12:35 +08:00
Zephyr
0a3595414e Feature: can set specify config file path in cli (#360) 2019-10-14 18:11:22 +08:00
Kirill Motkov
f4326daaa4 Chore: code style improvements (#361) 2019-10-14 17:13:23 +08:00
Dreamacro
710cd5aed2 Migration: use actions upload release 2019-10-14 10:40:00 +08:00
Dreamacro
521a190b0f Fix: hot recreate socks should ignore when receive same address 2019-10-13 23:51:26 +08:00
comwrg
e22ff74e79 Optimization: use context in fallback speed test (#357) 2019-10-13 18:11:02 +08:00
comwrg
2c82a2bfc8 Optimization: use context in urltest speed test (#356) 2019-10-13 12:11:26 +08:00
oasiscifr
461e0a6873 Fix: UDP socks recreate behavior (#355) 2019-10-13 11:19:46 +08:00
Dreamacro
d1fb442bd5 Chore: update dependencies 2019-10-13 00:22:39 +08:00
Dreamacro
7c4a359a2b Fix: dial tcp with context to avoid margin of error 2019-10-12 23:55:39 +08:00
comwrg
0cdc40beb3 Fix: urltest get fastest node ehavior (#326) 2019-10-12 23:29:00 +08:00
Jason Lyu
4cd8b6f24f Fix: some UDP issues (#265) 2019-10-11 20:11:18 +08:00
Birkhoff Lee
0f63682bdf Chore: update README.md (#353) 2019-10-11 20:10:19 +08:00
Dreamacro
52125a3992 Fix: fakeip missing host 2019-10-11 14:01:16 +08:00
Dreamacro
06c9dfdb80 Feature: experimental support snell 2019-10-09 18:46:23 +08:00
Birkhoff Lee
54386ccda3 Chore: Improve grammar and wording (#337) 2019-10-08 10:59:24 +08:00
Dreamacro
d3c50cf89f Fix: throw error when CONNECT return 5xx 2019-10-05 09:33:40 +08:00
Dreamacro
50d2e082d5 Feature: websocket api support browser 2019-09-30 14:13:29 +08:00
Dreamacro
c38469330d Fix: ip version check 2019-09-27 15:26:07 +08:00
Comzyh
045c3a3ad4 Fix: clearer error and ipv6 string parse (#325) 2019-09-27 10:33:37 +08:00
Dreamacro
904c354ee4 Fix: use correctly last record 2019-09-26 10:08:50 +08:00
Dreamacro
1a8a6d0b5d Feature: v2ray-plugin support disable mux 2019-09-21 23:49:00 +08:00
Dreamacro
e0c8aed5c7 Fix(API): cors middleware hoisting because it doesn't work with r.Group 2019-09-21 21:28:02 +08:00
Dreamacro
8f60d61ff9 Fix(fake-ip): return failed when type is AAAA 2019-09-21 10:30:43 +08:00
comwrg
5e6ab99403 Fix: dial should return when dns failed (#311) 2019-09-20 16:04:06 +08:00
Comzyh
8adcc4d83b Fix: TCP dial error should not return early (#307) 2019-09-17 20:11:49 +08:00
宋辰文
b76737bdbb Feature: add fallback filters (#105) 2019-09-15 13:36:45 +08:00
Dreamacro
09f435d928 Chore: update README.md 2019-09-14 21:45:11 +08:00
Dreamacro
3dd9ea52d8 Fix(domain-trie): crash when insert 2019-09-14 21:42:40 +08:00
Dreamacro
09917a2a95 Fix: tcp dual stack dial 2019-09-14 20:01:12 +08:00
Dreamacro
96a4abf46c Feature: move hosts to the top 2019-09-14 20:01:08 +08:00
Dreamacro
16e3090ee8 Feature: add version api 2019-09-13 17:44:30 +08:00
Comzyh
b3e10c05e6 Fix: parse error in proxyGroupsDagSort (#298) 2019-09-13 15:04:51 +08:00
Soar Qin
112b3e5a6c Fix: don't close connection on status 100 Continue and header Proxy-Connection: Keep-Alive (#294) 2019-09-12 10:22:08 +08:00
Dreamacro
60fdd82e2b Fix(API): use right status code 2019-09-08 22:33:52 +08:00
Soar Qin
9815010131 Fix: HTTP status code 100 Continue support" (#288)
* Fix: HTTP Status Code `100 Continue` support

* Style: code style adjustment
2019-09-08 12:21:28 +09:00
comwrg
9875f8ea6e Fix: typo (#287) 2019-09-07 17:23:43 +09:00
Dreamacro
9e0bd62790 Migration: go 1.13 2019-09-04 23:26:20 +09:00
Comzyh
0d51877fcd Fix: should keep the original order of proxy groups (#284) 2019-08-28 23:44:32 +08:00
comwrg
e34090c39a Improve: url-test retry dial when failed (#283) 2019-08-28 22:28:01 +08:00
comwrg
5cc66e51db Chore: remove unused code (#282) 2019-08-27 16:23:44 +08:00
comwrg
71f0a4e35e Fix: typo (#281) 2019-08-26 12:26:14 +08:00
Dreamacro
48a2013d9c Fix: socks address stringify buffer overflow 2019-08-16 21:38:27 +08:00
Dreamacro
6f3a654d6c
Chore: ship github action 2019-08-15 11:40:40 +08:00
X. Jason Lyu
0f7f0a9b1a Optimization: socks UDP & fix typo (#261) 2019-08-12 14:01:32 +08:00
Comzyh
d59e98dc83 Feature: allow arbitrary order in proxy group (#89) 2019-08-12 10:11:44 +08:00
Dreamacro
b137a50d85 Fix: crash in handleConn 2019-08-10 20:14:24 +08:00
Fndroid
f75cd04181 Change: speedtest with HEAD instead of GET (#259) 2019-08-09 15:39:13 +08:00
Yunhao Zhang
b926f4cf09 Feature: trace adapters when dialing (#170) 2019-08-09 01:28:37 +08:00
Siji
5829c3d5be Feature: support customizing bind-address when allow-lan is true (#255) 2019-08-08 13:45:07 +08:00
Siji
288afd1308 Fix: don't read yml if not exist (#253) 2019-08-07 14:21:39 +08:00
beyondkmp
528fbd10e4 Fix(dns): use closure client (#251) 2019-08-02 09:22:09 +08:00
Dreamacro
85128a634d Fix(vmess): set current server name in tls 2019-07-31 11:13:49 +08:00
X. Jason Lyu
f6acbaac7b Fix(vmess): typo (#248) 2019-07-29 12:25:29 +08:00
comwrg
b75da2c6d8 Fix: typo (#246) 2019-07-29 10:12:10 +08:00
Dreamacro
271ed2b9c1 Improve(fakeip): use lru cache to avoid outdate 2019-07-26 19:09:13 +08:00
Leo Yao
1702e7ddb4 Chore(build): add mipsle-softfloat (#240) 2019-07-26 18:45:50 +08:00
X. Jason Lyu
1fd8f690fe Fix(socks5): fully udp associate support (#233) 2019-07-25 17:47:39 +08:00
Siji
183e776970 Chore: use lower case cipher format (#238) 2019-07-25 17:06:26 +08:00
Dreamacro
f00dfdd34d Fix(picker): add WithTimeout for some situation 2019-07-18 00:12:01 +08:00
Dreamacro
0670275533 Fix(url-test): incorrect result 2019-07-17 22:24:26 +08:00
Dreamacro
9e77c650d9 Fix(domain-trie): domain could without dot 2019-07-16 00:57:08 +08:00
Dreamacro
3497fdaf45 Fix(domain-trie): Incorrect result 2019-07-15 18:00:51 +08:00
Dreamacro
6077e825c5 Fix(dns): miss response 2019-07-15 17:44:55 +08:00
Dreamacro
0dd2a6dee5 Fix(dns): set handler when resolver not nil 2019-07-15 10:18:42 +08:00
Dreamacro
c1b5e4f561 Fix(dns): Incorrect variable name 2019-07-14 23:16:52 +08:00
Dreamacro
1a21c8ebfd Feature(dns): support custom hosts 2019-07-14 19:29:58 +08:00
Dreamacro
f867f02546 Feature(API): logs and traffic support websocket 2019-07-12 15:44:12 +08:00
Dreamacro
7c6c147a18 Optimization: refactor picker 2019-07-02 19:18:03 +08:00
Dreamacro
0eff8516c0 Chore: improve Dockerfile 2019-06-30 15:10:56 +08:00
Dreamacro
34338e7107 Chore: update dependencies & fix typo 2019-06-29 16:48:48 +08:00
Dreamacro
57fdd223f1 Feature: custom dns ipv4/ipv6 dual stack 2019-06-29 00:58:59 +08:00
Dreamacro
bc3fc0c840 Feature: support DoH 2019-06-28 12:29:08 +08:00
Dreamacro
662038e40e Fix: log correctly path 2019-06-27 22:56:24 +08:00
Dreamacro
53528f8275 Fix: crash when authenticator is nil 2019-06-27 20:45:12 +08:00
bobo liu
1c792b46c9 Feature: local socks5/http(s) auth (#216) 2019-06-27 17:04:25 +08:00
Dreamacro
2417cfda12 Chore: set log output to stdout 2019-06-26 20:30:57 +08:00
Windendless
aa3516ca24 Chore: use 'dns' for ALPN in tcp-tls nameserver (#209) 2019-06-20 15:50:01 +08:00
beyondkmp
bcf5b21208 Fix: check target is valid in rules (#210) 2019-06-20 11:03:50 +08:00
Dreamacro
ba5eefb6dd Chore: clean up Dockfile 2019-06-19 22:12:25 +08:00
Dreamacro
407de7388c Standardized: use recommend extension & forward compatibility before 1.0 2019-06-18 20:55:26 +08:00
Dreamacro
6adafde9a0 Fix: strict ss obfs check 2019-06-18 20:37:53 +08:00
Jonathan Gao
cba548114f Fix: use original sequence for url-test group (#201) 2019-06-13 20:18:07 +08:00
Dreamacro
016e7bd0b4 Style: fix go vet warning 2019-05-26 13:55:13 +08:00
Dreamacro
ad13ad8dba Fix: add mutex for fake ip pool 2019-05-23 23:27:29 +08:00
Fndroid
89168e6c96 Fix: DNS server not recreate correctly (#186) 2019-05-18 17:52:42 +08:00
Kr328
a4b8e286db Fix: incorrect fake ip dns ttl (#187) 2019-05-18 17:44:12 +08:00
Dreamacro
e837470a6a Fix: udp crash in tunnel 2019-05-16 18:40:20 +08:00
recall704
b589754485 Chore: fix typo (#182) 2019-05-16 14:19:37 +08:00
ezksd
0eccbb023c Feature: make the selector proxies order as same as the order in the config file (#180)
* make the proxies order the same as the order in config file

* formatting & rename variable
2019-05-15 14:40:14 +08:00
Dreamacro
71a08ad8e2 Chore: clean up code 2019-05-14 21:35:34 +08:00
Dreamacro
0d4a999707 Chore: adjust fake-ip ttl 2019-05-12 10:48:07 +08:00
Dreamacro
243d8a2844 Chore: update README.md 2019-05-09 21:05:47 +08:00
Dreamacro
225c530d13 Feature: add DST-PORT and SRC-PORT 2019-05-09 21:00:29 +08:00
Dreamacro
cff4841f3e Chore: fix socks reader overflow & update dependencies 2019-05-06 21:00:29 +08:00
Dreamacro
f352f4479e Feature: support fakeip 2019-05-03 00:05:14 +08:00
Dreamacro
762f227512 Feature: support vmess udp 2019-04-25 16:32:15 +08:00
Dreamacro
936ea3aa55 Feature: support outbound socks5 udp 2019-04-25 13:48:47 +08:00
Dreamacro
cec2206774 Feature: add experimental config for resolving ip fail behavior 2019-04-24 12:02:52 +08:00
Dreamacro
90e3dccacd Fix: add missing error check 2019-04-24 10:29:29 +08:00
Dreamacro
c92cda6980 Feature: socks5 udp associate 2019-04-23 23:30:13 +08:00
Jang Rush
49f8902961 Fix: typo in initial config file (#166) 2019-04-22 09:57:08 +08:00
Birkhoff Lee
7770e18430 Chore: add GitBook link to README.md (#155) 2019-04-15 19:07:18 +08:00
Dreamacro
593a63c228 Fix: make releases script 2019-03-30 15:34:24 +08:00
Dreamacro
744728cb84 Chore: update README.md 2019-03-30 14:20:04 +08:00
Dreamacro
2036f8cb7a Fix: IP-CIDR invalid payload crash 2019-03-30 14:11:59 +08:00
Comzyh
531f487629 Fix: incorrect mutex in speedTest (#153) 2019-03-29 10:27:26 +08:00
Dreamacro
18f885a92a Feature: add interval url test for load-balance 2019-03-28 19:00:41 +08:00
Dreamacro
d3b280a7e5 Fix: reuse Current.HomeDir until go 1.13 release 2019-03-28 18:20:19 +08:00
beyondkmp
d1f6886558 Style: use atomic CompareAndSwap (#151) 2019-03-26 23:48:03 +08:00
Dreamacro
791d72e05b Fix: crash when key value is nil 2019-03-25 20:42:20 +08:00
Dreamacro
14600a8170 Fix: dns hot reload no effect 2019-03-23 19:41:41 +08:00
beyondkmp
bb267e4a1f Feature: add version command (#148) 2019-03-23 19:24:26 +08:00
Dreamacro
f99da37168 Fix: fallback & url-test lose efficacy 2019-03-23 16:29:27 +08:00
Dreamacro
7a9d986ff3 Feature: add delay history and improve url-test behavior 2019-03-17 14:52:39 +08:00
Comzyh
63446da5fa Fix: expand UDPSize to avoid resolving error (#139) 2019-03-17 14:08:15 +08:00
Dreamacro
acf55a7f64 Improve: Dial would reset proxy alive status 2019-03-16 00:43:16 +08:00
Rico
8c608f5d7a Feature: add custom headers support in v2ray-plugin (#137) 2019-03-15 09:43:46 +08:00
Dreamacro
7f0c7d7802 Fix: should not return extra ip in msgToIP 2019-03-03 17:23:59 +08:00
Dreamacro
7683271fe6 Style: rename Generator with Dial 2019-03-03 11:59:07 +08:00
Dreamacro
23bb01a4df Fix: http request keepAlive with right http header 2019-03-03 11:51:15 +08:00
Comzyh
0011c7acfe Improve: support tcp dns server & return an error when parsing nameserver (#127) 2019-03-01 00:52:30 +08:00
Dreamacro
d75f9ff783 Migration: go 1.12 2019-02-27 01:02:43 +08:00
Dreamacro
815e80f720 Fix: dns use Extra records 2019-02-24 01:26:51 +08:00
Dreamacro
ca5399a16e Fix: dns cache behavior 2019-02-23 20:31:59 +08:00
Dreamacro
04927229ff Fix: disconnect normal proxy request 2019-02-21 16:16:49 +08:00
Dreamacro
c0bd82d62b Chore: rename final 2019-02-18 21:53:57 +08:00
Dreamacro
5c8bb24121 Fix: crash when directly request proxy server 2019-02-18 20:14:18 +08:00
Dreamacro
575720e0cc Fix: windows 386 build 2019-02-15 23:43:28 +08:00
Dreamacro
e7997a035b Chore: update README.md 2019-02-15 22:01:11 +08:00
beyondkmp
287ad5bc53 Fix: vmess handshake block (#117) 2019-02-15 21:55:15 +08:00
Dreamacro
c295c5e412 Feature: add load-balance group 2019-02-15 14:25:20 +08:00
beyondkmp
8636a4f589 Fix: return 502 in http outbound (#116) 2019-02-14 11:37:47 +08:00
Dreamacro
7a0717830c Fix: api invalid returning 2019-02-13 23:45:43 +08:00
Dreamacro
5920b05752 Fix: crash when ip is nil 2019-02-12 12:29:33 +08:00
Dreamacro
26a87f9d34 Fix: redir-host mode crash 2019-02-11 17:20:42 +08:00
Dreamacro
8da19e81a4 Update: README.md 2019-02-11 15:55:17 +08:00
Dreamacro
1339487ce4 Fix: tun2socks not lookup IP 2019-02-11 15:44:42 +08:00
Dreamacro
2383cca2ce Feature: add v2ray-plugin 2019-02-11 15:25:39 +08:00
Dreamacro
53b5ef199f Fix: parse proxies shadow variable 2019-02-04 09:39:17 +08:00
Dreamacro
754df5ba9b Chore: update dependencies 2019-02-02 21:53:30 +08:00
Dreamacro
1016355ef6 Chore: log dns server address when success 2019-02-02 21:37:36 +08:00
beyondkmp
b594cbc68d Fix: parse ip string when use socks proxy (#100) 2019-02-02 21:11:27 +08:00
宋辰文
42d33fe629 Feature: SOURCE-IP-CIDR rule type (#96) 2019-02-02 21:03:13 +08:00
Dreamacro
bfe51e46b0 Improve: lazy resolve ip 2019-02-02 20:47:38 +08:00
Dreamacro
e30a628702 Fix: shadow variable 2019-01-30 20:22:52 +08:00
beyondkmp
5581698908 Chore: improve programming style (#109) 2019-01-29 23:46:18 +08:00
Dreamacro
36b5d1f18f Fix: DNS server returns the correct TTL 2019-01-25 15:38:14 +08:00
beyondkmp
bd6c6a9ad1 Chore: print origin rule when format error (#92) 2019-01-14 10:35:11 +08:00
beyondkmp
83fac44010 Fix: nghttpx return 400 error (#84) 2019-01-07 10:47:25 +08:00
beyondkmp
15a77fa71b Fix: print log when start dns server failed (#87) 2019-01-06 14:31:42 +08:00
Comzyh
7768c5b933 Chore: add more platform release (#83) 2019-01-03 10:49:09 +08:00
Noah Shang
4e91118a05 Feature: add freebsd release (#80)
add freebsd support
2018-12-31 20:57:21 +08:00
Dreamacro
7b5e1f759c Fix: authentication with stream api 2018-12-29 14:11:54 +08:00
Dreamacro
3f6c707aa9 Fix: patch config field 2018-12-23 20:25:49 +08:00
Dreamacro
532ec88964 Chore: make a consistent code style 2018-12-23 00:42:08 +08:00
Dreamacro
cb118d4371 Chore: improve outbound architecture 2018-12-22 23:56:42 +08:00
Dreamacro
a7cfc81885 Fix: ignore some general configuration 2018-12-21 22:51:37 +08:00
宋辰文
551ab68c1e Fix: allow access to external-ui without authentication (#75) 2018-12-21 17:48:29 +08:00
Dreamacro
ef6260282f Fix: parse external-ui 2018-12-21 10:55:21 +08:00
Dreamacro
49635eab6c Chore: update external-ui explanation 2018-12-20 22:34:38 +08:00
Dreamacro
a46041b81c Fix: force param make no sense 2018-12-20 22:23:31 +08:00
Dreamacro
a6bbc67afb Feature: add custom ui support in API 2018-12-20 01:29:13 +08:00
yuri@FreeBSD
afc4644dd1 Feature: FreeBSD compatibility patch (#63) 2018-12-18 10:37:00 +08:00
Dreamacro
1607d3253f Feature: add websocket headers support in vmess 2018-12-11 00:25:05 +08:00
beyondkmp
34c8655974 Fix: don't keepalive when connection is close (#65)
fixed #60
2018-12-10 11:48:57 +08:00
Dreamacro
5e4b35e03a Chore: standardize API returns 2018-12-10 11:33:37 +08:00
Dreamacro
fa9077969c Fix: dns crash & remove unused debug log 2018-12-10 11:00:52 +08:00
Dreamacro
fcb1a7813a Fix: dns msg to ip 2018-12-06 13:29:43 +08:00
Dreamacro
6f1bc3d65b Fix: add PATCH for CORS 2018-12-06 10:54:45 +08:00
Dreamacro
2b93c9d4c9 Fix: resolve ip crash 2018-12-06 10:51:37 +08:00
Dreamacro
f93d6aa294 Fix: crash when dns not set 2018-12-05 21:52:31 +08:00
Dreamacro
f192d591c7 Chore: bump to 0.10.0 2018-12-05 21:26:04 +08:00
Dreamacro
03c249ecb1
Feature: add custom DNS support (#56) 2018-12-05 21:13:29 +08:00
Dreamacro
da5db36ccf Fix: policy group unexpectedly closed 2018-12-05 18:19:30 +08:00
Dreamacro
ca6e67a384 Feature: add silent info level 2018-12-03 23:41:40 +08:00
beyondkmp
6636db242b Feature: add http/https [connect] proxy (#52) 2018-12-03 23:27:00 +08:00
beyondkmp
f5715c4f42 Fix: chunk size limit in tls obfs (#54)
* Fix: add chunkSize limit in TLSObfs

* Chore: add length var for len(b)
2018-12-01 09:32:02 +08:00
Dreamacro
9cfd26d440 Feat: add switch config file API 2018-11-30 17:42:40 +08:00
Dreamacro
dc24dd4d89 Fix: tls server name missing in vmess 2018-11-28 23:24:57 +08:00
Dreamacro
a64cea5011 Fix: patch config API 2018-11-28 10:38:30 +08:00
beyondkmp
f6743d4d21 Fix: chrome crash when using SwitchyOmega by reject rule (#47)
* Fix: chrome crash when using SwitchyOmega by reject rule
2018-11-25 17:00:11 +08:00
beyondkmp
970643b144 Fix: goroutine leak while closing proxy (#43)
* Fix: goroutine leak while closing proxy

* Chore: improve proxy architecture

* Fix: stack overflow
2018-11-22 11:54:01 +08:00
Dreamacro
05bf4d44ab Change: replace FINAL with MATCH in a progressive way 2018-11-21 18:21:24 +08:00
Dreamacro
c7a349e1fe Improve: auto change payload to lowercase 2018-11-21 13:59:39 +08:00
Dreamacro
01a477bd3d Chore: improve code architecture 2018-11-21 13:47:46 +08:00
Dreamacro
91e35f2f6a Fix: resolve path in windows 2018-11-14 20:58:10 +08:00
beyondkmp
b0e062dc7c Feature: SOCKS5 authentication support (#34)
* Feature: socks5 auth support

* Chore: make code unified

* Fix: auth buffer length
2018-11-09 17:36:30 +08:00
Dreamacro
09cd34ec07 Chore: update README.md 2018-11-08 20:14:57 +08:00
Dreamacro
da391356dd Fix: simple-obfs tls 2018-11-07 16:57:21 +08:00
Dreamacro
502aa61c0e Fix: vmess small probability invalid auth 2018-11-06 17:34:19 +08:00
beyondkmp
cc6d496143 Chore: optimize code structure in vmess websocket (#28)
* Chore: move conn process of ws to websocket.go

* Chore: some routine adjustment
2018-11-04 21:36:20 +08:00
beyondkmp
10e0231bc1 Fix: dial IPv6 host (#29) 2018-11-04 21:12:16 +08:00
changx
fd63707399 Optimization: use client session cache for TLS connection (#26) 2018-11-01 11:54:45 +08:00
beyondkmp
c5757a9b11 Chore: delete redundant print 2018-10-30 10:50:57 +08:00
381 changed files with 32099 additions and 4081 deletions

124
.github/ISSUE_TEMPLATE/bug_report_en.yml vendored Normal file
View File

@ -0,0 +1,124 @@
name: (English) Report a bug of the Clash core
description: Create a bug report to help us improve
labels:
- bug
title: "[Bug] <issue title>"
body:
- type: markdown
attributes:
value: "## Welcome to the official Clash open-source community"
- type: markdown
attributes:
value: |
Thank you for taking the time to report an issue with the Clash core.
Prior to submitting this issue, please read and follow the guidelines below to ensure that your issue can be resolved as quickly as possible. Options marked with an asterisk (*) are required, while others are optional. If the information you provide does not comply with the requirements, the maintainers may not respond and may directly close the issue.
If you can debug and fix the issue yourself, we welcome you to submit a pull request to merge your changes upstream.
- type: checkboxes
id: ensure
attributes:
label: Prerequisites
description: "If any of the following options do not apply, please do not submit this issue as we will close it"
options:
- label: "I understand that this is the official open-source version of the Clash core, **only providing support for the open-source version or Premium version**"
required: true
- label: "I am submitting an issue with the Clash core, not Clash.Meta / OpenClash / ClashX / Clash For Windows or any other derivative version"
required: true
- label: "I am using the latest version of the Clash or Clash Premium core **in this repository**"
required: true
- label: "I have searched at the [Issue Tracker](……/) **and have not found any related issues**"
required: true
- label: "I have read the [official Wiki](https://dreamacro.github.io/clash/) **and was unable to solve the issue**"
required: true
- label: "(required for Premium core) I've tried the `dev` branch and the issue still exists"
required: false
- type: markdown
attributes:
value: "## Environment"
- type: markdown
attributes:
value: |
Please provide the following information to help us locate the issue.
The issue might be closed if there's not enough information provided.
- type: input
attributes:
label: Version
description: "Run `clash -v` or look at the bottom-left corner of the Clash Dashboard to find out"
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating System
description: "Select all operating systems that apply to this issue"
multiple: true
options:
- Linux
- Windows
- macOS (darwin)
- Android
- OpenBSD / FreeBSD
- type: dropdown
id: arch
attributes:
label: Architecture
description: "Select all architectures that apply to this issue"
multiple: true
options:
- amd64
- amd64-v3
- arm64
- "386"
- armv5
- armv6
- armv7
- mips-softfloat
- mips-hardfloat
- mipsle-softfloat
- mipsle-hardfloat
- mips64
- mips64le
- riscv64
- type: markdown
attributes:
value: "## Clash related information"
- type: markdown
attributes:
value: |
Please provide relevant information about your Clash instance here. If you
do not provide enough information, the issue may be closed.
- type: textarea
attributes:
render: YAML
label: Configuration File
placeholder: "Ensure that there is no sensitive information (such as server addresses, passwords, or ports) in the configuration file, and provide the minimum reproducible configuration. Do not post configurations with thousands of lines."
validations:
required: true
- type: textarea
attributes:
render: Text
label: Log
placeholder: "Please attach the corresponding core outout (setting `log-level: debug` in the configuration provides debugging information)."
- type: textarea
attributes:
label: Description
placeholder: "Please describe your issue in detail here to help us understand (supports Markdown syntax)."
validations:
required: true
- type: textarea
attributes:
label: Reproduction Steps
placeholder: "Please provide the specific steps to reproduce the issue here (supports Markdown syntax)."

121
.github/ISSUE_TEMPLATE/bug_report_zh.yml vendored Normal file
View File

@ -0,0 +1,121 @@
name: (中文)提交 Clash 核心的问题
description: 如果 Clash 核心运作不符合预期,在这里提交问题
labels:
- bug
title: "[Bug] <问题标题>"
body:
- type: markdown
attributes:
value: "## 欢迎来到 Clash 官方开源社区!"
- type: markdown
attributes:
value: |
感谢你拨冗提交 Clash 内核的问题。在提交之前,请仔细阅读并遵守以下指引,以确保你的问题能够被尽快解决。
带有星号(*)的选项为必填,其他可选填。**如果你填写的资料不符合规范,维护者可能不予回复,并直接关闭这个 issue。**
如果你可以自行 debug 并且修正,我们随时欢迎你提交 Pull Request将你的修改合并到上游。
- type: checkboxes
id: ensure
attributes:
label: 先决条件
description: "若以下任意选项不适用,请勿提交这个 issue因为我们会把它关闭"
options:
- label: "我了解这里是官方开源版 Clash 核心仓库,**只提供开源版或者 Premium 内核的支持**"
required: true
- label: "我要提交 Clash 核心的问题,并非 Clash.Meta / OpenClash / ClashX / Clash For Windows 或其他任何衍生版本的问题"
required: true
- label: "我使用的是**本仓库**最新版本的 Clash 或 Clash Premium 内核"
required: true
- label: "我已经在 [Issue Tracker](……/) 中找过我要提出的 bug**并且没有找到相关问题**"
required: true
- label: "我已经仔细阅读 [官方 Wiki](https://dreamacro.github.io/clash/) 并无法自行解决问题"
required: true
- label: "(非 Premium 内核必填)我已经使用 dev 分支版本测试过,问题依旧存在"
required: false
- type: markdown
attributes:
value: "## 系统环境"
- type: markdown
attributes:
value: |
请附上这个问题适用的环境,以帮助我们迅速定位问题并解决。若你提供的信息不足,我们将关闭
这个 issue 并要求你提供更多信息。
- type: input
attributes:
label: 版本
description: "运行 `clash -v` 或者查看 Clash Dashboard 的左下角来找到你现在使用的版本"
validations:
required: true
- type: dropdown
id: os
attributes:
label: 适用的作业系统
description: "勾选所有适用于这个 issue 的系统"
multiple: true
options:
- Linux
- Windows
- macOS (darwin)
- Android
- OpenBSD / FreeBSD
- type: dropdown
id: arch
attributes:
label: 适用的硬件架构
description: "勾选所有适用于这个 issue 的架构"
multiple: true
options:
- amd64
- amd64-v3
- arm64
- "386"
- armv5
- armv6
- armv7
- mips-softfloat
- mips-hardfloat
- mipsle-softfloat
- mipsle-hardfloat
- mips64
- mips64le
- riscv64
- type: markdown
attributes:
value: "## Clash 相关信息"
- type: markdown
attributes:
value: |
请附上与这个问题直接相关的相应信息,以帮助我们迅速定位问题并解决。
若你提供的信息不足,我们将关闭这个 issue 并要求你提供更多信息。
- type: textarea
attributes:
render: YAML
label: "配置文件"
placeholder: "确保配置文件中没有敏感信息(如:服务器地址、密码、端口),并且提供最小可复现配置,严禁贴上上千行的配置"
validations:
required: true
- type: textarea
attributes:
render: Text
label: 日志输出
placeholder: "在这里附上问题对应的内核日志(在配置中设置 `log-level: debug` 可获得调试信息)"
- type: textarea
attributes:
label: 问题描述
placeholder: "在这里详细叙述你的问题,帮助我们理解(支持 Markdown 语法)"
validations:
required: true
- type: textarea
attributes:
label: 复现步骤
placeholder: "在这里提供问题的具体重现步骤(支持 Markdown 语法)"

9
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,9 @@
blank_issues_enabled: false
contact_links:
- name: (中文)阅读 Wiki
url: https://dreamacro.github.io/clash/zh_CN/
about: 如果你是新手,或者想要了解 Clash 的更多信息,请阅读我们撰写的官方 Wiki
- name: (English) Read our Wiki page
url: https://dreamacro.github.io/clash/
about: If you are new to Clash, or want to know more about Clash, please read our Wiki page

View File

@ -0,0 +1,43 @@
name: (English) Feature request
description: Suggest an idea for this project
labels:
- enhancement
title: "[Feature] <title>"
body:
- type: markdown
attributes:
value: "## Welcome to the official Clash open-source community"
- type: markdown
attributes:
value: |
Thank you for taking the time to make a suggestion to the Clash core.
Prior to submitting this issue, please read and follow the guidelines below to ensure that your issue can be resolved as quickly as possible. Options marked with an asterisk (*) are required, while others are optional. If the information you provide does not comply with the requirements, the maintainers may not respond and may directly close the issue.
If you can implement your idea by yourself, we welcome you to submit a pull request to merge your changes upstream.
- type: checkboxes
id: ensure
attributes:
label: Prerequisites
description: "If any of the following options do not apply, please do not submit this issue as we will close it"
options:
- label: "I understand that this is the official open-source version of the Clash core, **only providing support for the open-source version or Premium version**"
required: true
- label: "I have looked for my idea in [the issue tracker](https://github.com/Dreamacro/clash/issues?q=is%3Aissue+label%3Aenhancement), **and found none of which being related**"
required: true
- label: "I have read the [official Wiki](https://dreamacro.github.io/clash/)"
required: true
- type: textarea
attributes:
label: Description
placeholder: "Please explain your suggestions in detail and in a clear manner. For instance, how does this issue impact you? What specific functionality are you hoping to achieve? Also, let us know what Clash Core is currently doing in terms of your suggestion, and what you would like it to do instead."
validations:
required: true
- type: textarea
attributes:
label: Possible Solution
placeholder: "Do you have any ideas on the implementation details?"

View File

@ -0,0 +1,41 @@
name: (中文)建议一个新功能
description: 在这里提供一个的想法或建议
labels:
- enhancement
title: "[Feature] <标题>"
body:
- type: markdown
attributes:
value: "## 欢迎来到 Clash 官方开源社区!"
- type: markdown
attributes:
value: |
感谢你拨冗为 Clash 内核提供建议。在提交之前,请仔细阅读并遵守以下指引,以确保你的建议能够被顺利采纳。
带有星号(*)的选项为必填,其他可选填。**如果你填写的资料不符合规范,维护者可能不予回复,并直接关闭这个 issue。**
如果你可以自行添加这个功能,我们随时欢迎你提交 Pull Request并将你的修改合并到上游。
- type: checkboxes
id: ensure
attributes:
label: 先决条件
description: "若以下任意选项不适用,请勿提交这个 issue因为我们会把它关闭"
options:
- label: "我了解这里是 Clash 官方仓库,并非 Clash.Meta / OpenClash / ClashX / Clash For Windows 或其他任何衍生版本"
required: true
- label: "我已经在[这里](https://github.com/Dreamacro/clash/issues?q=is%3Aissue+label%3Aenhancement)找过我要提出的建议,**并且没有找到相关问题**"
required: true
- label: "我已经仔细阅读 [官方 Wiki](https://dreamacro.github.io/clash/) "
required: true
- type: textarea
attributes:
label: 描述
placeholder: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash Core 的行为是什么?
validations:
required: true
- type: textarea
attributes:
label: 可能的解决方案
placeholder: 此项非必须,但是如果你有想法的话欢迎提出。

30
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,30 @@
name: CodeQL
on:
push:
branches: [master, dev]
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language: ['go']
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@v2
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

42
.github/workflows/deploy-docs.yml vendored Normal file
View File

@ -0,0 +1,42 @@
name: Deploy
on:
workflow_dispatch: {}
push:
branches:
- master
jobs:
deploy:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20]
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: pnpm/action-setup@v2
with:
version: latest
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- name: Install dependencies
working-directory: docs
run: pnpm install --frozen-lockfile=false
- name: Build
working-directory: docs
run: pnpm run docs:build
- uses: actions/configure-pages@v2
- uses: actions/upload-pages-artifact@v1
with:
path: docs/.vitepress/dist
- name: Deploy
id: deployment
uses: actions/deploy-pages@v2

80
.github/workflows/docker.yml vendored Normal file
View File

@ -0,0 +1,80 @@
name: Publish Docker Image
on:
push:
branches:
- dev
tags:
- '*'
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
with:
platforms: all
- name: Set up docker buildx
id: buildx
uses: docker/setup-buildx-action@v2
with:
version: latest
- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to Github Package
uses: docker/login-action@v2
with:
registry: ghcr.io
username: Dreamacro
password: ${{ secrets.PACKAGE_TOKEN }}
- name: Build dev branch and push
if: github.ref == 'refs/heads/dev'
uses: docker/build-push-action@v4
with:
context: .
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
push: true
tags: 'dreamacro/clash:dev,ghcr.io/dreamacro/clash:dev'
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Get all docker tags
if: startsWith(github.ref, 'refs/tags/')
uses: actions/github-script@v6
id: tags
with:
script: |
const ref = context.payload.ref.replace(/\/?refs\/tags\//, '')
const tags = [
'dreamacro/clash:latest',
`dreamacro/clash:${ref}`,
'ghcr.io/dreamacro/clash:latest',
`ghcr.io/dreamacro/clash:${ref}`
]
return tags.join(',')
result-encoding: string
- name: Build release and push
if: startsWith(github.ref, 'refs/tags/')
uses: docker/build-push-action@v4
with:
context: .
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
push: true
tags: ${{steps.tags.outputs.result}}
cache-from: type=gha
cache-to: type=gha,mode=max

18
.github/workflows/linter.yml vendored Normal file
View File

@ -0,0 +1,18 @@
name: Linter
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Go
uses: actions/setup-go@v4
with:
check-latest: true
go-version: '1.20'
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
version: latest

42
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,42 @@
name: Release
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Setup Go
uses: actions/setup-go@v4
with:
check-latest: true
go-version: '1.20'
- name: Check out code into the Go module directory
uses: actions/checkout@v3
- name: Cache go module
uses: actions/cache@v3
with:
path: |
~/go/pkg/mod
~/.cache/go-build
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: |
${{ runner.os }}-go-
- name: Get dependencies, run test
run: |
go test ./...
- name: Build
if: startsWith(github.ref, 'refs/tags/')
env:
NAME: clash
BINDIR: bin
run: make -j $(go run ./test/main.go) releases
- name: Upload Release
uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/')
with:
files: bin/*
draft: true

18
.github/workflows/stale.yml vendored Normal file
View File

@ -0,0 +1,18 @@
name: Mark stale issues and pull requests
on:
schedule:
- cron: "30 1 * * *"
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v7
with:
stale-issue-message: 'This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 5 days'
days-before-stale: 60
days-before-close: 5

23
.gitignore vendored
View File

@ -4,6 +4,7 @@
*.dll *.dll
*.so *.so
*.dylib *.dylib
bin/*
# Test binary, build with `go test -c` # Test binary, build with `go test -c`
*.test *.test
@ -11,5 +12,25 @@
# Output of the go coverage tool, specifically when used with LiteIDE # Output of the go coverage tool, specifically when used with LiteIDE
*.out *.out
# dep # go mod vendor
vendor vendor
# GoLand
.idea/*
# macOS file
.DS_Store
# test suite
test/config/cache*
# docs site generator
node_modules
package-lock.json
pnpm-lock.yaml
# docs site cache
docs/.vitepress/cache
# docs site build files
docs/.vitepress/dist

23
.golangci.yaml Normal file
View File

@ -0,0 +1,23 @@
linters:
disable-all: true
enable:
- gci
- gofumpt
- gosimple
- govet
- ineffassign
- misspell
- staticcheck
- unconvert
- unused
- usestdlibvars
linters-settings:
gci:
custom-order: true
sections:
- standard
- prefix(github.com/Dreamacro/clash)
- default
staticcheck:
go: '1.20'

View File

@ -1,26 +0,0 @@
language: go
sudo: false
go:
- "1.11"
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

View File

@ -1,23 +1,22 @@
FROM golang:latest as builder FROM --platform=${BUILDPLATFORM} golang:alpine as builder
RUN wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz -O /tmp/GeoLite2-Country.tar.gz && \ RUN apk add --no-cache make git ca-certificates tzdata && \
tar zxvf /tmp/GeoLite2-Country.tar.gz -C /tmp && \ wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb
mv /tmp/GeoLite2-Country_*/GeoLite2-Country.mmdb /Country.mmdb WORKDIR /workdir
COPY --from=tonistiigi/xx:golang / /
ARG TARGETOS TARGETARCH TARGETVARIANT
WORKDIR /clash-src RUN --mount=target=. \
--mount=type=cache,target=/root/.cache/go-build \
COPY . /clash-src --mount=type=cache,target=/go/pkg/mod \
make BINDIR= ${TARGETOS}-${TARGETARCH}${TARGETVARIANT} && \
RUN go mod download && \ mv /clash* /clash
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '-w -s' -o /clash
FROM alpine:latest FROM alpine:latest
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
RUN apk add --no-cache ca-certificates COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /Country.mmdb /root/.config/clash/ COPY --from=builder /Country.mmdb /root/.config/clash/
COPY --from=builder /clash / COPY --from=builder /clash /
EXPOSE 7890 7891
ENTRYPOINT ["/clash"] ENTRYPOINT ["/clash"]

687
LICENSE
View File

@ -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>.

147
Makefile
View File

@ -1,23 +1,148 @@
NAME=clash NAME=clash
BINDIR=bin BINDIR=bin
GOBUILD=CGO_ENABLED=0 go build -ldflags '-w -s' VERSION=$(shell git describe --tags || echo "unknown version")
BUILDTIME=$(shell date -u)
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
-w -s -buildid='
all: linux macos win64 PLATFORM_LIST = \
darwin-amd64 \
darwin-amd64-v3 \
darwin-arm64 \
linux-386 \
linux-amd64 \
linux-amd64-v3 \
linux-armv5 \
linux-armv6 \
linux-armv7 \
linux-arm64 \
linux-mips-softfloat \
linux-mips-hardfloat \
linux-mipsle-softfloat \
linux-mipsle-hardfloat \
linux-mips64 \
linux-mips64le \
linux-riscv64 \
linux-loong64 \
freebsd-386 \
freebsd-amd64 \
freebsd-amd64-v3 \
freebsd-arm64
linux: WINDOWS_ARCH_LIST = \
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@ windows-386 \
windows-amd64 \
windows-amd64-v3 \
windows-arm64 \
windows-armv7
macos: all: linux-amd64 darwin-amd64 windows-amd64 # Most used
darwin-amd64:
GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@ GOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
win64: darwin-amd64-v3:
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
darwin-arm64:
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-386:
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-amd64:
GOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-amd64-v3:
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-armv5:
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-armv6:
GOARCH=arm GOOS=linux GOARM=6 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-armv7:
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-arm64:
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-mips-softfloat:
GOARCH=mips GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-mips-hardfloat:
GOARCH=mips GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-mipsle-softfloat:
GOARCH=mipsle GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-mipsle-hardfloat:
GOARCH=mipsle GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-mips64:
GOARCH=mips64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-mips64le:
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-riscv64:
GOARCH=riscv64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
linux-loong64:
GOARCH=loong64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
freebsd-386:
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
freebsd-amd64:
GOARCH=amd64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
freebsd-amd64-v3:
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
freebsd-arm64:
GOARCH=arm64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
windows-386:
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
windows-amd64:
GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe GOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
releases: linux macos win64 windows-amd64-v3:
chmod +x $(BINDIR)/$(NAME)-* GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
gzip $(BINDIR)/$(NAME)-linux
gzip $(BINDIR)/$(NAME)-macos windows-arm64:
zip -m -j $(BINDIR)/$(NAME)-win64.zip $(BINDIR)/$(NAME)-win64.exe GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
windows-armv7:
GOARCH=arm GOOS=windows GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
$(gz_releases): %.gz : %
chmod +x $(BINDIR)/$(NAME)-$(basename $@)
gzip -f -S -$(VERSION).gz $(BINDIR)/$(NAME)-$(basename $@)
$(zip_releases): %.zip : %
zip -m -j $(BINDIR)/$(NAME)-$(basename $@)-$(VERSION).zip $(BINDIR)/$(NAME)-$(basename $@).exe
all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
releases: $(gz_releases) $(zip_releases)
LINT_OS_LIST := darwin windows linux freebsd openbsd
lint: $(foreach os,$(LINT_OS_LIST),$(os)-lint)
%-lint:
GOOS=$* golangci-lint run ./...
lint-fix: $(foreach os,$(LINT_OS_LIST),$(os)-lint-fix)
%-lint-fix:
GOOS=$* golangci-lint run --fix ./...
clean: clean:
rm $(BINDIR)/* rm $(BINDIR)/*

172
README.md
View File

@ -1,171 +1,53 @@
<h1 align="center"> <h1 align="center">
<img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200"> <img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200">
<br> <br>Clash<br>
Clash
<br>
</h1> </h1>
<h4 align="center">A rule based proxy 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/actions/workflow/status/Dreamacro/clash/release.yml?branch=master&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">
</a> </a>
<img src="https://img.shields.io/github/go-mod/go-version/Dreamacro/clash?style=flat-square">
<a href="https://github.com/Dreamacro/clash/releases"> <a href="https://github.com/Dreamacro/clash/releases">
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square"> <img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
</a> </a>
<a href="https://github.com/Dreamacro/clash/releases/tag/premium">
<img src="https://img.shields.io/badge/release-Premium-00b4f0?style=flat-square">
</a>
</p> </p>
## Features ## Features
- HTTP/HTTPS and SOCKS proxy This is a general overview of the features that comes with Clash.
- Surge like configuration
- GeoIP rule support
- Support Vmess/Shadowsocks/Socks5
- Support for Netfilter TCP redirect
## Discussion - Inbound: HTTP, HTTPS, SOCKS5 server, TUN device
- Outbound: Shadowsocks(R), VMess, Trojan, Snell, SOCKS5, HTTP(S), Wireguard
- Rule-based Routing: dynamic scripting, domain, IP addresses, process name and more
- Fake-IP DNS: minimises impact on DNS pollution and improves network performance
- Transparent Proxy: Redirect TCP and TProxy TCP/UDP with automatic route table/rule management
- Proxy Groups: automatic fallback, load balancing or latency testing
- Remote Providers: load remote proxy lists dynamically
- RESTful API: update configuration in-place via a comprehensive API
[Telegram Group](https://t.me/clash_discuss) *Some of the features may only be available in the [Premium core](https://dreamacro.github.io/clash/premium/introduction.html).*
## Install ## Documentation
You can build from source: You can find the latest documentation at [https://dreamacro.github.io/clash/](https://dreamacro.github.io/clash/).
```sh ## Credits
go get -u -v github.com/Dreamacro/clash
```
Pre-built binaries are available: [release](https://github.com/Dreamacro/clash/releases) - [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
Requires Go >= 1.10. - [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
## Daemon
Unfortunately, there is no native elegant way to implement golang's daemon.
So we can use third-party daemon tools like pm2, supervisor, and so on.
In the case of [pm2](https://github.com/Unitech/pm2), we can start the daemon this way:
```sh
pm2 start clash
```
If you have Docker installed, you can run clash directly using `docker-compose`.
[Run clash in docker](https://github.com/Dreamacro/clash/wiki/Run-clash-in-docker)
## Config
**NOTE: after v0.8.0, clash using yaml as configuration file**
The default configuration directory is `$HOME/.config/clash`
The name of the configuration file is `config.yml`
If you want to use another directory, you can use `-d` to control the configuration directory
For example, you can use the current directory as the configuration directory
```sh
clash -d .
```
Below is a simple demo configuration file:
```yml
# port of HTTP
port: 7890
# port of SOCKS5
socks-port: 7891
# redir proxy for Linux and macOS
# redir-port: 7892
allow-lan: false
# Rule / Global/ Direct (default is Rule)
mode: Rule
# set log level to stdout (default is info)
# info / warning / error / debug
log-level: info
# A RESTful API for clash
external-controller: 127.0.0.1:9090
# Secret for RESTful API (Optional)
# secret: ""
Proxy:
# shadowsocks
# The types of cipher are consistent with go-shadowsocks2
# support AEAD_AES_128_GCM AEAD_AES_192_GCM AEAD_AES_256_GCM AEAD_CHACHA20_POLY1305 AES-128-CTR AES-192-CTR AES-256-CTR AES-128-CFB AES-192-CFB AES-256-CFB CHACHA20-IETF XCHACHA20
# In addition to what go-shadowsocks2 supports, it also supports chacha20 rc4-md5 xchacha20-ietf-poly1305
- { name: "ss1", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password" }
- { name: "ss2", type: ss, server: server, port: 443, cipher: AEAD_CHACHA20_POLY1305, password: "password", obfs: tls, obfs-host: bing.com }
# vmess
# cipher support auto/aes-128-gcm/chacha20-poly1305/none
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto }
# with tls
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true }
# with tls and skip-cert-verify
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, tls: true, skip-cert-verify: true }
# with ws
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path }
# with ws + tls
- { name: "vmess", type: vmess, server: server, port: 443, uuid: uuid, alterId: 32, cipher: auto, network: ws, ws-path: /path, tls: true }
# socks5
- { name: "socks", type: socks5, server: server, port: 443 }
# with tls
- { name: "socks", type: socks5, server: server, port: 443, tls: true }
# with tls and skip-cert-verify
- { name: "socks", type: socks5, server: server, port: 443, tls: true, skip-cert-verify: true }
Proxy Group:
# url-test select which proxy will be used by benchmarking speed to a URL.
- { name: "auto", type: url-test, proxies: ["ss1", "ss2", "vmess1"], url: http://www.gstatic.com/generate_204, interval: 300 }
# fallback select an available policy by priority. The availability is tested by accessing an URL, just like an auto url-test group.
- { name: "fallback-auto", type: fallback, proxies: ["ss1", "ss2", "vmess1"], url: http://www.gstatic.com/generate_204, interval: 300 }
# select is used for selecting proxy or proxy group
# you can use RESTful API to switch proxy, is recommended for use in GUI.
- { name: "Proxy", type: select, proxies: ["ss1", "ss2", "vmess1", "auto"] }
Rule:
- DOMAIN-SUFFIX,google.com,Proxy
- DOMAIN-KEYWORD,google,Proxy
- DOMAIN,google.com,Proxy
- DOMAIN-SUFFIX,ad.com,REJECT
- IP-CIDR,127.0.0.0/8,DIRECT
- GEOIP,CN,DIRECT
# note: there is two ","
- FINAL,,Proxy
```
## Thanks
[riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
[v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
## License ## License
This software is released under the GPL-3.0 license.
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FDreamacro%2Fclash.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FDreamacro%2Fclash.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large)
## TODO
- [x] Complementing the necessary rule operators
- [x] Redir proxy
- [ ] UDP support
- [ ] Connection manager

203
adapter/adapter.go Normal file
View File

@ -0,0 +1,203 @@
package adapter
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"time"
"github.com/Dreamacro/clash/common/queue"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"go.uber.org/atomic"
)
type Proxy struct {
C.ProxyAdapter
history *queue.Queue
alive *atomic.Bool
}
// Alive implements C.Proxy
func (p *Proxy) Alive() bool {
return p.alive.Load()
}
// Dial implements C.Proxy
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
defer cancel()
return p.DialContext(ctx, metadata)
}
// DialContext implements C.ProxyAdapter
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
p.alive.Store(err == nil)
return conn, err
}
// DialUDP implements C.ProxyAdapter
func (p *Proxy) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultUDPTimeout)
defer cancel()
return p.ListenPacketContext(ctx, metadata)
}
// ListenPacketContext implements C.ProxyAdapter
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
p.alive.Store(err == nil)
return pc, err
}
// DelayHistory implements C.Proxy
func (p *Proxy) DelayHistory() []C.DelayHistory {
queue := p.history.Copy()
histories := []C.DelayHistory{}
for _, item := range queue {
histories = append(histories, item.(C.DelayHistory))
}
return histories
}
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
// implements C.Proxy
func (p *Proxy) LastDelay() (delay uint16) {
var max uint16 = 0xffff
if !p.alive.Load() {
return max
}
last := p.history.Last()
if last == nil {
return max
}
history := last.(C.DelayHistory)
if history.Delay == 0 {
return max
}
return history.Delay
}
// MarshalJSON implements C.ProxyAdapter
func (p *Proxy) MarshalJSON() ([]byte, error) {
inner, err := p.ProxyAdapter.MarshalJSON()
if err != nil {
return inner, err
}
mapping := map[string]any{}
json.Unmarshal(inner, &mapping)
mapping["history"] = p.DelayHistory()
mapping["alive"] = p.Alive()
mapping["name"] = p.Name()
mapping["udp"] = p.SupportUDP()
return json.Marshal(mapping)
}
// URLTest get the delay for the specified URL
// implements C.Proxy
func (p *Proxy) URLTest(ctx context.Context, url string) (delay, meanDelay uint16, err error) {
defer func() {
p.alive.Store(err == nil)
record := C.DelayHistory{Time: time.Now()}
if err == nil {
record.Delay = delay
record.MeanDelay = meanDelay
}
p.history.Put(record)
if p.history.Len() > 10 {
p.history.Pop()
}
}()
addr, err := urlToMetadata(url)
if err != nil {
return
}
start := time.Now()
instance, err := p.DialContext(ctx, &addr)
if err != nil {
return
}
defer instance.Close()
req, err := http.NewRequest(http.MethodHead, url, nil)
if err != nil {
return
}
req = req.WithContext(ctx)
transport := &http.Transport{
Dial: func(string, string) (net.Conn, error) {
return instance, nil
},
// from http.DefaultTransport
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
client := http.Client{
Transport: transport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
defer client.CloseIdleConnections()
resp, err := client.Do(req)
if err != nil {
return
}
resp.Body.Close()
delay = uint16(time.Since(start) / time.Millisecond)
resp, err = client.Do(req)
if err != nil {
// ignore error because some server will hijack the connection and close immediately
return delay, 0, nil
}
resp.Body.Close()
meanDelay = uint16(time.Since(start) / time.Millisecond / 2)
return
}
func NewProxy(adapter C.ProxyAdapter) *Proxy {
return &Proxy{adapter, queue.New(10), atomic.NewBool(true)}
}
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
u, err := url.Parse(rawURL)
if err != nil {
return
}
port := u.Port()
if port == "" {
switch u.Scheme {
case "https":
port = "443"
case "http":
port = "80"
default:
err = fmt.Errorf("%s scheme not Support", rawURL)
return
}
}
addr = C.Metadata{
Host: u.Hostname(),
DstIP: nil,
DstPort: port,
}
return
}

27
adapter/inbound/http.go Normal file
View File

@ -0,0 +1,27 @@
package inbound
import (
"net"
"net/netip"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/context"
"github.com/Dreamacro/clash/transport/socks5"
)
// NewHTTP receive normal http request and return HTTPContext
func NewHTTP(target socks5.Addr, source net.Addr, originTarget net.Addr, conn net.Conn) *context.ConnContext {
metadata := parseSocksAddr(target)
metadata.NetWork = C.TCP
metadata.Type = C.HTTP
if ip, port, err := parseAddr(source.String()); err == nil {
metadata.SrcIP = ip
metadata.SrcPort = port
}
if originTarget != nil {
if addrPort, err := netip.ParseAddrPort(originTarget.String()); err == nil {
metadata.OriginDst = addrPort
}
}
return context.NewConnContext(conn, metadata)
}

24
adapter/inbound/https.go Normal file
View File

@ -0,0 +1,24 @@
package inbound
import (
"net"
"net/http"
"net/netip"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/context"
)
// NewHTTPS receive CONNECT request and return ConnContext
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
metadata := parseHTTPAddr(request)
metadata.Type = C.HTTPCONNECT
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
metadata.SrcIP = ip
metadata.SrcPort = port
}
if addrPort, err := netip.ParseAddrPort(conn.LocalAddr().String()); err == nil {
metadata.OriginDst = addrPort
}
return context.NewConnContext(conn, metadata)
}

40
adapter/inbound/packet.go Normal file
View File

@ -0,0 +1,40 @@
package inbound
import (
"net"
"net/netip"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/socks5"
)
// 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, originTarget net.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
metadata := parseSocksAddr(target)
metadata.NetWork = C.UDP
metadata.Type = source
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
metadata.SrcIP = ip
metadata.SrcPort = port
}
if originTarget != nil {
if addrPort, err := netip.ParseAddrPort(originTarget.String()); err == nil {
metadata.OriginDst = addrPort
}
}
return &PacketAdapter{
UDPPacket: packet,
metadata: metadata,
}
}

25
adapter/inbound/socket.go Normal file
View File

@ -0,0 +1,25 @@
package inbound
import (
"net"
"net/netip"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/context"
"github.com/Dreamacro/clash/transport/socks5"
)
// NewSocket receive TCP inbound and return ConnContext
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnContext {
metadata := parseSocksAddr(target)
metadata.NetWork = C.TCP
metadata.Type = source
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
metadata.SrcIP = ip
metadata.SrcPort = port
}
if addrPort, err := netip.ParseAddrPort(conn.LocalAddr().String()); err == nil {
metadata.OriginDst = addrPort
}
return context.NewConnContext(conn, metadata)
}

66
adapter/inbound/util.go Normal file
View File

@ -0,0 +1,66 @@
package inbound
import (
"net"
"net/http"
"strconv"
"strings"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/socks5"
)
func parseSocksAddr(target socks5.Addr) *C.Metadata {
metadata := &C.Metadata{}
switch target[0] {
case socks5.AtypDomainName:
// trim for FQDN
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
case socks5.AtypIPv4:
ip := net.IP(target[1 : 1+net.IPv4len])
metadata.DstIP = ip
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
case socks5.AtypIPv6:
ip := net.IP(target[1 : 1+net.IPv6len])
metadata.DstIP = ip
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
}
return metadata
}
func parseHTTPAddr(request *http.Request) *C.Metadata {
host := request.URL.Hostname()
port := request.URL.Port()
if port == "" {
port = "80"
}
// trim FQDN (#737)
host = strings.TrimRight(host, ".")
metadata := &C.Metadata{
NetWork: C.TCP,
Host: host,
DstIP: nil,
DstPort: port,
}
if ip := net.ParseIP(host); ip != nil {
metadata.DstIP = ip
}
return metadata
}
func parseAddr(addr string) (net.IP, string, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, "", err
}
ip := net.ParseIP(host)
return ip, port, nil
}

138
adapter/outbound/base.go Normal file
View File

@ -0,0 +1,138 @@
package outbound
import (
"context"
"encoding/json"
"errors"
"net"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
)
type Base struct {
name string
addr string
iface string
tp C.AdapterType
udp bool
rmark int
}
// Name implements C.ProxyAdapter
func (b *Base) Name() string {
return b.name
}
// Type implements C.ProxyAdapter
func (b *Base) Type() C.AdapterType {
return b.tp
}
// StreamConn implements C.ProxyAdapter
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
return c, errors.New("no support")
}
// ListenPacketContext implements C.ProxyAdapter
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
return nil, errors.New("no support")
}
// SupportUDP implements C.ProxyAdapter
func (b *Base) SupportUDP() bool {
return b.udp
}
// MarshalJSON implements C.ProxyAdapter
func (b *Base) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]string{
"type": b.Type().String(),
})
}
// Addr implements C.ProxyAdapter
func (b *Base) Addr() string {
return b.addr
}
// Unwrap implements C.ProxyAdapter
func (b *Base) Unwrap(metadata *C.Metadata) C.Proxy {
return nil
}
// DialOptions return []dialer.Option from struct
func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
if b.iface != "" {
opts = append(opts, dialer.WithInterface(b.iface))
}
if b.rmark != 0 {
opts = append(opts, dialer.WithRoutingMark(b.rmark))
}
return opts
}
type BasicOption struct {
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
}
type BaseOption struct {
Name string
Addr string
Type C.AdapterType
UDP bool
Interface string
RoutingMark int
}
func NewBase(opt BaseOption) *Base {
return &Base{
name: opt.Name,
addr: opt.Addr,
tp: opt.Type,
udp: opt.UDP,
iface: opt.Interface,
rmark: opt.RoutingMark,
}
}
type conn struct {
net.Conn
chain C.Chain
}
// Chains implements C.Connection
func (c *conn) Chains() C.Chain {
return c.chain
}
// AppendToChains implements C.Connection
func (c *conn) AppendToChains(a C.ProxyAdapter) {
c.chain = append(c.chain, a.Name())
}
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
return &conn{c, []string{a.Name()}}
}
type packetConn struct {
net.PacketConn
chain C.Chain
}
// Chains implements C.Connection
func (c *packetConn) Chains() C.Chain {
return c.chain
}
// AppendToChains implements C.Connection
func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
c.chain = append(c.chain, a.Name())
}
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
return &packetConn{pc, []string{a.Name()}}
}

View File

@ -0,0 +1,46 @@
package outbound
import (
"context"
"net"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
)
type Direct struct {
*Base
}
// DialContext implements C.ProxyAdapter
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
if err != nil {
return nil, err
}
tcpKeepAlive(c)
return NewConn(c, d), nil
}
// ListenPacketContext implements C.ProxyAdapter
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
pc, err := dialer.ListenPacket(ctx, "udp", "", d.Base.DialOptions(opts...)...)
if err != nil {
return nil, err
}
return newPacketConn(&directPacketConn{pc}, d), nil
}
type directPacketConn struct {
net.PacketConn
}
func NewDirect() *Direct {
return &Direct{
Base: &Base{
name: "DIRECT",
tp: C.Direct,
udp: true,
},
}
}

157
adapter/outbound/http.go Normal file
View File

@ -0,0 +1,157 @@
package outbound
import (
"bufio"
"context"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strconv"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
)
type Http struct {
*Base
user string
pass string
tlsConfig *tls.Config
Headers http.Header
}
type HttpOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
UserName string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
TLS bool `proxy:"tls,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
Headers map[string]string `proxy:"headers,omitempty"`
}
// StreamConn implements C.ProxyAdapter
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
if h.tlsConfig != nil {
cc := tls.Client(c, h.tlsConfig)
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
defer cancel()
err := cc.HandshakeContext(ctx)
c = cc
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
}
}
if err := h.shakeHand(metadata, c); err != nil {
return nil, err
}
return c, nil
}
// DialContext implements C.ProxyAdapter
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
c, err := dialer.DialContext(ctx, "tcp", h.addr, h.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
}
tcpKeepAlive(c)
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = h.StreamConn(c, metadata)
if err != nil {
return nil, err
}
return NewConn(c, h), nil
}
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
addr := metadata.RemoteAddress()
req := &http.Request{
Method: http.MethodConnect,
URL: &url.URL{
Host: addr,
},
Host: addr,
Header: h.Headers.Clone(),
}
req.Header.Add("Proxy-Connection", "Keep-Alive")
if h.user != "" && h.pass != "" {
auth := h.user + ":" + h.pass
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
}
if err := req.Write(rw); err != nil {
return err
}
resp, err := http.ReadResponse(bufio.NewReader(rw), req)
if err != nil {
return err
}
if resp.StatusCode == http.StatusOK {
return nil
}
if resp.StatusCode == http.StatusProxyAuthRequired {
return errors.New("HTTP need auth")
}
if resp.StatusCode == http.StatusMethodNotAllowed {
return errors.New("CONNECT method not allowed by proxy")
}
if resp.StatusCode >= http.StatusInternalServerError {
return errors.New(resp.Status)
}
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
}
func NewHttp(option HttpOption) *Http {
var tlsConfig *tls.Config
if option.TLS {
sni := option.Server
if option.SNI != "" {
sni = option.SNI
}
tlsConfig = &tls.Config{
InsecureSkipVerify: option.SkipCertVerify,
ServerName: sni,
}
}
headers := http.Header{}
for name, value := range option.Headers {
headers.Add(name, value)
}
return &Http{
Base: &Base{
name: option.Name,
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
tp: C.Http,
iface: option.Interface,
rmark: option.RoutingMark,
},
user: option.UserName,
pass: option.Password,
tlsConfig: tlsConfig,
Headers: headers,
}
}

View File

@ -0,0 +1,62 @@
package outbound
import (
"context"
"io"
"net"
"time"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
)
type Reject struct {
*Base
}
// DialContext implements C.ProxyAdapter
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
return NewConn(&nopConn{}, r), nil
}
// ListenPacketContext implements C.ProxyAdapter
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
return newPacketConn(&nopPacketConn{}, r), nil
}
func NewReject() *Reject {
return &Reject{
Base: &Base{
name: "REJECT",
tp: C.Reject,
udp: true,
},
}
}
type nopConn struct{}
func (rw *nopConn) Read(b []byte) (int, error) {
return 0, io.EOF
}
func (rw *nopConn) Write(b []byte) (int, error) {
return 0, io.EOF
}
func (rw *nopConn) Close() error { return nil }
func (rw *nopConn) LocalAddr() net.Addr { return nil }
func (rw *nopConn) RemoteAddr() net.Addr { return nil }
func (rw *nopConn) SetDeadline(time.Time) error { return nil }
func (rw *nopConn) SetReadDeadline(time.Time) error { return nil }
func (rw *nopConn) SetWriteDeadline(time.Time) error { return nil }
type nopPacketConn struct{}
func (npc *nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
func (npc *nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
func (npc *nopPacketConn) Close() error { return nil }
func (npc *nopPacketConn) LocalAddr() net.Addr { return &net.UDPAddr{IP: net.IPv4zero, Port: 0} }
func (npc *nopPacketConn) SetDeadline(time.Time) error { return nil }
func (npc *nopPacketConn) SetReadDeadline(time.Time) error { return nil }
func (npc *nopPacketConn) SetWriteDeadline(time.Time) error { return nil }

View File

@ -0,0 +1,205 @@
package outbound
import (
"context"
"errors"
"fmt"
"net"
"strconv"
"github.com/Dreamacro/clash/common/structure"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/shadowsocks/core"
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
"github.com/Dreamacro/clash/transport/socks5"
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
)
type ShadowSocks struct {
*Base
cipher core.Cipher
// obfs
obfsMode string
obfsOption *simpleObfsOption
v2rayOption *v2rayObfs.Option
}
type ShadowSocksOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
Cipher string `proxy:"cipher"`
UDP bool `proxy:"udp,omitempty"`
Plugin string `proxy:"plugin,omitempty"`
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
}
type simpleObfsOption struct {
Mode string `obfs:"mode,omitempty"`
Host string `obfs:"host,omitempty"`
}
type v2rayObfsOption struct {
Mode string `obfs:"mode"`
Host string `obfs:"host,omitempty"`
Path string `obfs:"path,omitempty"`
TLS bool `obfs:"tls,omitempty"`
Headers map[string]string `obfs:"headers,omitempty"`
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
Mux bool `obfs:"mux,omitempty"`
}
// StreamConn implements C.ProxyAdapter
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
switch ss.obfsMode {
case "tls":
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
case "http":
_, port, _ := net.SplitHostPort(ss.addr)
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
case "websocket":
var err error
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
}
}
c = ss.cipher.StreamConn(c)
_, err := c.Write(serializesSocksAddr(metadata))
return c, err
}
// DialContext implements C.ProxyAdapter
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
}
tcpKeepAlive(c)
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = ss.StreamConn(c, metadata)
return NewConn(c, ss), err
}
// ListenPacketContext implements C.ProxyAdapter
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
if err != nil {
return nil, err
}
addr, err := resolveUDPAddr("udp", ss.addr)
if err != nil {
pc.Close()
return nil, err
}
pc = ss.cipher.PacketConn(pc)
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ss), nil
}
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
cipher := option.Cipher
password := option.Password
ciph, err := core.PickCipher(cipher, nil, password)
if err != nil {
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
}
var v2rayOption *v2rayObfs.Option
var obfsOption *simpleObfsOption
obfsMode := ""
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
if option.Plugin == "obfs" {
opts := simpleObfsOption{Host: "bing.com"}
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
return nil, fmt.Errorf("ss %s initialize obfs error: %w", addr, err)
}
if opts.Mode != "tls" && opts.Mode != "http" {
return nil, fmt.Errorf("ss %s obfs mode error: %s", addr, opts.Mode)
}
obfsMode = opts.Mode
obfsOption = &opts
} else if option.Plugin == "v2ray-plugin" {
opts := v2rayObfsOption{Host: "bing.com", Mux: true}
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %w", addr, err)
}
if opts.Mode != "websocket" {
return nil, fmt.Errorf("ss %s obfs mode error: %s", addr, opts.Mode)
}
obfsMode = opts.Mode
v2rayOption = &v2rayObfs.Option{
Host: opts.Host,
Path: opts.Path,
Headers: opts.Headers,
Mux: opts.Mux,
}
if opts.TLS {
v2rayOption.TLS = true
v2rayOption.SkipCertVerify = opts.SkipCertVerify
}
}
return &ShadowSocks{
Base: &Base{
name: option.Name,
addr: addr,
tp: C.Shadowsocks,
udp: option.UDP,
iface: option.Interface,
rmark: option.RoutingMark,
},
cipher: ciph,
obfsMode: obfsMode,
v2rayOption: v2rayOption,
obfsOption: obfsOption,
}, nil
}
type ssPacketConn struct {
net.PacketConn
rAddr net.Addr
}
func (spc *ssPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
if err != nil {
return
}
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
}
func (spc *ssPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
n, _, e := spc.PacketConn.ReadFrom(b)
if e != nil {
return 0, nil, e
}
addr := socks5.SplitAddr(b[:n])
if addr == nil {
return 0, nil, errors.New("parse addr error")
}
udpAddr := addr.UDPAddr()
if udpAddr == nil {
return 0, nil, errors.New("parse addr error")
}
copy(b, b[len(addr):])
return n - len(addr), udpAddr, e
}

View File

@ -0,0 +1,159 @@
package outbound
import (
"context"
"fmt"
"net"
"strconv"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/shadowsocks/core"
"github.com/Dreamacro/clash/transport/shadowsocks/shadowaead"
"github.com/Dreamacro/clash/transport/shadowsocks/shadowstream"
"github.com/Dreamacro/clash/transport/ssr/obfs"
"github.com/Dreamacro/clash/transport/ssr/protocol"
)
type ShadowSocksR struct {
*Base
cipher core.Cipher
obfs obfs.Obfs
protocol protocol.Protocol
}
type ShadowSocksROption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
Cipher string `proxy:"cipher"`
Obfs string `proxy:"obfs"`
ObfsParam string `proxy:"obfs-param,omitempty"`
Protocol string `proxy:"protocol"`
ProtocolParam string `proxy:"protocol-param,omitempty"`
UDP bool `proxy:"udp,omitempty"`
}
// StreamConn implements C.ProxyAdapter
func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
c = ssr.obfs.StreamConn(c)
c = ssr.cipher.StreamConn(c)
var (
iv []byte
err error
)
switch conn := c.(type) {
case *shadowstream.Conn:
iv, err = conn.ObtainWriteIV()
if err != nil {
return nil, err
}
case *shadowaead.Conn:
return nil, fmt.Errorf("invalid connection type")
}
c = ssr.protocol.StreamConn(c, iv)
_, err = c.Write(serializesSocksAddr(metadata))
return c, err
}
// DialContext implements C.ProxyAdapter
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
}
tcpKeepAlive(c)
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = ssr.StreamConn(c, metadata)
return NewConn(c, ssr), err
}
// ListenPacketContext implements C.ProxyAdapter
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
pc, err := dialer.ListenPacket(ctx, "udp", "", ssr.Base.DialOptions(opts...)...)
if err != nil {
return nil, err
}
addr, err := resolveUDPAddr("udp", ssr.addr)
if err != nil {
pc.Close()
return nil, err
}
pc = ssr.cipher.PacketConn(pc)
pc = ssr.protocol.PacketConn(pc)
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
}
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
// SSR protocol compatibility
// https://github.com/Dreamacro/clash/pull/2056
if option.Cipher == "none" {
option.Cipher = "dummy"
}
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
cipher := option.Cipher
password := option.Password
coreCiph, err := core.PickCipher(cipher, nil, password)
if err != nil {
return nil, fmt.Errorf("ssr %s initialize error: %w", addr, err)
}
var (
ivSize int
key []byte
)
if option.Cipher == "dummy" {
ivSize = 0
key = core.Kdf(option.Password, 16)
} else {
ciph, ok := coreCiph.(*core.StreamCipher)
if !ok {
return nil, fmt.Errorf("%s is not none or a supported stream cipher in ssr", cipher)
}
ivSize = ciph.IVSize()
key = ciph.Key
}
obfs, obfsOverhead, err := obfs.PickObfs(option.Obfs, &obfs.Base{
Host: option.Server,
Port: option.Port,
Key: key,
IVSize: ivSize,
Param: option.ObfsParam,
})
if err != nil {
return nil, fmt.Errorf("ssr %s initialize obfs error: %w", addr, err)
}
protocol, err := protocol.PickProtocol(option.Protocol, &protocol.Base{
Key: key,
Overhead: obfsOverhead,
Param: option.ProtocolParam,
})
if err != nil {
return nil, fmt.Errorf("ssr %s initialize protocol error: %w", addr, err)
}
return &ShadowSocksR{
Base: &Base{
name: option.Name,
addr: addr,
tp: C.ShadowsocksR,
udp: option.UDP,
iface: option.Interface,
rmark: option.RoutingMark,
},
cipher: coreCiph,
obfs: obfs,
protocol: protocol,
}, nil
}

166
adapter/outbound/snell.go Normal file
View File

@ -0,0 +1,166 @@
package outbound
import (
"context"
"fmt"
"net"
"strconv"
"github.com/Dreamacro/clash/common/structure"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
"github.com/Dreamacro/clash/transport/snell"
)
type Snell struct {
*Base
psk []byte
pool *snell.Pool
obfsOption *simpleObfsOption
version int
}
type SnellOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Psk string `proxy:"psk"`
UDP bool `proxy:"udp,omitempty"`
Version int `proxy:"version,omitempty"`
ObfsOpts map[string]any `proxy:"obfs-opts,omitempty"`
}
type streamOption struct {
psk []byte
version int
addr string
obfsOption *simpleObfsOption
}
func streamConn(c net.Conn, option streamOption) *snell.Snell {
switch option.obfsOption.Mode {
case "tls":
c = obfs.NewTLSObfs(c, option.obfsOption.Host)
case "http":
_, port, _ := net.SplitHostPort(option.addr)
c = obfs.NewHTTPObfs(c, option.obfsOption.Host, port)
}
return snell.StreamConn(c, option.psk, option.version)
}
// StreamConn implements C.ProxyAdapter
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
return c, err
}
// DialContext implements C.ProxyAdapter
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
if s.version == snell.Version2 && len(opts) == 0 {
c, err := s.pool.Get()
if err != nil {
return nil, err
}
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
c.Close()
return nil, err
}
return NewConn(c, s), err
}
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
}
tcpKeepAlive(c)
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = s.StreamConn(c, metadata)
return NewConn(c, s), err
}
// ListenPacketContext implements C.ProxyAdapter
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
if err != nil {
return nil, err
}
tcpKeepAlive(c)
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
err = snell.WriteUDPHeader(c, s.version)
if err != nil {
return nil, err
}
pc := snell.PacketConn(c)
return newPacketConn(pc, s), nil
}
func NewSnell(option SnellOption) (*Snell, error) {
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
psk := []byte(option.Psk)
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
obfsOption := &simpleObfsOption{Host: "bing.com"}
if err := decoder.Decode(option.ObfsOpts, obfsOption); err != nil {
return nil, fmt.Errorf("snell %s initialize obfs error: %w", addr, err)
}
switch obfsOption.Mode {
case "tls", "http", "":
break
default:
return nil, fmt.Errorf("snell %s obfs mode error: %s", addr, obfsOption.Mode)
}
// backward compatible
if option.Version == 0 {
option.Version = snell.DefaultSnellVersion
}
switch option.Version {
case snell.Version1, snell.Version2:
if option.UDP {
return nil, fmt.Errorf("snell version %d not support UDP", option.Version)
}
case snell.Version3:
default:
return nil, fmt.Errorf("snell version error: %d", option.Version)
}
s := &Snell{
Base: &Base{
name: option.Name,
addr: addr,
tp: C.Snell,
udp: option.UDP,
iface: option.Interface,
rmark: option.RoutingMark,
},
psk: psk,
obfsOption: obfsOption,
version: option.Version,
}
if option.Version == snell.Version2 {
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
c, err := dialer.DialContext(ctx, "tcp", addr, s.Base.DialOptions()...)
if err != nil {
return nil, err
}
tcpKeepAlive(c)
return streamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
})
}
return s, nil
}

212
adapter/outbound/socks5.go Normal file
View File

@ -0,0 +1,212 @@
package outbound
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"strconv"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/socks5"
)
type Socks5 struct {
*Base
user string
pass string
tls bool
skipCertVerify bool
tlsConfig *tls.Config
}
type Socks5Option struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
UserName string `proxy:"username,omitempty"`
Password string `proxy:"password,omitempty"`
TLS bool `proxy:"tls,omitempty"`
UDP bool `proxy:"udp,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
}
// StreamConn implements C.ProxyAdapter
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
if ss.tls {
cc := tls.Client(c, ss.tlsConfig)
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
defer cancel()
err := cc.HandshakeContext(ctx)
c = cc
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
}
}
var user *socks5.User
if ss.user != "" {
user = &socks5.User{
Username: ss.user,
Password: ss.pass,
}
}
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
return nil, err
}
return c, nil
}
// DialContext implements C.ProxyAdapter
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
}
tcpKeepAlive(c)
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = ss.StreamConn(c, metadata)
if err != nil {
return nil, err
}
return NewConn(c, ss), nil
}
// ListenPacketContext implements C.ProxyAdapter
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
if err != nil {
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
return
}
if ss.tls {
cc := tls.Client(c, ss.tlsConfig)
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
defer cancel()
err = cc.HandshakeContext(ctx)
c = cc
}
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
tcpKeepAlive(c)
var user *socks5.User
if ss.user != "" {
user = &socks5.User{
Username: ss.user,
Password: ss.pass,
}
}
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
if err != nil {
err = fmt.Errorf("client hanshake error: %w", err)
return
}
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
if err != nil {
return
}
go func() {
io.Copy(io.Discard, c)
c.Close()
// A UDP association terminates when the TCP connection that the UDP
// ASSOCIATE request arrived on terminates. RFC1928
pc.Close()
}()
// Support unspecified UDP bind address.
bindUDPAddr := bindAddr.UDPAddr()
if bindUDPAddr == nil {
err = errors.New("invalid UDP bind address")
return
} else if bindUDPAddr.IP.IsUnspecified() {
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
if err != nil {
return nil, err
}
bindUDPAddr.IP = serverAddr.IP
}
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
}
func NewSocks5(option Socks5Option) *Socks5 {
var tlsConfig *tls.Config
if option.TLS {
tlsConfig = &tls.Config{
InsecureSkipVerify: option.SkipCertVerify,
ServerName: option.Server,
}
}
return &Socks5{
Base: &Base{
name: option.Name,
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
tp: C.Socks5,
udp: option.UDP,
iface: option.Interface,
rmark: option.RoutingMark,
},
user: option.UserName,
pass: option.Password,
tls: option.TLS,
skipCertVerify: option.SkipCertVerify,
tlsConfig: tlsConfig,
}
}
type socksPacketConn struct {
net.PacketConn
rAddr net.Addr
tcpConn net.Conn
}
func (uc *socksPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
if err != nil {
return
}
return uc.PacketConn.WriteTo(packet, uc.rAddr)
}
func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
n, _, e := uc.PacketConn.ReadFrom(b)
if e != nil {
return 0, nil, e
}
addr, payload, err := socks5.DecodeUDPPacket(b)
if err != nil {
return 0, nil, err
}
udpAddr := addr.UDPAddr()
if udpAddr == nil {
return 0, nil, errors.New("parse udp addr error")
}
// due to DecodeUDPPacket is mutable, record addr length
copy(b, payload)
return n - len(addr) - 3, udpAddr, nil
}
func (uc *socksPacketConn) Close() error {
uc.tcpConn.Close()
return uc.PacketConn.Close()
}

214
adapter/outbound/trojan.go Normal file
View File

@ -0,0 +1,214 @@
package outbound
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"strconv"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/gun"
"github.com/Dreamacro/clash/transport/trojan"
"golang.org/x/net/http2"
)
type Trojan struct {
*Base
instance *trojan.Trojan
option *TrojanOption
// for gun mux
gunTLSConfig *tls.Config
gunConfig *gun.Config
transport *http2.Transport
}
type TrojanOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
ALPN []string `proxy:"alpn,omitempty"`
SNI string `proxy:"sni,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
UDP bool `proxy:"udp,omitempty"`
Network string `proxy:"network,omitempty"`
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
}
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
if t.option.Network == "ws" {
host, port, _ := net.SplitHostPort(t.addr)
wsOpts := &trojan.WebsocketOption{
Host: host,
Port: port,
Path: t.option.WSOpts.Path,
}
if t.option.SNI != "" {
wsOpts.Host = t.option.SNI
}
if len(t.option.WSOpts.Headers) != 0 {
header := http.Header{}
for key, value := range t.option.WSOpts.Headers {
header.Add(key, value)
}
wsOpts.Headers = header
}
return t.instance.StreamWebsocketConn(c, wsOpts)
}
return t.instance.StreamConn(c)
}
// StreamConn implements C.ProxyAdapter
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
var err error
if t.transport != nil {
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
} else {
c, err = t.plainStream(c)
}
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
}
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
return c, err
}
// DialContext implements C.ProxyAdapter
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
// gun transport
if t.transport != nil && len(opts) == 0 {
c, err := gun.StreamGunWithTransport(t.transport, t.gunConfig)
if err != nil {
return nil, err
}
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
c.Close()
return nil, err
}
return NewConn(c, t), nil
}
c, err := dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
}
tcpKeepAlive(c)
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = t.StreamConn(c, metadata)
if err != nil {
return nil, err
}
return NewConn(c, t), err
}
// ListenPacketContext implements C.ProxyAdapter
func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
var c net.Conn
// grpc transport
if t.transport != nil && len(opts) == 0 {
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
}
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
} else {
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
}
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
tcpKeepAlive(c)
c, err = t.plainStream(c)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
}
}
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
if err != nil {
return nil, err
}
pc := t.instance.PacketConn(c)
return newPacketConn(pc, t), err
}
func NewTrojan(option TrojanOption) (*Trojan, error) {
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
tOption := &trojan.Option{
Password: option.Password,
ALPN: option.ALPN,
ServerName: option.Server,
SkipCertVerify: option.SkipCertVerify,
}
if option.SNI != "" {
tOption.ServerName = option.SNI
}
t := &Trojan{
Base: &Base{
name: option.Name,
addr: addr,
tp: C.Trojan,
udp: option.UDP,
iface: option.Interface,
rmark: option.RoutingMark,
},
instance: trojan.New(tOption),
option: &option,
}
if option.Network == "grpc" {
dialFn := func(network, addr string) (net.Conn, error) {
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
}
tcpKeepAlive(c)
return c, nil
}
tlsConfig := &tls.Config{
NextProtos: option.ALPN,
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: tOption.SkipCertVerify,
ServerName: tOption.ServerName,
}
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
t.gunTLSConfig = tlsConfig
t.gunConfig = &gun.Config{
ServiceName: option.GrpcOpts.GrpcServiceName,
Host: tOption.ServerName,
}
}
return t, nil
}

60
adapter/outbound/util.go Normal file
View File

@ -0,0 +1,60 @@
package outbound
import (
"net"
"strconv"
"time"
"github.com/Dreamacro/clash/component/resolver"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/socks5"
"github.com/Dreamacro/protobytes"
)
func tcpKeepAlive(c net.Conn) {
if tcp, ok := c.(*net.TCPConn); ok {
tcp.SetKeepAlive(true)
tcp.SetKeepAlivePeriod(30 * time.Second)
}
}
func serializesSocksAddr(metadata *C.Metadata) []byte {
buf := protobytes.BytesWriter{}
addrType := metadata.AddrType()
buf.PutUint8(uint8(addrType))
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
switch addrType {
case socks5.AtypDomainName:
buf.PutUint8(uint8(len(metadata.Host)))
buf.PutString(metadata.Host)
case socks5.AtypIPv4:
buf.PutSlice(metadata.DstIP.To4())
case socks5.AtypIPv6:
buf.PutSlice(metadata.DstIP.To16())
}
buf.PutUint16be(uint16(p))
return buf.Bytes()
}
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
ip, err := resolver.ResolveIP(host)
if err != nil {
return nil, err
}
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
}
func safeConnClose(c net.Conn, err error) {
if err != nil {
c.Close()
}
}

385
adapter/outbound/vmess.go Normal file
View File

@ -0,0 +1,385 @@
package outbound
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"github.com/Dreamacro/clash/component/dialer"
"github.com/Dreamacro/clash/component/resolver"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/transport/gun"
"github.com/Dreamacro/clash/transport/socks5"
"github.com/Dreamacro/clash/transport/vmess"
"golang.org/x/net/http2"
)
var ErrUDPRemoteAddrMismatch = errors.New("udp packet dropped due to mismatched remote address")
type Vmess struct {
*Base
client *vmess.Client
option *VmessOption
// for gun mux
gunTLSConfig *tls.Config
gunConfig *gun.Config
transport *http2.Transport
}
type VmessOption struct {
BasicOption
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
UUID string `proxy:"uuid"`
AlterID int `proxy:"alterId"`
Cipher string `proxy:"cipher"`
UDP bool `proxy:"udp,omitempty"`
Network string `proxy:"network,omitempty"`
TLS bool `proxy:"tls,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
ServerName string `proxy:"servername,omitempty"`
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
}
type HTTPOptions struct {
Method string `proxy:"method,omitempty"`
Path []string `proxy:"path,omitempty"`
Headers map[string][]string `proxy:"headers,omitempty"`
}
type HTTP2Options struct {
Host []string `proxy:"host,omitempty"`
Path string `proxy:"path,omitempty"`
}
type GrpcOptions struct {
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
}
type WSOptions struct {
Path string `proxy:"path,omitempty"`
Headers map[string]string `proxy:"headers,omitempty"`
MaxEarlyData int `proxy:"max-early-data,omitempty"`
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
}
// StreamConn implements C.ProxyAdapter
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
var err error
switch v.option.Network {
case "ws":
host, port, _ := net.SplitHostPort(v.addr)
wsOpts := &vmess.WebsocketConfig{
Host: host,
Port: port,
Path: v.option.WSOpts.Path,
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
}
if len(v.option.WSOpts.Headers) != 0 {
header := http.Header{}
for key, value := range v.option.WSOpts.Headers {
header.Add(key, value)
}
wsOpts.Headers = header
}
if v.option.TLS {
wsOpts.TLS = true
wsOpts.TLSConfig = &tls.Config{
ServerName: host,
InsecureSkipVerify: v.option.SkipCertVerify,
NextProtos: []string{"http/1.1"},
}
if v.option.ServerName != "" {
wsOpts.TLSConfig.ServerName = v.option.ServerName
} else if host := wsOpts.Headers.Get("Host"); host != "" {
wsOpts.TLSConfig.ServerName = host
}
}
c, err = vmess.StreamWebsocketConn(c, wsOpts)
case "http":
// readability first, so just copy default TLS logic
if v.option.TLS {
host, _, _ := net.SplitHostPort(v.addr)
tlsOpts := &vmess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
}
if v.option.ServerName != "" {
tlsOpts.Host = v.option.ServerName
}
c, err = vmess.StreamTLSConn(c, tlsOpts)
if err != nil {
return nil, err
}
}
host, _, _ := net.SplitHostPort(v.addr)
httpOpts := &vmess.HTTPConfig{
Host: host,
Method: v.option.HTTPOpts.Method,
Path: v.option.HTTPOpts.Path,
Headers: v.option.HTTPOpts.Headers,
}
c = vmess.StreamHTTPConn(c, httpOpts)
case "h2":
host, _, _ := net.SplitHostPort(v.addr)
tlsOpts := vmess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
NextProtos: []string{"h2"},
}
if v.option.ServerName != "" {
tlsOpts.Host = v.option.ServerName
}
c, err = vmess.StreamTLSConn(c, &tlsOpts)
if err != nil {
return nil, err
}
h2Opts := &vmess.H2Config{
Hosts: v.option.HTTP2Opts.Host,
Path: v.option.HTTP2Opts.Path,
}
c, err = vmess.StreamH2Conn(c, h2Opts)
case "grpc":
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
default:
// handle TLS
if v.option.TLS {
host, _, _ := net.SplitHostPort(v.addr)
tlsOpts := &vmess.TLSConfig{
Host: host,
SkipCertVerify: v.option.SkipCertVerify,
}
if v.option.ServerName != "" {
tlsOpts.Host = v.option.ServerName
}
c, err = vmess.StreamTLSConn(c, tlsOpts)
}
}
if err != nil {
return nil, err
}
return v.client.StreamConn(c, parseVmessAddr(metadata))
}
// DialContext implements C.ProxyAdapter
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
// gun transport
if v.transport != nil && len(opts) == 0 {
c, err := gun.StreamGunWithTransport(v.transport, v.gunConfig)
if err != nil {
return nil, err
}
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
if err != nil {
return nil, err
}
return NewConn(c, v), nil
}
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
}
tcpKeepAlive(c)
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = v.StreamConn(c, metadata)
return NewConn(c, v), err
}
// ListenPacketContext implements C.ProxyAdapter
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
if !metadata.Resolved() {
ip, err := resolver.ResolveIP(metadata.Host)
if err != nil {
return nil, errors.New("can't resolve ip")
}
metadata.DstIP = ip
}
var c net.Conn
// gun transport
if v.transport != nil && len(opts) == 0 {
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
if err != nil {
return nil, err
}
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
} else {
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
}
tcpKeepAlive(c)
defer func(c net.Conn) {
safeConnClose(c, err)
}(c)
c, err = v.StreamConn(c, metadata)
}
if err != nil {
return nil, fmt.Errorf("new vmess client error: %v", err)
}
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
}
func NewVmess(option VmessOption) (*Vmess, error) {
security := strings.ToLower(option.Cipher)
client, err := vmess.NewClient(vmess.Config{
UUID: option.UUID,
AlterID: uint16(option.AlterID),
Security: security,
HostName: option.Server,
Port: strconv.Itoa(option.Port),
IsAead: option.AlterID == 0,
})
if err != nil {
return nil, err
}
switch option.Network {
case "h2", "grpc":
if !option.TLS {
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
}
}
v := &Vmess{
Base: &Base{
name: option.Name,
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
tp: C.Vmess,
udp: option.UDP,
iface: option.Interface,
rmark: option.RoutingMark,
},
client: client,
option: &option,
}
switch option.Network {
case "h2":
if len(option.HTTP2Opts.Host) == 0 {
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
}
case "grpc":
dialFn := func(network, addr string) (net.Conn, error) {
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
}
tcpKeepAlive(c)
return c, nil
}
gunConfig := &gun.Config{
ServiceName: v.option.GrpcOpts.GrpcServiceName,
Host: v.option.ServerName,
}
tlsConfig := &tls.Config{
InsecureSkipVerify: v.option.SkipCertVerify,
ServerName: v.option.ServerName,
}
if v.option.ServerName == "" {
host, _, _ := net.SplitHostPort(v.addr)
tlsConfig.ServerName = host
gunConfig.Host = host
}
v.gunTLSConfig = tlsConfig
v.gunConfig = gunConfig
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
}
return v, nil
}
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
var addrType byte
var addr []byte
switch metadata.AddrType() {
case socks5.AtypIPv4:
addrType = vmess.AtypIPv4
addr = make([]byte, net.IPv4len)
copy(addr[:], metadata.DstIP.To4())
case socks5.AtypIPv6:
addrType = vmess.AtypIPv6
addr = make([]byte, net.IPv6len)
copy(addr[:], metadata.DstIP.To16())
case socks5.AtypDomainName:
addrType = vmess.AtypDomainName
addr = make([]byte, len(metadata.Host)+1)
addr[0] = byte(len(metadata.Host))
copy(addr[1:], []byte(metadata.Host))
}
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
return &vmess.DstAddr{
UDP: metadata.NetWork == C.UDP,
AddrType: addrType,
Addr: addr,
Port: uint(port),
}
}
type vmessPacketConn struct {
net.Conn
rAddr net.Addr
}
// WriteTo implments C.PacketConn.WriteTo
// Since VMess doesn't support full cone NAT by design, we verify if addr matches uc.rAddr, and drop the packet if not.
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
allowedAddr := uc.rAddr.(*net.UDPAddr)
destAddr := addr.(*net.UDPAddr)
if !(allowedAddr.IP.Equal(destAddr.IP) && allowedAddr.Port == destAddr.Port) {
return 0, ErrUDPRemoteAddrMismatch
}
return uc.Conn.Write(b)
}
func (uc *vmessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
n, err := uc.Conn.Read(b)
return n, uc.rAddr, err
}

View File

@ -0,0 +1,29 @@
package outboundgroup
import (
"time"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/constant/provider"
)
const (
defaultGetProxiesDuration = time.Second * 5
)
func touchProviders(providers []provider.ProxyProvider) {
for _, provider := range providers {
provider.Touch()
}
}
func getProvidersProxies(providers []provider.ProxyProvider, touch bool) []C.Proxy {
proxies := []C.Proxy{}
for _, provider := range providers {
if touch {
provider.Touch()
}
proxies = append(proxies, provider.Proxies()...)
}
return proxies
}

View File

@ -0,0 +1,106 @@
package outboundgroup
import (
"context"
"encoding/json"
"github.com/Dreamacro/clash/adapter/outbound"
"github.com/Dreamacro/clash/common/singledo"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/constant/provider"
)
type Fallback struct {
*outbound.Base
disableUDP bool
single *singledo.Single
providers []provider.ProxyProvider
}
func (f *Fallback) Now() string {
proxy := f.findAliveProxy(false)
return proxy.Name()
}
// DialContext implements C.ProxyAdapter
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
proxy := f.findAliveProxy(true)
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
if err == nil {
c.AppendToChains(f)
}
return c, err
}
// ListenPacketContext implements C.ProxyAdapter
func (f *Fallback) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
proxy := f.findAliveProxy(true)
pc, err := proxy.ListenPacketContext(ctx, metadata, f.Base.DialOptions(opts...)...)
if err == nil {
pc.AppendToChains(f)
}
return pc, err
}
// SupportUDP implements C.ProxyAdapter
func (f *Fallback) SupportUDP() bool {
if f.disableUDP {
return false
}
proxy := f.findAliveProxy(false)
return proxy.SupportUDP()
}
// MarshalJSON implements C.ProxyAdapter
func (f *Fallback) MarshalJSON() ([]byte, error) {
var all []string
for _, proxy := range f.proxies(false) {
all = append(all, proxy.Name())
}
return json.Marshal(map[string]any{
"type": f.Type().String(),
"now": f.Now(),
"all": all,
})
}
// Unwrap implements C.ProxyAdapter
func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
proxy := f.findAliveProxy(true)
return proxy
}
func (f *Fallback) proxies(touch bool) []C.Proxy {
elm, _, _ := f.single.Do(func() (any, error) {
return getProvidersProxies(f.providers, touch), nil
})
return elm.([]C.Proxy)
}
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
proxies := f.proxies(touch)
for _, proxy := range proxies {
if proxy.Alive() {
return proxy
}
}
return proxies[0]
}
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
return &Fallback{
Base: outbound.NewBase(outbound.BaseOption{
Name: option.Name,
Type: C.Fallback,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
}),
single: singledo.NewSingle(defaultGetProxiesDuration),
providers: providers,
disableUDP: option.DisableUDP,
}
}

View File

@ -0,0 +1,189 @@
package outboundgroup
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"github.com/Dreamacro/clash/adapter/outbound"
"github.com/Dreamacro/clash/common/murmur3"
"github.com/Dreamacro/clash/common/singledo"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/constant/provider"
"golang.org/x/net/publicsuffix"
)
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
type LoadBalance struct {
*outbound.Base
disableUDP bool
single *singledo.Single
providers []provider.ProxyProvider
strategyFn strategyFn
}
var errStrategy = errors.New("unsupported strategy")
func parseStrategy(config map[string]any) string {
if strategy, ok := config["strategy"].(string); ok {
return strategy
}
return "consistent-hashing"
}
func getKey(metadata *C.Metadata) string {
if metadata.Host != "" {
// ip host
if ip := net.ParseIP(metadata.Host); ip != nil {
return metadata.Host
}
if etld, err := publicsuffix.EffectiveTLDPlusOne(metadata.Host); err == nil {
return etld
}
}
if metadata.DstIP == nil {
return ""
}
return metadata.DstIP.String()
}
func jumpHash(key uint64, buckets int32) int32 {
var b, j int64
for j < int64(buckets) {
b = j
key = key*2862933555777941757 + 1
j = int64(float64(b+1) * (float64(int64(1)<<31) / float64((key>>33)+1)))
}
return int32(b)
}
// DialContext implements C.ProxyAdapter
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
defer func() {
if err == nil {
c.AppendToChains(lb)
}
}()
proxy := lb.Unwrap(metadata)
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
return
}
// ListenPacketContext implements C.ProxyAdapter
func (lb *LoadBalance) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (pc C.PacketConn, err error) {
defer func() {
if err == nil {
pc.AppendToChains(lb)
}
}()
proxy := lb.Unwrap(metadata)
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
}
// SupportUDP implements C.ProxyAdapter
func (lb *LoadBalance) SupportUDP() bool {
return !lb.disableUDP
}
func strategyRoundRobin() strategyFn {
idx := 0
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
length := len(proxies)
for i := 0; i < length; i++ {
idx = (idx + 1) % length
proxy := proxies[idx]
if proxy.Alive() {
return proxy
}
}
return proxies[0]
}
}
func strategyConsistentHashing() strategyFn {
maxRetry := 5
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
buckets := int32(len(proxies))
for i := 0; i < maxRetry; i, key = i+1, key+1 {
idx := jumpHash(key, buckets)
proxy := proxies[idx]
if proxy.Alive() {
return proxy
}
}
// when availability is poor, traverse the entire list to get the available nodes
for _, proxy := range proxies {
if proxy.Alive() {
return proxy
}
}
return proxies[0]
}
}
// Unwrap implements C.ProxyAdapter
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
proxies := lb.proxies(true)
return lb.strategyFn(proxies, metadata)
}
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
elm, _, _ := lb.single.Do(func() (any, error) {
return getProvidersProxies(lb.providers, touch), nil
})
return elm.([]C.Proxy)
}
// MarshalJSON implements C.ProxyAdapter
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
var all []string
for _, proxy := range lb.proxies(false) {
all = append(all, proxy.Name())
}
return json.Marshal(map[string]any{
"type": lb.Type().String(),
"all": all,
})
}
func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
var strategyFn strategyFn
switch strategy {
case "consistent-hashing":
strategyFn = strategyConsistentHashing()
case "round-robin":
strategyFn = strategyRoundRobin()
default:
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
}
return &LoadBalance{
Base: outbound.NewBase(outbound.BaseOption{
Name: option.Name,
Type: C.LoadBalance,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
}),
single: singledo.NewSingle(defaultGetProxiesDuration),
providers: providers,
strategyFn: strategyFn,
disableUDP: option.DisableUDP,
}, nil
}

View File

@ -0,0 +1,166 @@
package outboundgroup
import (
"errors"
"fmt"
"github.com/Dreamacro/clash/adapter/outbound"
"github.com/Dreamacro/clash/adapter/provider"
"github.com/Dreamacro/clash/common/structure"
C "github.com/Dreamacro/clash/constant"
types "github.com/Dreamacro/clash/constant/provider"
regexp "github.com/dlclark/regexp2"
)
var (
errFormat = errors.New("format error")
errType = errors.New("unsupport type")
errMissProxy = errors.New("`use` or `proxies` missing")
errMissHealthCheck = errors.New("`url` or `interval` missing")
errDuplicateProvider = errors.New("duplicate provider name")
)
type GroupCommonOption struct {
outbound.BasicOption
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"`
Lazy bool `group:"lazy,omitempty"`
DisableUDP bool `group:"disable-udp,omitempty"`
Filter string `group:"filter,omitempty"`
}
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
groupOption := &GroupCommonOption{
Lazy: true,
}
if err := decoder.Decode(config, groupOption); err != nil {
return nil, errFormat
}
if groupOption.Type == "" || groupOption.Name == "" {
return nil, errFormat
}
var (
groupName = groupOption.Name
filterReg *regexp.Regexp
)
if groupOption.Filter != "" {
f, err := regexp.Compile(groupOption.Filter, regexp.None)
if err != nil {
return nil, fmt.Errorf("%s: invalid filter regex: %w", groupName, err)
}
filterReg = f
}
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
}
providers := []types.ProxyProvider{}
if len(groupOption.Proxies) != 0 {
ps, err := getProxies(proxyMap, groupOption.Proxies)
if err != nil {
return nil, fmt.Errorf("%s: %w", groupName, err)
}
if _, ok := providersMap[groupName]; ok {
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
}
// select don't need health check
if groupOption.Type == "select" || groupOption.Type == "relay" {
hc := provider.NewHealthCheck(ps, "", 0, true)
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
if err != nil {
return nil, fmt.Errorf("%s: %w", groupName, err)
}
providers = append(providers, pd)
providersMap[groupName] = pd
} else {
if groupOption.URL == "" || groupOption.Interval == 0 {
return nil, fmt.Errorf("%s: %w", groupName, errMissHealthCheck)
}
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
if err != nil {
return nil, fmt.Errorf("%s: %w", groupName, err)
}
providers = append(providers, pd)
providersMap[groupName] = pd
}
}
if len(groupOption.Use) != 0 {
list, err := getProviders(providersMap, groupOption.Use)
if err != nil {
return nil, fmt.Errorf("%s: %w", groupName, err)
}
if filterReg != nil {
pd := provider.NewFilterableProvider(groupName, list, filterReg)
providers = append(providers, pd)
} else {
providers = append(providers, list...)
}
}
var group C.ProxyAdapter
switch groupOption.Type {
case "url-test":
opts := parseURLTestOption(config)
group = NewURLTest(groupOption, providers, opts...)
case "select":
group = NewSelector(groupOption, providers)
case "fallback":
group = NewFallback(groupOption, providers)
case "load-balance":
strategy := parseStrategy(config)
return NewLoadBalance(groupOption, providers, strategy)
case "relay":
group = NewRelay(groupOption, providers)
default:
return nil, fmt.Errorf("%s %w: %s", groupName, 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]types.ProxyProvider, list []string) ([]types.ProxyProvider, error) {
var ps []types.ProxyProvider
for _, name := range list {
p, ok := mapping[name]
if !ok {
return nil, fmt.Errorf("'%s' not found", name)
}
if p.VehicleType() == types.Compatible {
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
}
ps = append(ps, p)
}
return ps, nil
}

View File

@ -0,0 +1,114 @@
package outboundgroup
import (
"context"
"encoding/json"
"fmt"
"github.com/Dreamacro/clash/adapter/outbound"
"github.com/Dreamacro/clash/common/singledo"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/constant/provider"
)
type Relay struct {
*outbound.Base
single *singledo.Single
providers []provider.ProxyProvider
}
// DialContext implements C.ProxyAdapter
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
var proxies []C.Proxy
for _, proxy := range r.proxies(metadata, true) {
if proxy.Type() != C.Direct {
proxies = append(proxies, proxy)
}
}
switch len(proxies) {
case 0:
return outbound.NewDirect().DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
case 1:
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
}
first := proxies[0]
last := proxies[len(proxies)-1]
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
}
tcpKeepAlive(c)
var currentMeta *C.Metadata
for _, proxy := range proxies[1:] {
currentMeta, err = addrToMetadata(proxy.Addr())
if err != nil {
return nil, err
}
c, err = first.StreamConn(c, currentMeta)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
}
first = proxy
}
c, err = last.StreamConn(c, metadata)
if err != nil {
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
}
return outbound.NewConn(c, r), nil
}
// MarshalJSON implements C.ProxyAdapter
func (r *Relay) MarshalJSON() ([]byte, error) {
var all []string
for _, proxy := range r.rawProxies(false) {
all = append(all, proxy.Name())
}
return json.Marshal(map[string]any{
"type": r.Type().String(),
"all": all,
})
}
func (r *Relay) rawProxies(touch bool) []C.Proxy {
elm, _, _ := r.single.Do(func() (any, error) {
return getProvidersProxies(r.providers, touch), nil
})
return elm.([]C.Proxy)
}
func (r *Relay) proxies(metadata *C.Metadata, touch bool) []C.Proxy {
proxies := r.rawProxies(touch)
for n, proxy := range proxies {
subproxy := proxy.Unwrap(metadata)
for subproxy != nil {
proxies[n] = subproxy
subproxy = subproxy.Unwrap(metadata)
}
}
return proxies
}
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
return &Relay{
Base: outbound.NewBase(outbound.BaseOption{
Name: option.Name,
Type: C.Relay,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
}),
single: singledo.NewSingle(defaultGetProxiesDuration),
providers: providers,
}
}

View File

@ -0,0 +1,114 @@
package outboundgroup
import (
"context"
"encoding/json"
"errors"
"github.com/Dreamacro/clash/adapter/outbound"
"github.com/Dreamacro/clash/common/singledo"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/constant/provider"
)
type Selector struct {
*outbound.Base
disableUDP bool
single *singledo.Single
selected string
providers []provider.ProxyProvider
}
// DialContext implements C.ProxyAdapter
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
c, err := s.selectedProxy(true).DialContext(ctx, metadata, s.Base.DialOptions(opts...)...)
if err == nil {
c.AppendToChains(s)
}
return c, err
}
// ListenPacketContext implements C.ProxyAdapter
func (s *Selector) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
pc, err := s.selectedProxy(true).ListenPacketContext(ctx, metadata, s.Base.DialOptions(opts...)...)
if err == nil {
pc.AppendToChains(s)
}
return pc, err
}
// SupportUDP implements C.ProxyAdapter
func (s *Selector) SupportUDP() bool {
if s.disableUDP {
return false
}
return s.selectedProxy(false).SupportUDP()
}
// MarshalJSON implements C.ProxyAdapter
func (s *Selector) MarshalJSON() ([]byte, error) {
var all []string
for _, proxy := range getProvidersProxies(s.providers, false) {
all = append(all, proxy.Name())
}
return json.Marshal(map[string]any{
"type": s.Type().String(),
"now": s.Now(),
"all": all,
})
}
func (s *Selector) Now() string {
return s.selectedProxy(false).Name()
}
func (s *Selector) Set(name string) error {
for _, proxy := range getProvidersProxies(s.providers, false) {
if proxy.Name() == name {
s.selected = name
s.single.Reset()
return nil
}
}
return errors.New("proxy not exist")
}
// Unwrap implements C.ProxyAdapter
func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
return s.selectedProxy(true)
}
func (s *Selector) selectedProxy(touch bool) C.Proxy {
elm, _, _ := s.single.Do(func() (any, error) {
proxies := getProvidersProxies(s.providers, touch)
for _, proxy := range proxies {
if proxy.Name() == s.selected {
return proxy, nil
}
}
return proxies[0], nil
})
return elm.(C.Proxy)
}
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
selected := providers[0].Proxies()[0].Name()
return &Selector{
Base: outbound.NewBase(outbound.BaseOption{
Name: option.Name,
Type: C.Selector,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
}),
single: singledo.NewSingle(defaultGetProxiesDuration),
providers: providers,
selected: selected,
disableUDP: option.DisableUDP,
}
}

View File

@ -0,0 +1,157 @@
package outboundgroup
import (
"context"
"encoding/json"
"time"
"github.com/Dreamacro/clash/adapter/outbound"
"github.com/Dreamacro/clash/common/singledo"
"github.com/Dreamacro/clash/component/dialer"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/constant/provider"
)
type urlTestOption func(*URLTest)
func urlTestWithTolerance(tolerance uint16) urlTestOption {
return func(u *URLTest) {
u.tolerance = tolerance
}
}
type URLTest struct {
*outbound.Base
tolerance uint16
disableUDP bool
fastNode C.Proxy
single *singledo.Single
fastSingle *singledo.Single
providers []provider.ProxyProvider
}
func (u *URLTest) Now() string {
return u.fast(false).Name()
}
// DialContext implements C.ProxyAdapter
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
if err == nil {
c.AppendToChains(u)
}
return c, err
}
// ListenPacketContext implements C.ProxyAdapter
func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
pc, err := u.fast(true).ListenPacketContext(ctx, metadata, u.Base.DialOptions(opts...)...)
if err == nil {
pc.AppendToChains(u)
}
return pc, err
}
// Unwrap implements C.ProxyAdapter
func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
return u.fast(true)
}
func (u *URLTest) proxies(touch bool) []C.Proxy {
elm, _, _ := u.single.Do(func() (any, error) {
return getProvidersProxies(u.providers, touch), nil
})
return elm.([]C.Proxy)
}
func (u *URLTest) fast(touch bool) C.Proxy {
elm, _, shared := u.fastSingle.Do(func() (any, error) {
proxies := u.proxies(touch)
fast := proxies[0]
min := fast.LastDelay()
fastNotExist := true
for _, proxy := range proxies[1:] {
if u.fastNode != nil && proxy.Name() == u.fastNode.Name() {
fastNotExist = false
}
if !proxy.Alive() {
continue
}
delay := proxy.LastDelay()
if delay < min {
fast = proxy
min = delay
}
}
// tolerance
if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
u.fastNode = fast
}
return u.fastNode, nil
})
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
touchProviders(u.providers)
}
return elm.(C.Proxy)
}
// SupportUDP implements C.ProxyAdapter
func (u *URLTest) SupportUDP() bool {
if u.disableUDP {
return false
}
return u.fast(false).SupportUDP()
}
// MarshalJSON implements C.ProxyAdapter
func (u *URLTest) MarshalJSON() ([]byte, error) {
var all []string
for _, proxy := range u.proxies(false) {
all = append(all, proxy.Name())
}
return json.Marshal(map[string]any{
"type": u.Type().String(),
"now": u.Now(),
"all": all,
})
}
func parseURLTestOption(config map[string]any) []urlTestOption {
opts := []urlTestOption{}
// tolerance
if tolerance, ok := config["tolerance"].(int); ok {
opts = append(opts, urlTestWithTolerance(uint16(tolerance)))
}
return opts
}
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
urlTest := &URLTest{
Base: outbound.NewBase(outbound.BaseOption{
Name: option.Name,
Type: C.URLTest,
Interface: option.Interface,
RoutingMark: option.RoutingMark,
}),
single: singledo.NewSingle(defaultGetProxiesDuration),
fastSingle: singledo.NewSingle(time.Second * 10),
providers: providers,
disableUDP: option.DisableUDP,
}
for _, option := range options {
option(urlTest)
}
return urlTest
}

View File

@ -0,0 +1,48 @@
package outboundgroup
import (
"fmt"
"net"
"time"
C "github.com/Dreamacro/clash/constant"
)
func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
host, port, err := net.SplitHostPort(rawAddress)
if err != nil {
err = fmt.Errorf("addrToMetadata failed: %w", err)
return
}
ip := net.ParseIP(host)
if ip == nil {
addr = &C.Metadata{
Host: host,
DstIP: nil,
DstPort: port,
}
return
} else if ip4 := ip.To4(); ip4 != nil {
addr = &C.Metadata{
Host: "",
DstIP: ip4,
DstPort: port,
}
return
}
addr = &C.Metadata{
Host: "",
DstIP: ip,
DstPort: port,
}
return
}
func tcpKeepAlive(c net.Conn) {
if tcp, ok := c.(*net.TCPConn); ok {
tcp.SetKeepAlive(true)
tcp.SetKeepAlivePeriod(30 * time.Second)
}
}

86
adapter/parser.go Normal file
View File

@ -0,0 +1,86 @@
package adapter
import (
"fmt"
"github.com/Dreamacro/clash/adapter/outbound"
"github.com/Dreamacro/clash/common/structure"
C "github.com/Dreamacro/clash/constant"
)
func ParseProxy(mapping map[string]any) (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 error
)
switch proxyType {
case "ss":
ssOption := &outbound.ShadowSocksOption{}
err = decoder.Decode(mapping, ssOption)
if err != nil {
break
}
proxy, err = outbound.NewShadowSocks(*ssOption)
case "ssr":
ssrOption := &outbound.ShadowSocksROption{}
err = decoder.Decode(mapping, ssrOption)
if err != nil {
break
}
proxy, err = outbound.NewShadowSocksR(*ssrOption)
case "socks5":
socksOption := &outbound.Socks5Option{}
err = decoder.Decode(mapping, socksOption)
if err != nil {
break
}
proxy = outbound.NewSocks5(*socksOption)
case "http":
httpOption := &outbound.HttpOption{}
err = decoder.Decode(mapping, httpOption)
if err != nil {
break
}
proxy = outbound.NewHttp(*httpOption)
case "vmess":
vmessOption := &outbound.VmessOption{
HTTPOpts: outbound.HTTPOptions{
Method: "GET",
Path: []string{"/"},
},
}
err = decoder.Decode(mapping, vmessOption)
if err != nil {
break
}
proxy, err = outbound.NewVmess(*vmessOption)
case "snell":
snellOption := &outbound.SnellOption{}
err = decoder.Decode(mapping, snellOption)
if err != nil {
break
}
proxy, err = outbound.NewSnell(*snellOption)
case "trojan":
trojanOption := &outbound.TrojanOption{}
err = decoder.Decode(mapping, trojanOption)
if err != nil {
break
}
proxy, err = outbound.NewTrojan(*trojanOption)
default:
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
}
if err != nil {
return nil, err
}
return NewProxy(proxy), nil
}

197
adapter/provider/fetcher.go Normal file
View File

@ -0,0 +1,197 @@
package provider
import (
"bytes"
"crypto/md5"
"os"
"path/filepath"
"time"
types "github.com/Dreamacro/clash/constant/provider"
"github.com/Dreamacro/clash/log"
)
var (
fileMode os.FileMode = 0o666
dirMode os.FileMode = 0o755
)
type parser = func([]byte) (any, error)
type fetcher struct {
name string
vehicle types.Vehicle
interval time.Duration
updatedAt *time.Time
ticker *time.Ticker
done chan struct{}
hash [16]byte
parser parser
onUpdate func(any)
}
func (f *fetcher) Name() string {
return f.name
}
func (f *fetcher) VehicleType() types.VehicleType {
return f.vehicle.Type()
}
func (f *fetcher) Initial() (any, error) {
var (
buf []byte
err error
isLocal bool
immediatelyUpdate bool
)
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
buf, err = os.ReadFile(f.vehicle.Path())
modTime := stat.ModTime()
f.updatedAt = &modTime
isLocal = true
immediatelyUpdate = time.Since(modTime) > f.interval
} else {
buf, err = f.vehicle.Read()
}
if err != nil {
return nil, err
}
proxies, err := f.parser(buf)
if err != nil {
if !isLocal {
return nil, err
}
// parse local file error, fallback to remote
buf, err = f.vehicle.Read()
if err != nil {
return nil, err
}
proxies, err = f.parser(buf)
if err != nil {
return nil, err
}
isLocal = false
}
if f.vehicle.Type() != types.File && !isLocal {
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
return nil, err
}
}
f.hash = md5.Sum(buf)
// pull proxies automatically
if f.ticker != nil {
go f.pullLoop(immediatelyUpdate)
}
return proxies, nil
}
func (f *fetcher) Update() (any, bool, error) {
buf, err := f.vehicle.Read()
if err != nil {
return nil, false, err
}
now := time.Now()
hash := md5.Sum(buf)
if bytes.Equal(f.hash[:], hash[:]) {
f.updatedAt = &now
os.Chtimes(f.vehicle.Path(), now, now)
return nil, true, nil
}
proxies, err := f.parser(buf)
if err != nil {
return nil, false, err
}
if f.vehicle.Type() != types.File {
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
return nil, false, err
}
}
f.updatedAt = &now
f.hash = hash
return proxies, false, nil
}
func (f *fetcher) Destroy() error {
if f.ticker != nil {
f.done <- struct{}{}
}
return nil
}
func (f *fetcher) pullLoop(immediately bool) {
update := func() {
elm, same, err := f.Update()
if err != nil {
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
return
}
if same {
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
return
}
log.Infoln("[Provider] %s's proxies update", f.Name())
if f.onUpdate != nil {
f.onUpdate(elm)
}
}
if immediately {
update()
}
for {
select {
case <-f.ticker.C:
update()
case <-f.done:
f.ticker.Stop()
return
}
}
}
func safeWrite(path string, buf []byte) error {
dir := filepath.Dir(path)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, dirMode); err != nil {
return err
}
}
return os.WriteFile(path, buf, fileMode)
}
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(any)) *fetcher {
var ticker *time.Ticker
if interval != 0 {
ticker = time.NewTicker(interval)
}
return &fetcher{
name: name,
ticker: ticker,
vehicle: vehicle,
interval: interval,
parser: parser,
done: make(chan struct{}, 1),
onUpdate: onUpdate,
}
}

View File

@ -0,0 +1,100 @@
package provider
import (
"context"
"time"
"github.com/Dreamacro/clash/common/batch"
C "github.com/Dreamacro/clash/constant"
"github.com/samber/lo"
"go.uber.org/atomic"
)
const (
defaultURLTestTimeout = time.Second * 5
)
type HealthCheckOption struct {
URL string
Interval uint
}
type HealthCheck struct {
url string
proxies []C.Proxy
interval uint
lazy bool
lastTouch *atomic.Int64
done chan struct{}
}
func (hc *HealthCheck) process() {
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
go hc.checkAll()
for {
select {
case <-ticker.C:
now := time.Now().Unix()
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
hc.checkAll()
} else { // lazy but still need to check not alive proxies
notAliveProxies := lo.Filter(hc.proxies, func(proxy C.Proxy, _ int) bool {
return !proxy.Alive()
})
if len(notAliveProxies) != 0 {
hc.check(notAliveProxies)
}
}
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) touch() {
hc.lastTouch.Store(time.Now().Unix())
}
func (hc *HealthCheck) checkAll() {
hc.check(hc.proxies)
}
func (hc *HealthCheck) check(proxies []C.Proxy) {
b, _ := batch.New(context.Background(), batch.WithConcurrencyNum(10))
for _, proxy := range proxies {
p := proxy
b.Go(p.Name(), func() (any, error) {
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
defer cancel()
p.URLTest(ctx, hc.url)
return nil, nil
})
}
b.Wait()
}
func (hc *HealthCheck) close() {
hc.done <- struct{}{}
}
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool) *HealthCheck {
return &HealthCheck{
proxies: proxies,
url: url,
interval: interval,
lazy: lazy,
lastTouch: atomic.NewInt64(0),
done: make(chan struct{}, 1),
}
}

View File

@ -0,0 +1,70 @@
package provider
import (
"errors"
"fmt"
"time"
"github.com/Dreamacro/clash/common/structure"
C "github.com/Dreamacro/clash/constant"
types "github.com/Dreamacro/clash/constant/provider"
)
var (
errVehicleType = errors.New("unsupport vehicle type")
errSubPath = errors.New("path is not subpath of home directory")
)
type healthCheckSchema struct {
Enable bool `provider:"enable"`
URL string `provider:"url"`
Interval int `provider:"interval"`
Lazy bool `provider:"lazy,omitempty"`
}
type proxyProviderSchema struct {
Type string `provider:"type"`
Path string `provider:"path"`
URL string `provider:"url,omitempty"`
Interval int `provider:"interval,omitempty"`
Filter string `provider:"filter,omitempty"`
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
}
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
schema := &proxyProviderSchema{
HealthCheck: healthCheckSchema{
Lazy: true,
},
}
if err := decoder.Decode(mapping, schema); err != nil {
return nil, err
}
var hcInterval uint
if schema.HealthCheck.Enable {
hcInterval = uint(schema.HealthCheck.Interval)
}
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy)
path := C.Path.Resolve(schema.Path)
var vehicle types.Vehicle
switch schema.Type {
case "file":
vehicle = NewFileVehicle(path)
case "http":
if !C.Path.IsSubPath(path) {
return nil, fmt.Errorf("%w: %s", errSubPath, path)
}
vehicle = NewHTTPVehicle(schema.URL, path)
default:
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
}
interval := time.Duration(uint(schema.Interval)) * time.Second
filter := schema.Filter
return NewProxySetProvider(name, interval, filter, vehicle, hc)
}

View File

@ -0,0 +1,322 @@
package provider
import (
"encoding/json"
"errors"
"fmt"
"runtime"
"time"
"github.com/Dreamacro/clash/adapter"
"github.com/Dreamacro/clash/adapter/outbound"
"github.com/Dreamacro/clash/common/singledo"
C "github.com/Dreamacro/clash/constant"
types "github.com/Dreamacro/clash/constant/provider"
regexp "github.com/dlclark/regexp2"
"github.com/samber/lo"
"gopkg.in/yaml.v3"
)
var reject = adapter.NewProxy(outbound.NewReject())
const (
ReservedName = "default"
)
type ProxySchema struct {
Proxies []map[string]any `yaml:"proxies"`
}
// for auto gc
type ProxySetProvider struct {
*proxySetProvider
}
type proxySetProvider struct {
*fetcher
proxies []C.Proxy
healthCheck *HealthCheck
}
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{
"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) HealthCheck() {
pp.healthCheck.checkAll()
}
func (pp *proxySetProvider) Update() error {
elm, same, err := pp.fetcher.Update()
if err == nil && !same {
pp.onUpdate(elm)
}
return err
}
func (pp *proxySetProvider) Initial() error {
elm, err := pp.fetcher.Initial()
if err != nil {
return err
}
pp.onUpdate(elm)
return nil
}
func (pp *proxySetProvider) Type() types.ProviderType {
return types.Proxy
}
func (pp *proxySetProvider) Proxies() []C.Proxy {
return pp.proxies
}
func (pp *proxySetProvider) Touch() {
pp.healthCheck.touch()
}
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
pp.proxies = proxies
pp.healthCheck.setProxy(proxies)
if pp.healthCheck.auto() {
go pp.healthCheck.checkAll()
}
}
func stopProxyProvider(pd *ProxySetProvider) {
pd.healthCheck.close()
pd.fetcher.Destroy()
}
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
filterReg, err := regexp.Compile(filter, regexp.None)
if err != nil {
return nil, fmt.Errorf("invalid filter regex: %w", err)
}
if hc.auto() {
go hc.process()
}
pd := &proxySetProvider{
proxies: []C.Proxy{},
healthCheck: hc,
}
onUpdate := func(elm any) {
ret := elm.([]C.Proxy)
pd.setProxies(ret)
}
proxiesParseAndFilter := func(buf []byte) (any, 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 {
if name, ok := mapping["name"].(string); ok && len(filter) > 0 {
matched, err := filterReg.MatchString(name)
if err != nil {
return nil, fmt.Errorf("regex filter failed: %w", err)
}
if !matched {
continue
}
}
proxy, err := adapter.ParseProxy(mapping)
if err != nil {
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
}
proxies = append(proxies, proxy)
}
if len(proxies) == 0 {
if len(filter) > 0 {
return nil, errors.New("doesn't match any proxy, please check your filter")
}
return nil, errors.New("file doesn't have any proxy")
}
return proxies, nil
}
fetcher := newFetcher(name, interval, vehicle, proxiesParseAndFilter, onUpdate)
pd.fetcher = fetcher
wrapper := &ProxySetProvider{pd}
runtime.SetFinalizer(wrapper, stopProxyProvider)
return wrapper, nil
}
// for auto gc
type CompatibleProvider struct {
*compatibleProvider
}
type compatibleProvider struct {
name string
healthCheck *HealthCheck
proxies []C.Proxy
}
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{
"name": cp.Name(),
"type": cp.Type().String(),
"vehicleType": cp.VehicleType().String(),
"proxies": cp.Proxies(),
})
}
func (cp *compatibleProvider) Name() string {
return cp.name
}
func (cp *compatibleProvider) HealthCheck() {
cp.healthCheck.checkAll()
}
func (cp *compatibleProvider) Update() error {
return nil
}
func (cp *compatibleProvider) Initial() error {
return nil
}
func (cp *compatibleProvider) VehicleType() types.VehicleType {
return types.Compatible
}
func (cp *compatibleProvider) Type() types.ProviderType {
return types.Proxy
}
func (cp *compatibleProvider) Proxies() []C.Proxy {
return cp.proxies
}
func (cp *compatibleProvider) Touch() {
cp.healthCheck.touch()
}
func stopCompatibleProvider(pd *CompatibleProvider) {
pd.healthCheck.close()
}
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
if len(proxies) == 0 {
return nil, errors.New("provider need one proxy at least")
}
if hc.auto() {
go hc.process()
}
pd := &compatibleProvider{
name: name,
proxies: proxies,
healthCheck: hc,
}
wrapper := &CompatibleProvider{pd}
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
return wrapper, nil
}
var _ types.ProxyProvider = (*FilterableProvider)(nil)
type FilterableProvider struct {
name string
providers []types.ProxyProvider
filterReg *regexp.Regexp
single *singledo.Single
}
func (fp *FilterableProvider) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{
"name": fp.Name(),
"type": fp.Type().String(),
"vehicleType": fp.VehicleType().String(),
"proxies": fp.Proxies(),
})
}
func (fp *FilterableProvider) Name() string {
return fp.name
}
func (fp *FilterableProvider) HealthCheck() {
}
func (fp *FilterableProvider) Update() error {
return nil
}
func (fp *FilterableProvider) Initial() error {
return nil
}
func (fp *FilterableProvider) VehicleType() types.VehicleType {
return types.Compatible
}
func (fp *FilterableProvider) Type() types.ProviderType {
return types.Proxy
}
func (fp *FilterableProvider) Proxies() []C.Proxy {
elm, _, _ := fp.single.Do(func() (any, error) {
proxies := lo.FlatMap(
fp.providers,
func(item types.ProxyProvider, _ int) []C.Proxy {
return lo.Filter(
item.Proxies(),
func(item C.Proxy, _ int) bool {
matched, _ := fp.filterReg.MatchString(item.Name())
return matched
})
})
if len(proxies) == 0 {
proxies = append(proxies, reject)
}
return proxies, nil
})
return elm.([]C.Proxy)
}
func (fp *FilterableProvider) Touch() {
for _, provider := range fp.providers {
provider.Touch()
}
}
func NewFilterableProvider(name string, providers []types.ProxyProvider, filterReg *regexp.Regexp) *FilterableProvider {
return &FilterableProvider{
name: name,
providers: providers,
filterReg: filterReg,
single: singledo.NewSingle(time.Second * 10),
}
}

View File

@ -0,0 +1,98 @@
package provider
import (
"context"
"io"
"net"
"net/http"
"net/url"
"os"
"time"
"github.com/Dreamacro/clash/component/dialer"
types "github.com/Dreamacro/clash/constant/provider"
)
type FileVehicle struct {
path string
}
func (f *FileVehicle) Type() types.VehicleType {
return types.File
}
func (f *FileVehicle) Path() string {
return f.path
}
func (f *FileVehicle) Read() ([]byte, error) {
return os.ReadFile(f.path)
}
func NewFileVehicle(path string) *FileVehicle {
return &FileVehicle{path: path}
}
type HTTPVehicle struct {
url string
path string
}
func (h *HTTPVehicle) Type() types.VehicleType {
return types.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()
uri, err := url.Parse(h.url)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
if err != nil {
return nil, err
}
if user := uri.User; user != nil {
password, _ := user.Password()
req.SetBasicAuth(user.Username(), password)
}
req = req.WithContext(ctx)
transport := &http.Transport{
// from http.DefaultTransport
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return dialer.DialContext(ctx, network, address)
},
}
client := http.Client{Transport: transport}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
buf, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return buf, nil
}
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
return &HTTPVehicle{url, path}
}

View File

@ -1,64 +0,0 @@
package adapters
import (
"net"
"net/http"
"strings"
C "github.com/Dreamacro/clash/constant"
)
// HTTPAdapter is a adapter for HTTP connection
type HTTPAdapter struct {
metadata *C.Metadata
conn net.Conn
R *http.Request
}
// Close HTTP connection
func (h *HTTPAdapter) Close() {
h.conn.Close()
}
// Metadata return destination metadata
func (h *HTTPAdapter) Metadata() *C.Metadata {
return h.metadata
}
// Conn return raw net.Conn of HTTP
func (h *HTTPAdapter) Conn() net.Conn {
return h.conn
}
// NewHTTP is HTTPAdapter generator
func NewHTTP(request *http.Request, conn net.Conn) *HTTPAdapter {
return &HTTPAdapter{
metadata: parseHTTPAddr(request),
R: request,
conn: conn,
}
}
// RemoveHopByHopHeaders remove hop-by-hop header
func RemoveHopByHopHeaders(header http.Header) {
// Strip hop-by-hop header based on RFC:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
// https://www.mnot.net/blog/2011/07/11/what_proxies_must_do
header.Del("Proxy-Connection")
header.Del("Proxy-Authenticate")
header.Del("Proxy-Authorization")
header.Del("TE")
header.Del("Trailers")
header.Del("Transfer-Encoding")
header.Del("Upgrade")
connections := header.Get("Connection")
header.Del("Connection")
if len(connections) == 0 {
return
}
for _, h := range strings.Split(connections, ",") {
header.Del(strings.TrimSpace(h))
}
}

View File

@ -1,14 +0,0 @@
package adapters
import (
"net"
"net/http"
)
// NewHTTPS is HTTPAdapter generator
func NewHTTPS(request *http.Request, conn net.Conn) *SocketAdapter {
return &SocketAdapter{
metadata: parseHTTPAddr(request),
conn: conn,
}
}

View File

@ -1,37 +0,0 @@
package adapters
import (
"net"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/go-shadowsocks2/socks"
)
// SocketAdapter is a adapter for socks and redir connection
type SocketAdapter struct {
conn net.Conn
metadata *C.Metadata
}
// Close socks and redir connection
func (s *SocketAdapter) Close() {
s.conn.Close()
}
// Metadata return destination metadata
func (s *SocketAdapter) Metadata() *C.Metadata {
return s.metadata
}
// Conn return raw net.Conn
func (s *SocketAdapter) Conn() net.Conn {
return s.conn
}
// NewSocket is SocketAdapter generator
func NewSocket(target socks.Addr, conn net.Conn) *SocketAdapter {
return &SocketAdapter{
conn: conn,
metadata: parseSocksAddr(target),
}
}

View File

@ -1,71 +0,0 @@
package adapters
import (
"net"
"net/http"
"strconv"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/go-shadowsocks2/socks"
)
func parseSocksAddr(target socks.Addr) *C.Metadata {
var host, port string
var ip net.IP
switch target[0] {
case socks.AtypDomainName:
host = string(target[2 : 2+target[1]])
port = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
ipAddr, err := net.ResolveIPAddr("ip", host)
if err == nil {
ip = ipAddr.IP
}
case socks.AtypIPv4:
ip = net.IP(target[1 : 1+net.IPv4len])
port = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
case socks.AtypIPv6:
ip = net.IP(target[1 : 1+net.IPv6len])
port = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
}
return &C.Metadata{
NetWork: C.TCP,
AddrType: int(target[0]),
Host: host,
IP: &ip,
Port: port,
}
}
func parseHTTPAddr(request *http.Request) *C.Metadata {
host := request.URL.Hostname()
port := request.URL.Port()
if port == "" {
port = "80"
}
ipAddr, err := net.ResolveIPAddr("ip", host)
var resolveIP *net.IP
if err == nil {
resolveIP = &ipAddr.IP
}
var addType int
ip := net.ParseIP(host)
switch {
case ip == nil:
addType = socks.AtypDomainName
case ip.To4() == nil:
addType = socks.AtypIPv6
default:
addType = socks.AtypIPv4
}
return &C.Metadata{
NetWork: C.TCP,
AddrType: addType,
Host: host,
IP: resolveIP,
Port: port,
}
}

View File

@ -1,45 +0,0 @@
package adapters
import (
"net"
C "github.com/Dreamacro/clash/constant"
)
// DirectAdapter is a directly connected adapter
type DirectAdapter struct {
conn net.Conn
}
// Close is used to close connection
func (d *DirectAdapter) Close() {
d.conn.Close()
}
// Conn is used to http request
func (d *DirectAdapter) Conn() net.Conn {
return d.conn
}
type Direct struct{}
func (d *Direct) Name() string {
return "DIRECT"
}
func (d *Direct) Type() C.AdapterType {
return C.Direct
}
func (d *Direct) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
c, err := net.DialTimeout("tcp", net.JoinHostPort(metadata.String(), metadata.Port), tcpTimeout)
if err != nil {
return
}
tcpKeepAlive(c)
return &DirectAdapter{conn: c}, nil
}
func NewDirect() *Direct {
return &Direct{}
}

View File

@ -1,136 +0,0 @@
package adapters
import (
"errors"
"sync"
"time"
C "github.com/Dreamacro/clash/constant"
)
type proxy struct {
RawProxy C.Proxy
Valid bool
}
type Fallback struct {
name string
proxies []*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) Name() string {
return f.name
}
func (f *Fallback) Type() C.AdapterType {
return C.Fallback
}
func (f *Fallback) Now() string {
_, proxy := f.findNextValidProxy(0)
if proxy != nil {
return proxy.RawProxy.Name()
}
return f.proxies[0].RawProxy.Name()
}
func (f *Fallback) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
idx := 0
var proxy *proxy
for {
idx, proxy = f.findNextValidProxy(idx)
if proxy == nil {
break
}
adapter, err = proxy.RawProxy.Generator(metadata)
if err != nil {
proxy.Valid = false
idx++
continue
}
return
}
return f.proxies[0].RawProxy.Generator(metadata)
}
func (f *Fallback) Close() {
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) findNextValidProxy(start int) (int, *proxy) {
for i := start; i < len(f.proxies); i++ {
if f.proxies[i].Valid {
return i, f.proxies[i]
}
}
return -1, nil
}
func (f *Fallback) validTest() {
wg := sync.WaitGroup{}
wg.Add(len(f.proxies))
for _, p := range f.proxies {
go func(p *proxy) {
_, err := DelayTest(p.RawProxy, f.rawURL)
p.Valid = err == nil
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
warpperProxies := make([]*proxy, len(proxies))
for idx := range proxies {
warpperProxies[idx] = &proxy{
RawProxy: proxies[idx],
Valid: true,
}
}
Fallback := &Fallback{
name: option.Name,
proxies: warpperProxies,
rawURL: option.URL,
interval: interval,
done: make(chan struct{}),
}
go Fallback.loop()
return Fallback, nil
}

View File

@ -1,69 +0,0 @@
package adapters
import (
"io"
"net"
"time"
C "github.com/Dreamacro/clash/constant"
)
// RejectAdapter is a reject connected adapter
type RejectAdapter struct {
conn net.Conn
}
// Close is used to close connection
func (r *RejectAdapter) Close() {}
// Conn is used to http request
func (r *RejectAdapter) Conn() net.Conn {
return r.conn
}
type Reject struct {
}
func (r *Reject) Name() string {
return "REJECT"
}
func (r *Reject) Type() C.AdapterType {
return C.Reject
}
func (r *Reject) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
return &RejectAdapter{conn: &NopConn{}}, nil
}
func NewReject() *Reject {
return &Reject{}
}
type NopConn struct{}
func (rw *NopConn) Read(b []byte) (int, error) {
return len(b), nil
}
func (rw *NopConn) Write(b []byte) (int, error) {
return 0, io.EOF
}
// Close is fake function for net.Conn
func (rw *NopConn) Close() error { return nil }
// LocalAddr is fake function for net.Conn
func (rw *NopConn) LocalAddr() net.Addr { return nil }
// RemoteAddr is fake function for net.Conn
func (rw *NopConn) RemoteAddr() net.Addr { return nil }
// SetDeadline is fake function for net.Conn
func (rw *NopConn) SetDeadline(time.Time) error { return nil }
// SetReadDeadline is fake function for net.Conn
func (rw *NopConn) SetReadDeadline(time.Time) error { return nil }
// SetWriteDeadline is fake function for net.Conn
func (rw *NopConn) SetWriteDeadline(time.Time) error { return nil }

View File

@ -1,71 +0,0 @@
package adapters
import (
"errors"
"sort"
C "github.com/Dreamacro/clash/constant"
)
type Selector struct {
name string
selected C.Proxy
proxies map[string]C.Proxy
}
type SelectorOption struct {
Name string `proxy:"name"`
Proxies []string `proxy:"proxies"`
}
func (s *Selector) Name() string {
return s.name
}
func (s *Selector) Type() C.AdapterType {
return C.Selector
}
func (s *Selector) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
return s.selected.Generator(metadata)
}
func (s *Selector) Now() string {
return s.selected.Name()
}
func (s *Selector) All() []string {
var all []string
for k := range s.proxies {
all = append(all, k)
}
sort.Strings(all)
return all
}
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)
for _, proxy := range proxies {
mapping[proxy.Name()] = proxy
}
s := &Selector{
name: name,
proxies: mapping,
selected: proxies[0],
}
return s, nil
}

View File

@ -1,116 +0,0 @@
package adapters
import (
"bytes"
"fmt"
"net"
"strconv"
"github.com/Dreamacro/clash/component/simple-obfs"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/go-shadowsocks2/core"
"github.com/Dreamacro/go-shadowsocks2/socks"
)
// ShadowsocksAdapter is a shadowsocks adapter
type ShadowsocksAdapter struct {
conn net.Conn
}
// Close is used to close connection
func (ss *ShadowsocksAdapter) Close() {
ss.conn.Close()
}
func (ss *ShadowsocksAdapter) Conn() net.Conn {
return ss.conn
}
type ShadowSocks struct {
server string
name string
obfs string
obfsHost string
cipher core.Cipher
}
type ShadowSocksOption struct {
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
Password string `proxy:"password"`
Cipher string `proxy:"cipher"`
Obfs string `proxy:"obfs,omitempty"`
ObfsHost string `proxy:"obfs-host,omitempty"`
}
func (ss *ShadowSocks) Name() string {
return ss.name
}
func (ss *ShadowSocks) Type() C.AdapterType {
return C.Shadowsocks
}
func (ss *ShadowSocks) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
c, err := net.DialTimeout("tcp", ss.server, tcpTimeout)
if err != nil {
return nil, fmt.Errorf("%s connect error", ss.server)
}
tcpKeepAlive(c)
switch ss.obfs {
case "tls":
c = obfs.NewTLSObfs(c, ss.obfsHost)
case "http":
_, port, _ := net.SplitHostPort(ss.server)
c = obfs.NewHTTPObfs(c, ss.obfsHost, port)
}
c = ss.cipher.StreamConn(c)
_, err = c.Write(serializesSocksAddr(metadata))
return &ShadowsocksAdapter{conn: c}, err
}
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
server := fmt.Sprintf("%s:%d", option.Server, option.Port)
cipher := option.Cipher
password := option.Password
ciph, err := core.PickCipher(cipher, nil, password)
if err != nil {
return nil, fmt.Errorf("ss %s initialize error: %s", server, err.Error())
}
obfs := option.Obfs
obfsHost := "bing.com"
if option.ObfsHost != "" {
obfsHost = option.ObfsHost
}
return &ShadowSocks{
server: server,
name: option.Name,
cipher: ciph,
obfs: obfs,
obfsHost: obfsHost,
}, nil
}
func serializesSocksAddr(metadata *C.Metadata) []byte {
var buf [][]byte
aType := uint8(metadata.AddrType)
p, _ := strconv.Atoi(metadata.Port)
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
switch metadata.AddrType {
case socks.AtypDomainName:
len := uint8(len(metadata.Host))
host := []byte(metadata.Host)
buf = [][]byte{{aType, len}, host, port}
case socks.AtypIPv4:
host := metadata.IP.To4()
buf = [][]byte{{aType}, host, port}
case socks.AtypIPv6:
host := metadata.IP.To16()
buf = [][]byte{{aType}, host, port}
}
return bytes.Join(buf, nil)
}

View File

@ -1,112 +0,0 @@
package adapters
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/go-shadowsocks2/socks"
)
// Socks5Adapter is a shadowsocks adapter
type Socks5Adapter struct {
conn net.Conn
}
// Close is used to close connection
func (ss *Socks5Adapter) Close() {
ss.conn.Close()
}
func (ss *Socks5Adapter) Conn() net.Conn {
return ss.conn
}
type Socks5 struct {
addr string
name string
tls bool
skipCertVerify bool
}
type Socks5Option struct {
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
TLS bool `proxy:"tls,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
}
func (ss *Socks5) Name() string {
return ss.name
}
func (ss *Socks5) Type() C.AdapterType {
return C.Socks5
}
func (ss *Socks5) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
c, err := net.DialTimeout("tcp", ss.addr, tcpTimeout)
if err == nil && ss.tls {
tlsConfig := tls.Config{
InsecureSkipVerify: ss.skipCertVerify,
MaxVersion: tls.VersionTLS12,
}
c = tls.Client(c, &tlsConfig)
}
if err != nil {
return nil, fmt.Errorf("%s connect error", ss.addr)
}
tcpKeepAlive(c)
if err := ss.shakeHand(metadata, c); err != nil {
return nil, err
}
return &Socks5Adapter{conn: c}, nil
}
func (ss *Socks5) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
buf := make([]byte, socks.MaxAddrLen)
// VER, CMD, RSV
_, err := rw.Write([]byte{5, 1, 0})
if err != nil {
return err
}
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
return err
}
if buf[0] != 5 {
return errors.New("SOCKS version error")
} else if buf[1] != 0 {
return errors.New("SOCKS need auth")
}
// VER, CMD, RSV, ADDR
if _, err := rw.Write(bytes.Join([][]byte{{5, 1, 0}, serializesSocksAddr(metadata)}, []byte(""))); err != nil {
return err
}
if _, err := io.ReadFull(rw, buf[:10]); err != nil {
return err
}
return nil
}
func NewSocks5(option Socks5Option) *Socks5 {
return &Socks5{
addr: fmt.Sprintf("%s:%d", option.Server, option.Port),
name: option.Name,
tls: option.TLS,
skipCertVerify: option.SkipCertVerify,
}
}

View File

@ -1,126 +0,0 @@
package adapters
import (
"errors"
"sync"
"sync/atomic"
"time"
C "github.com/Dreamacro/clash/constant"
)
type URLTest struct {
name string
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) Name() string {
return u.name
}
func (u *URLTest) Type() C.AdapterType {
return C.URLTest
}
func (u *URLTest) Now() string {
return u.fast.Name()
}
func (u *URLTest) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
a, err := u.fast.Generator(metadata)
if err != nil {
go u.speedTest()
}
return a, err
}
func (u *URLTest) Close() {
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) speedTest() {
if atomic.AddInt32(&u.once, 1) != 1 {
return
}
defer atomic.StoreInt32(&u.once, 0)
wg := sync.WaitGroup{}
wg.Add(len(u.proxies))
c := make(chan interface{})
fast := selectFast(c)
timer := time.NewTimer(u.interval)
for _, p := range u.proxies {
go func(p C.Proxy) {
_, err := DelayTest(p, u.rawURL)
if err == nil {
c <- p
}
wg.Done()
}(p)
}
go func() {
wg.Wait()
close(c)
}()
select {
case <-timer.C:
// Wait for fast to return or close.
<-fast
case p, open := <-fast:
if open {
u.fast = p.(C.Proxy)
}
}
}
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{
name: option.Name,
proxies: proxies[:],
rawURL: option.URL,
fast: proxies[0],
interval: interval,
done: make(chan struct{}),
once: 0,
}
go urlTest.loop()
return urlTest, nil
}

View File

@ -1,97 +0,0 @@
package adapters
import (
"fmt"
"net"
"net/http"
"net/url"
"time"
C "github.com/Dreamacro/clash/constant"
)
const (
tcpTimeout = 5 * time.Second
)
// DelayTest get the delay for the specified URL
func DelayTest(proxy C.Proxy, url string) (t int16, err error) {
addr, err := urlToMetadata(url)
if err != nil {
return
}
start := time.Now()
instance, err := proxy.Generator(&addr)
if err != nil {
return
}
defer instance.Close()
transport := &http.Transport{
Dial: func(string, string) (net.Conn, error) {
return instance.Conn(), nil
},
// 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.Get(url)
if err != nil {
return
}
resp.Body.Close()
t = int16(time.Since(start) / time.Millisecond)
return
}
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
u, err := url.Parse(rawURL)
if err != nil {
return
}
port := u.Port()
if port == "" {
if u.Scheme == "https" {
port = "443"
} else if u.Scheme == "http" {
port = "80"
} else {
err = fmt.Errorf("%s scheme not Support", rawURL)
return
}
}
addr = C.Metadata{
AddrType: C.AtypDomainName,
Host: u.Hostname(),
IP: nil,
Port: port,
}
return
}
func selectFast(in chan interface{}) chan interface{} {
out := make(chan interface{})
go func() {
p, open := <-in
if open {
out <- p
}
close(out)
for range in {
}
}()
return out
}
func tcpKeepAlive(c net.Conn) {
if tcp, ok := c.(*net.TCPConn); ok {
tcp.SetKeepAlive(true)
tcp.SetKeepAlivePeriod(30 * time.Second)
}
}

View File

@ -1,112 +0,0 @@
package adapters
import (
"fmt"
"net"
"strconv"
"strings"
"github.com/Dreamacro/clash/component/vmess"
C "github.com/Dreamacro/clash/constant"
)
// VmessAdapter is a vmess adapter
type VmessAdapter struct {
conn net.Conn
}
// Close is used to close connection
func (v *VmessAdapter) Close() {
v.conn.Close()
}
func (v *VmessAdapter) Conn() net.Conn {
return v.conn
}
type Vmess struct {
name string
server string
client *vmess.Client
}
type VmessOption struct {
Name string `proxy:"name"`
Server string `proxy:"server"`
Port int `proxy:"port"`
UUID string `proxy:"uuid"`
AlterID int `proxy:"alterId"`
Cipher string `proxy:"cipher"`
TLS bool `proxy:"tls,omitempty"`
Network string `proxy:"network,omitempty"`
WSPath string `proxy:"ws-path,omitempty"`
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
}
func (ss *Vmess) Name() string {
return ss.name
}
func (ss *Vmess) Type() C.AdapterType {
return C.Vmess
}
func (ss *Vmess) Generator(metadata *C.Metadata) (adapter C.ProxyAdapter, err error) {
c, err := net.DialTimeout("tcp", ss.server, tcpTimeout)
if err != nil {
return nil, fmt.Errorf("%s connect error", ss.server)
}
tcpKeepAlive(c)
c, err = ss.client.New(c, parseVmessAddr(metadata))
return &VmessAdapter{conn: c}, err
}
func NewVmess(option VmessOption) (*Vmess, error) {
security := strings.ToLower(option.Cipher)
client, err := vmess.NewClient(vmess.Config{
UUID: option.UUID,
AlterID: uint16(option.AlterID),
Security: security,
TLS: option.TLS,
Host: fmt.Sprintf("%s:%d", option.Server, option.Port),
NetWork: option.Network,
WebSocketPath: option.WSPath,
SkipCertVerify: option.SkipCertVerify,
})
if err != nil {
return nil, err
}
return &Vmess{
name: option.Name,
server: fmt.Sprintf("%s:%d", option.Server, option.Port),
client: client,
}, nil
}
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
var addrType byte
var addr []byte
switch metadata.AddrType {
case C.AtypIPv4:
addrType = byte(vmess.AtypIPv4)
addr = make([]byte, net.IPv4len)
copy(addr[:], metadata.IP.To4())
case C.AtypIPv6:
addrType = byte(vmess.AtypIPv6)
addr = make([]byte, net.IPv6len)
copy(addr[:], metadata.IP.To16())
case C.AtypDomainName:
addrType = byte(vmess.AtypDomainName)
addr = make([]byte, len(metadata.Host)+1)
addr[0] = byte(len(metadata.Host))
copy(addr[1:], []byte(metadata.Host))
}
port, _ := strconv.Atoi(metadata.Port)
return &vmess.DstAddr{
AddrType: addrType,
Addr: addr,
Port: uint(port),
}
}

105
common/batch/batch.go Normal file
View File

@ -0,0 +1,105 @@
package batch
import (
"context"
"sync"
)
type Option = func(b *Batch)
type Result struct {
Value any
Err error
}
type Error struct {
Key string
Err error
}
func WithConcurrencyNum(n int) Option {
return func(b *Batch) {
q := make(chan struct{}, n)
for i := 0; i < n; i++ {
q <- struct{}{}
}
b.queue = q
}
}
// Batch similar to errgroup, but can control the maximum number of concurrent
type Batch struct {
result map[string]Result
queue chan struct{}
wg sync.WaitGroup
mux sync.Mutex
err *Error
once sync.Once
cancel func()
}
func (b *Batch) Go(key string, fn func() (any, error)) {
b.wg.Add(1)
go func() {
defer b.wg.Done()
if b.queue != nil {
<-b.queue
defer func() {
b.queue <- struct{}{}
}()
}
value, err := fn()
if err != nil {
b.once.Do(func() {
b.err = &Error{key, err}
if b.cancel != nil {
b.cancel()
}
})
}
ret := Result{value, err}
b.mux.Lock()
defer b.mux.Unlock()
b.result[key] = ret
}()
}
func (b *Batch) Wait() *Error {
b.wg.Wait()
if b.cancel != nil {
b.cancel()
}
return b.err
}
func (b *Batch) WaitAndGetResult() (map[string]Result, *Error) {
err := b.Wait()
return b.Result(), err
}
func (b *Batch) Result() map[string]Result {
b.mux.Lock()
defer b.mux.Unlock()
copy := map[string]Result{}
for k, v := range b.result {
copy[k] = v
}
return copy
}
func New(ctx context.Context, opts ...Option) (*Batch, context.Context) {
ctx, cancel := context.WithCancel(ctx)
b := &Batch{
result: map[string]Result{},
}
for _, o := range opts {
o(b)
}
b.cancel = cancel
return b, ctx
}

View File

@ -0,0 +1,83 @@
package batch
import (
"context"
"errors"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestBatch(t *testing.T) {
b, _ := New(context.Background())
now := time.Now()
b.Go("foo", func() (any, error) {
time.Sleep(time.Millisecond * 100)
return "foo", nil
})
b.Go("bar", func() (any, error) {
time.Sleep(time.Millisecond * 150)
return "bar", nil
})
result, err := b.WaitAndGetResult()
assert.Nil(t, err)
duration := time.Since(now)
assert.Less(t, duration, time.Millisecond*200)
assert.Equal(t, 2, len(result))
for k, v := range result {
assert.NoError(t, v.Err)
assert.Equal(t, k, v.Value.(string))
}
}
func TestBatchWithConcurrencyNum(t *testing.T) {
b, _ := New(
context.Background(),
WithConcurrencyNum(3),
)
now := time.Now()
for i := 0; i < 7; i++ {
idx := i
b.Go(strconv.Itoa(idx), func() (any, error) {
time.Sleep(time.Millisecond * 100)
return strconv.Itoa(idx), nil
})
}
result, _ := b.WaitAndGetResult()
duration := time.Since(now)
assert.Greater(t, duration, time.Millisecond*260)
assert.Equal(t, 7, len(result))
for k, v := range result {
assert.NoError(t, v.Err)
assert.Equal(t, k, v.Value.(string))
}
}
func TestBatchContext(t *testing.T) {
b, ctx := New(context.Background())
b.Go("error", func() (any, error) {
time.Sleep(time.Millisecond * 100)
return nil, errors.New("test error")
})
b.Go("ctx", func() (any, error) {
<-ctx.Done()
return nil, ctx.Err()
})
result, err := b.WaitAndGetResult()
assert.NotNil(t, err)
assert.Equal(t, "error", err.Key)
assert.Equal(t, ctx.Err(), result["ctx"].Err)
}

223
common/cache/lrucache.go vendored Normal file
View File

@ -0,0 +1,223 @@
package cache
// Modified by https://github.com/die-net/lrucache
import (
"container/list"
"sync"
"time"
)
// Option is part of Functional Options Pattern
type Option func(*LruCache)
// EvictCallback is used to get a callback when a cache entry is evicted
type EvictCallback = func(key any, value any)
// WithEvict set the evict callback
func WithEvict(cb EvictCallback) Option {
return func(l *LruCache) {
l.onEvict = cb
}
}
// WithUpdateAgeOnGet update expires when Get element
func WithUpdateAgeOnGet() Option {
return func(l *LruCache) {
l.updateAgeOnGet = true
}
}
// WithAge defined element max age (second)
func WithAge(maxAge int64) Option {
return func(l *LruCache) {
l.maxAge = maxAge
}
}
// WithSize defined max length of LruCache
func WithSize(maxSize int) Option {
return func(l *LruCache) {
l.maxSize = maxSize
}
}
// WithStale decide whether Stale return is enabled.
// If this feature is enabled, element will not get Evicted according to `WithAge`.
func WithStale(stale bool) Option {
return func(l *LruCache) {
l.staleReturn = stale
}
}
// LruCache is a thread-safe, in-memory lru-cache that evicts the
// least recently used entries from memory when (if set) the entries are
// older than maxAge (in seconds). Use the New constructor to create one.
type LruCache struct {
maxAge int64
maxSize int
mu sync.Mutex
cache map[any]*list.Element
lru *list.List // Front is least-recent
updateAgeOnGet bool
staleReturn bool
onEvict EvictCallback
}
// New creates an LruCache
func New(options ...Option) *LruCache {
lc := &LruCache{
lru: list.New(),
cache: make(map[any]*list.Element),
}
for _, option := range options {
option(lc)
}
return lc
}
// Get returns the any representation of a cached response and a bool
// set to true if the key was found.
func (c *LruCache) Get(key any) (any, bool) {
entry := c.get(key)
if entry == nil {
return nil, false
}
value := entry.value
return value, true
}
// GetWithExpire returns the any representation of a cached response,
// a time.Time Give expected expires,
// and a bool set to true if the key was found.
// This method will NOT check the maxAge of element and will NOT update the expires.
func (c *LruCache) GetWithExpire(key any) (any, time.Time, bool) {
entry := c.get(key)
if entry == nil {
return nil, time.Time{}, false
}
return entry.value, time.Unix(entry.expires, 0), true
}
// Exist returns if key exist in cache but not put item to the head of linked list
func (c *LruCache) Exist(key any) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.cache[key]
return ok
}
// Set stores the any representation of a response for a given key.
func (c *LruCache) Set(key any, value any) {
expires := int64(0)
if c.maxAge > 0 {
expires = time.Now().Unix() + c.maxAge
}
c.SetWithExpire(key, value, time.Unix(expires, 0))
}
// SetWithExpire stores the any representation of a response for a given key and given expires.
// The expires time will round to second.
func (c *LruCache) SetWithExpire(key any, value any, expires time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
if le, ok := c.cache[key]; ok {
c.lru.MoveToBack(le)
e := le.Value.(*entry)
e.value = value
e.expires = expires.Unix()
} else {
e := &entry{key: key, value: value, expires: expires.Unix()}
c.cache[key] = c.lru.PushBack(e)
if c.maxSize > 0 {
if len := c.lru.Len(); len > c.maxSize {
c.deleteElement(c.lru.Front())
}
}
}
c.maybeDeleteOldest()
}
// CloneTo clone and overwrite elements to another LruCache
func (c *LruCache) CloneTo(n *LruCache) {
c.mu.Lock()
defer c.mu.Unlock()
n.mu.Lock()
defer n.mu.Unlock()
n.lru = list.New()
n.cache = make(map[any]*list.Element)
for e := c.lru.Front(); e != nil; e = e.Next() {
elm := e.Value.(*entry)
n.cache[elm.key] = n.lru.PushBack(elm)
}
}
func (c *LruCache) get(key any) *entry {
c.mu.Lock()
defer c.mu.Unlock()
le, ok := c.cache[key]
if !ok {
return nil
}
if !c.staleReturn && c.maxAge > 0 && le.Value.(*entry).expires <= time.Now().Unix() {
c.deleteElement(le)
c.maybeDeleteOldest()
return nil
}
c.lru.MoveToBack(le)
entry := le.Value.(*entry)
if c.maxAge > 0 && c.updateAgeOnGet {
entry.expires = time.Now().Unix() + c.maxAge
}
return entry
}
// Delete removes the value associated with a key.
func (c *LruCache) Delete(key any) {
c.mu.Lock()
if le, ok := c.cache[key]; ok {
c.deleteElement(le)
}
c.mu.Unlock()
}
func (c *LruCache) maybeDeleteOldest() {
if !c.staleReturn && c.maxAge > 0 {
now := time.Now().Unix()
for le := c.lru.Front(); le != nil && le.Value.(*entry).expires <= now; le = c.lru.Front() {
c.deleteElement(le)
}
}
}
func (c *LruCache) deleteElement(le *list.Element) {
c.lru.Remove(le)
e := le.Value.(*entry)
delete(c.cache, e.key)
if c.onEvict != nil {
c.onEvict(e.key, e.value)
}
}
type entry struct {
key any
value any
expires int64
}

183
common/cache/lrucache_test.go vendored Normal file
View File

@ -0,0 +1,183 @@
package cache
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var entries = []struct {
key string
value string
}{
{"1", "one"},
{"2", "two"},
{"3", "three"},
{"4", "four"},
{"5", "five"},
}
func TestLRUCache(t *testing.T) {
c := New()
for _, e := range entries {
c.Set(e.key, e.value)
}
c.Delete("missing")
_, ok := c.Get("missing")
assert.False(t, ok)
for _, e := range entries {
value, ok := c.Get(e.key)
if assert.True(t, ok) {
assert.Equal(t, e.value, value.(string))
}
}
for _, e := range entries {
c.Delete(e.key)
_, ok := c.Get(e.key)
assert.False(t, ok)
}
}
func TestLRUMaxAge(t *testing.T) {
c := New(WithAge(86400))
now := time.Now().Unix()
expected := now + 86400
// Add one expired entry
c.Set("foo", "bar")
c.lru.Back().Value.(*entry).expires = now
// Reset
c.Set("foo", "bar")
e := c.lru.Back().Value.(*entry)
assert.True(t, e.expires >= now)
c.lru.Back().Value.(*entry).expires = now
// Set a few and verify expiration times
for _, s := range entries {
c.Set(s.key, s.value)
e := c.lru.Back().Value.(*entry)
assert.True(t, e.expires >= expected && e.expires <= expected+10)
}
// Make sure we can get them all
for _, s := range entries {
_, ok := c.Get(s.key)
assert.True(t, ok)
}
// Expire all entries
for _, s := range entries {
le, ok := c.cache[s.key]
if assert.True(t, ok) {
le.Value.(*entry).expires = now
}
}
// Get one expired entry, which should clear all expired entries
_, ok := c.Get("3")
assert.False(t, ok)
assert.Equal(t, c.lru.Len(), 0)
}
func TestLRUpdateOnGet(t *testing.T) {
c := New(WithAge(86400), WithUpdateAgeOnGet())
now := time.Now().Unix()
expires := now + 86400/2
// Add one expired entry
c.Set("foo", "bar")
c.lru.Back().Value.(*entry).expires = expires
_, ok := c.Get("foo")
assert.True(t, ok)
assert.True(t, c.lru.Back().Value.(*entry).expires > expires)
}
func TestMaxSize(t *testing.T) {
c := New(WithSize(2))
// Add one expired entry
c.Set("foo", "bar")
_, ok := c.Get("foo")
assert.True(t, ok)
c.Set("bar", "foo")
c.Set("baz", "foo")
_, ok = c.Get("foo")
assert.False(t, ok)
}
func TestExist(t *testing.T) {
c := New(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 any, value any) {
temp = key.(int) + value.(int)
}
c := New(WithEvict(evict), WithSize(1))
c.Set(1, 2)
c.Set(2, 3)
assert.Equal(t, temp, 3)
}
func TestSetWithExpire(t *testing.T) {
c := New(WithAge(1))
now := time.Now().Unix()
tenSecBefore := time.Unix(now-10, 0)
c.SetWithExpire(1, 2, tenSecBefore)
// res is expected not to exist, and expires should be empty time.Time
res, expires, exist := c.GetWithExpire(1)
assert.Equal(t, nil, res)
assert.Equal(t, time.Time{}, expires)
assert.Equal(t, false, exist)
}
func TestStale(t *testing.T) {
c := New(WithAge(1), WithStale(true))
now := time.Now().Unix()
tenSecBefore := time.Unix(now-10, 0)
c.SetWithExpire(1, 2, tenSecBefore)
res, expires, exist := c.GetWithExpire(1)
assert.Equal(t, 2, res)
assert.Equal(t, tenSecBefore, expires)
assert.Equal(t, true, exist)
}
func TestCloneTo(t *testing.T) {
o := New(WithSize(10))
o.Set("1", 1)
o.Set("2", 2)
n := New(WithSize(2))
n.Set("3", 3)
n.Set("4", 4)
o.CloneTo(n)
assert.False(t, n.Exist("3"))
assert.True(t, n.Exist("1"))
n.Set("5", 5)
assert.False(t, n.Exist("1"))
}

50
common/murmur3/murmur.go Normal file
View File

@ -0,0 +1,50 @@
package murmur3
type bmixer interface {
bmix(p []byte) (tail []byte)
Size() (n int)
reset()
}
type digest struct {
clen int // Digested input cumulative length.
tail []byte // 0 to Size()-1 bytes view of `buf'.
buf [16]byte // Expected (but not required) to be Size() large.
seed uint32 // Seed for initializing the hash.
bmixer
}
func (d *digest) BlockSize() int { return 1 }
func (d *digest) Write(p []byte) (n int, err error) {
n = len(p)
d.clen += n
if len(d.tail) > 0 {
// Stick back pending bytes.
nfree := d.Size() - len(d.tail) // nfree ∈ [1, d.Size()-1].
if nfree < len(p) {
// One full block can be formed.
block := append(d.tail, p[:nfree]...)
p = p[nfree:]
_ = d.bmix(block) // No tail.
} else {
// Tail's buf is large enough to prevent reallocs.
p = append(d.tail, p...)
}
}
d.tail = d.bmix(p)
// Keep own copy of the 0 to Size()-1 pending bytes.
nn := copy(d.buf[:], d.tail)
d.tail = d.buf[:nn]
return n, nil
}
func (d *digest) Reset() {
d.clen = 0
d.tail = nil
d.bmixer.reset()
}

144
common/murmur3/murmur32.go Normal file
View File

@ -0,0 +1,144 @@
package murmur3
// https://github.com/spaolacci/murmur3/blob/master/murmur32.go
import (
"hash"
"math/bits"
"unsafe"
)
// Make sure interfaces are correctly implemented.
var (
_ hash.Hash32 = new(digest32)
_ bmixer = new(digest32)
)
const (
c1_32 uint32 = 0xcc9e2d51
c2_32 uint32 = 0x1b873593
)
// digest32 represents a partial evaluation of a 32 bites hash.
type digest32 struct {
digest
h1 uint32 // Unfinalized running hash.
}
// New32 returns new 32-bit hasher
func New32() hash.Hash32 { return New32WithSeed(0) }
// New32WithSeed returns new 32-bit hasher set with explicit seed value
func New32WithSeed(seed uint32) hash.Hash32 {
d := new(digest32)
d.seed = seed
d.bmixer = d
d.Reset()
return d
}
func (d *digest32) Size() int { return 4 }
func (d *digest32) reset() { d.h1 = d.seed }
func (d *digest32) Sum(b []byte) []byte {
h := d.Sum32()
return append(b, byte(h>>24), byte(h>>16), byte(h>>8), byte(h))
}
// Digest as many blocks as possible.
func (d *digest32) bmix(p []byte) (tail []byte) {
h1 := d.h1
nblocks := len(p) / 4
for i := 0; i < nblocks; i++ {
k1 := *(*uint32)(unsafe.Pointer(&p[i*4]))
k1 *= c1_32
k1 = bits.RotateLeft32(k1, 15)
k1 *= c2_32
h1 ^= k1
h1 = bits.RotateLeft32(h1, 13)
h1 = h1*4 + h1 + 0xe6546b64
}
d.h1 = h1
return p[nblocks*d.Size():]
}
func (d *digest32) Sum32() (h1 uint32) {
h1 = d.h1
var k1 uint32
switch len(d.tail) & 3 {
case 3:
k1 ^= uint32(d.tail[2]) << 16
fallthrough
case 2:
k1 ^= uint32(d.tail[1]) << 8
fallthrough
case 1:
k1 ^= uint32(d.tail[0])
k1 *= c1_32
k1 = bits.RotateLeft32(k1, 15)
k1 *= c2_32
h1 ^= k1
}
h1 ^= uint32(d.clen)
h1 ^= h1 >> 16
h1 *= 0x85ebca6b
h1 ^= h1 >> 13
h1 *= 0xc2b2ae35
h1 ^= h1 >> 16
return h1
}
func Sum32(data []byte) uint32 { return Sum32WithSeed(data, 0) }
func Sum32WithSeed(data []byte, seed uint32) uint32 {
h1 := seed
nblocks := len(data) / 4
for i := 0; i < nblocks; i++ {
k1 := *(*uint32)(unsafe.Pointer(&data[i*4]))
k1 *= c1_32
k1 = bits.RotateLeft32(k1, 15)
k1 *= c2_32
h1 ^= k1
h1 = bits.RotateLeft32(h1, 13)
h1 = h1*4 + h1 + 0xe6546b64
}
tail := data[nblocks*4:]
var k1 uint32
switch len(tail) & 3 {
case 3:
k1 ^= uint32(tail[2]) << 16
fallthrough
case 2:
k1 ^= uint32(tail[1]) << 8
fallthrough
case 1:
k1 ^= uint32(tail[0])
k1 *= c1_32
k1 = bits.RotateLeft32(k1, 15)
k1 *= c2_32
h1 ^= k1
}
h1 ^= uint32(len(data))
h1 ^= h1 >> 16
h1 *= 0x85ebca6b
h1 ^= h1 >> 13
h1 *= 0xc2b2ae35
h1 ^= h1 >> 16
return h1
}

44
common/net/bufconn.go Normal file
View File

@ -0,0 +1,44 @@
package net
import (
"bufio"
"net"
)
type BufferedConn struct {
r *bufio.Reader
net.Conn
}
func NewBufferedConn(c net.Conn) *BufferedConn {
if bc, ok := c.(*BufferedConn); ok {
return bc
}
return &BufferedConn{bufio.NewReader(c), c}
}
// Reader returns the internal bufio.Reader.
func (c *BufferedConn) Reader() *bufio.Reader {
return c.r
}
// Peek returns the next n bytes without advancing the reader.
func (c *BufferedConn) Peek(n int) ([]byte, error) {
return c.r.Peek(n)
}
func (c *BufferedConn) Read(p []byte) (int, error) {
return c.r.Read(p)
}
func (c *BufferedConn) ReadByte() (byte, error) {
return c.r.ReadByte()
}
func (c *BufferedConn) UnreadByte() error {
return c.r.UnreadByte()
}
func (c *BufferedConn) Buffered() int {
return c.r.Buffered()
}

11
common/net/io.go Normal file
View File

@ -0,0 +1,11 @@
package net
import "io"
type ReadOnlyReader struct {
io.Reader
}
type WriteOnlyWriter struct {
io.Writer
}

24
common/net/relay.go Normal file
View File

@ -0,0 +1,24 @@
package net
import (
"io"
"net"
"time"
)
// Relay copies between left and right bidirectionally.
func Relay(leftConn, rightConn net.Conn) {
ch := make(chan error)
go func() {
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
// See also https://github.com/Dreamacro/clash/pull/1209
_, err := io.Copy(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn})
leftConn.SetReadDeadline(time.Now())
ch <- err
}()
io.Copy(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn})
rightConn.SetReadDeadline(time.Now())
<-ch
}

View File

@ -1,3 +1,3 @@
package observable package observable
type Iterable <-chan interface{} type Iterable <-chan any

View File

@ -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

View File

@ -1,14 +1,16 @@
package observable package observable
import ( import (
"runtime"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"go.uber.org/atomic"
) )
func iterator(item []interface{}) chan interface{} { func iterator(item []any) chan any {
ch := make(chan interface{}) ch := make(chan any)
go func() { go func() {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
for _, elm := range item { for _, elm := range item {
@ -20,82 +22,67 @@ func iterator(item []interface{}) chan interface{} {
} }
func TestObservable(t *testing.T) { func TestObservable(t *testing.T) {
iter := iterator([]interface{}{1, 2, 3, 4, 5}) iter := iterator([]any{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_MultiSubscribe(t *testing.T) {
iter := iterator([]interface{}{1, 2, 3, 4, 5}) iter := iterator([]any{1, 2, 3, 4, 5})
src := NewObservable(iter) src := NewObservable(iter)
ch1, _ := src.Subscribe() ch1, _ := src.Subscribe()
ch2, _ := src.Subscribe() ch2, _ := src.Subscribe()
count := 0 count := atomic.NewInt32(0)
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(2) wg.Add(2)
waitCh := func(ch <-chan interface{}) { waitCh := func(ch <-chan any) {
for range ch { for range ch {
count = count + 1 count.Inc()
} }
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, int32(10), count.Load())
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([]any{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) {
iter := iterator([]interface{}{1}) iter := iterator([]any{1})
src := NewObservable(iter) src := NewObservable(iter)
data, _ := src.Subscribe() data, _ := src.Subscribe()
<-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) {
sub := Subscription(make(chan interface{})) sub := Subscription(make(chan any))
iter := iterator([]interface{}{1}) iter := iterator([]any{1})
src := NewObservable(iter) src := NewObservable(iter)
src.UnSubscribe(sub) src.UnSubscribe(sub)
} }
func TestObservable_SubscribeGoroutineLeak(t *testing.T) { func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
// waiting for other goroutine recycle iter := iterator([]any{1, 2, 3, 4, 5})
time.Sleep(120 * time.Millisecond)
init := runtime.NumGoroutine()
iter := iterator([]interface{}{1, 2, 3, 4, 5})
src := NewObservable(iter) src := NewObservable(iter)
max := 100 max := 100
@ -107,7 +94,7 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(max) wg.Add(max)
waitCh := func(ch <-chan interface{}) { waitCh := func(ch <-chan any) {
for range ch { for range ch {
} }
wg.Done() wg.Done()
@ -117,8 +104,43 @@ func TestObservable_SubscribeGoroutineLeak(t *testing.T) {
go waitCh(ch) go waitCh(ch)
} }
wg.Wait() wg.Wait()
now := runtime.NumGoroutine()
if init != now { for _, sub := range list {
t.Errorf("Goroutine Leak: init %d now %d", init, now) _, more := <-sub
assert.False(t, more)
} }
_, more := <-list[0]
assert.False(t, more)
}
func Benchmark_Observable_1000(b *testing.B) {
ch := make(chan any)
o := NewObservable(ch)
num := 1000
subs := []Subscription{}
for i := 0; i < num; i++ {
sub, _ := o.Subscribe()
subs = append(subs, sub)
}
wg := sync.WaitGroup{}
wg.Add(num)
b.ResetTimer()
for _, sub := range subs {
go func(s Subscription) {
for range s {
}
wg.Done()
}(sub)
}
for i := 0; i < b.N; i++ {
ch <- i
}
close(ch)
wg.Wait()
} }

View File

@ -2,34 +2,32 @@ package observable
import ( import (
"sync" "sync"
"gopkg.in/eapache/channels.v1"
) )
type Subscription <-chan interface{} type Subscription <-chan any
type Subscriber struct { type Subscriber struct {
buffer *channels.InfiniteChannel buffer chan any
once sync.Once once sync.Once
} }
func (s *Subscriber) Emit(item interface{}) { func (s *Subscriber) Emit(item any) {
s.buffer.In() <- item s.buffer <- item
} }
func (s *Subscriber) Out() Subscription { func (s *Subscriber) Out() Subscription {
return s.buffer.Out() return s.buffer
} }
func (s *Subscriber) Close() { func (s *Subscriber) Close() {
s.once.Do(func() { s.once.Do(func() {
s.buffer.Close() close(s.buffer)
}) })
} }
func newSubscriber() *Subscriber { func newSubscriber() *Subscriber {
sub := &Subscriber{ sub := &Subscriber{
buffer: channels.NewInfiniteChannel(), buffer: make(chan any, 200),
} }
return sub return sub
} }

80
common/picker/picker.go Normal file
View File

@ -0,0 +1,80 @@
package picker
import (
"context"
"sync"
"time"
)
// Picker provides synchronization, and Context cancelation
// for groups of goroutines working on subtasks of a common task.
// Inspired by errGroup
type Picker struct {
ctx context.Context
cancel func()
wg sync.WaitGroup
once sync.Once
errOnce sync.Once
result any
err error
}
func newPicker(ctx context.Context, cancel func()) *Picker {
return &Picker{
ctx: ctx,
cancel: cancel,
}
}
// WithContext returns a new Picker and an associated Context derived from ctx.
// and cancel when first element return.
func WithContext(ctx context.Context) (*Picker, context.Context) {
ctx, cancel := context.WithCancel(ctx)
return newPicker(ctx, cancel), ctx
}
// WithTimeout returns a new Picker and an associated Context derived from ctx with timeout.
func WithTimeout(ctx context.Context, timeout time.Duration) (*Picker, context.Context) {
ctx, cancel := context.WithTimeout(ctx, timeout)
return newPicker(ctx, cancel), ctx
}
// Wait blocks until all function calls from the Go method have returned,
// then returns the first nil error result (if any) from them.
func (p *Picker) Wait() any {
p.wg.Wait()
if p.cancel != nil {
p.cancel()
}
return p.result
}
// Error return the first error (if all success return nil)
func (p *Picker) Error() error {
return p.err
}
// Go calls the given function in a new goroutine.
// The first call to return a nil error cancels the group; its result will be returned by Wait.
func (p *Picker) Go(f func() (any, error)) {
p.wg.Add(1)
go func() {
defer p.wg.Done()
if ret, err := f(); err == nil {
p.once.Do(func() {
p.result = ret
if p.cancel != nil {
p.cancel()
}
})
} else {
p.errOnce.Do(func() {
p.err = err
})
}
}()
}

View File

@ -0,0 +1,40 @@
package picker
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func sleepAndSend(ctx context.Context, delay int, input any) func() (any, error) {
return func() (any, error) {
timer := time.NewTimer(time.Millisecond * time.Duration(delay))
select {
case <-timer.C:
return input, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
func TestPicker_Basic(t *testing.T) {
picker, ctx := WithContext(context.Background())
picker.Go(sleepAndSend(ctx, 30, 2))
picker.Go(sleepAndSend(ctx, 20, 1))
number := picker.Wait()
assert.NotNil(t, number)
assert.Equal(t, number.(int), 1)
}
func TestPicker_Timeout(t *testing.T) {
picker, ctx := WithTimeout(context.Background(), time.Millisecond*5)
picker.Go(sleepAndSend(ctx, 20, 1))
number := picker.Wait()
assert.Nil(t, number)
assert.NotNil(t, picker.Error())
}

73
common/pool/alloc.go Normal file
View File

@ -0,0 +1,73 @@
package pool
// Inspired by https://github.com/xtaci/smux/blob/master/alloc.go
import (
"errors"
"math/bits"
"sync"
)
var defaultAllocator = NewAllocator()
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
type Allocator struct {
buffers []sync.Pool
}
// NewAllocator initiates a []byte allocator for frames less than 65536 bytes,
// the waste(memory fragmentation) of space allocation is guaranteed to be
// no more than 50%.
func NewAllocator() *Allocator {
alloc := new(Allocator)
alloc.buffers = make([]sync.Pool, 17) // 1B -> 64K
for k := range alloc.buffers {
i := k
alloc.buffers[k].New = func() any {
return make([]byte, 1<<uint32(i))
}
}
return alloc
}
// Get a []byte from pool with most appropriate cap
func (alloc *Allocator) Get(size int) []byte {
switch {
case size < 0:
panic("alloc.Get: len out of range")
case size == 0:
return nil
case size > 65536:
return make([]byte, size)
default:
bits := msb(size)
if size == 1<<bits {
return alloc.buffers[bits].Get().([]byte)[:size]
}
return alloc.buffers[bits+1].Get().([]byte)[:size]
}
}
// Put returns a []byte to pool for future use,
// which the cap must be exactly 2^n
func (alloc *Allocator) Put(buf []byte) error {
if cap(buf) == 0 || cap(buf) > 65536 {
return nil
}
bits := msb(cap(buf))
if cap(buf) != 1<<bits {
return errors.New("allocator Put() incorrect buffer size")
}
//nolint
//lint:ignore SA6002 ignore temporarily
alloc.buffers[bits].Put(buf)
return nil
}
// msb return the pos of most significant bit
func msb(size int) uint16 {
return uint16(bits.Len32(uint32(size)) - 1)
}

48
common/pool/alloc_test.go Normal file
View File

@ -0,0 +1,48 @@
package pool
import (
"math/rand"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAllocGet(t *testing.T) {
alloc := NewAllocator()
assert.Nil(t, alloc.Get(0))
assert.Equal(t, 1, len(alloc.Get(1)))
assert.Equal(t, 2, len(alloc.Get(2)))
assert.Equal(t, 3, len(alloc.Get(3)))
assert.Equal(t, 4, cap(alloc.Get(3)))
assert.Equal(t, 4, cap(alloc.Get(4)))
assert.Equal(t, 1023, len(alloc.Get(1023)))
assert.Equal(t, 1024, cap(alloc.Get(1023)))
assert.Equal(t, 1024, len(alloc.Get(1024)))
assert.Equal(t, 65536, len(alloc.Get(65536)))
assert.Equal(t, 65537, len(alloc.Get(65537)))
}
func TestAllocPut(t *testing.T) {
alloc := NewAllocator()
assert.Nil(t, alloc.Put(nil), "put nil misbehavior")
assert.NotNil(t, alloc.Put(make([]byte, 3)), "put elem:3 []bytes misbehavior")
assert.Nil(t, alloc.Put(make([]byte, 4)), "put elem:4 []bytes misbehavior")
assert.Nil(t, alloc.Put(make([]byte, 1023, 1024)), "put elem:1024 []bytes misbehavior")
assert.Nil(t, alloc.Put(make([]byte, 65536)), "put elem:65536 []bytes misbehavior")
assert.Nil(t, alloc.Put(make([]byte, 65537)), "put elem:65537 []bytes misbehavior")
}
func TestAllocPutThenGet(t *testing.T) {
alloc := NewAllocator()
data := alloc.Get(4)
alloc.Put(data)
newData := alloc.Get(4)
assert.Equal(t, cap(data), cap(newData), "different cap while alloc.Get()")
}
func BenchmarkMSB(b *testing.B) {
for i := 0; i < b.N; i++ {
msb(rand.Int())
}
}

31
common/pool/buffer.go Normal file
View File

@ -0,0 +1,31 @@
package pool
import (
"bytes"
"sync"
"github.com/Dreamacro/protobytes"
)
var (
bufferPool = sync.Pool{New: func() any { return &bytes.Buffer{} }}
bytesBufferPool = sync.Pool{New: func() any { return &protobytes.BytesWriter{} }}
)
func GetBuffer() *bytes.Buffer {
return bufferPool.Get().(*bytes.Buffer)
}
func PutBuffer(buf *bytes.Buffer) {
buf.Reset()
bufferPool.Put(buf)
}
func GetBytesBuffer() *protobytes.BytesWriter {
return bytesBufferPool.Get().(*protobytes.BytesWriter)
}
func PutBytesBuffer(buf *protobytes.BytesWriter) {
buf.Reset()
bytesBufferPool.Put(buf)
}

21
common/pool/pool.go Normal file
View File

@ -0,0 +1,21 @@
package pool
const (
// io.Copy default buffer size is 32 KiB
// but the maximum packet size of vmess/shadowsocks is about 16 KiB
// so define a buffer of 20 KiB to reduce the memory of each TCP relay
RelayBufferSize = 20 * 1024
// RelayBufferSize uses 20KiB, but due to the allocator it will actually
// request 32Kib. Most UDPs are smaller than the MTU, and the TUN's MTU
// set to 9000, so the UDP Buffer size set to 16Kib
UDPBufferSize = 16 * 1024
)
func Get(size int) []byte {
return defaultAllocator.Get(size)
}
func Put(buf []byte) error {
return defaultAllocator.Put(buf)
}

71
common/queue/queue.go Normal file
View File

@ -0,0 +1,71 @@
package queue
import (
"sync"
)
// Queue is a simple concurrent safe queue
type Queue struct {
items []any
lock sync.RWMutex
}
// Put add the item to the queue.
func (q *Queue) Put(items ...any) {
if len(items) == 0 {
return
}
q.lock.Lock()
q.items = append(q.items, items...)
q.lock.Unlock()
}
// Pop returns the head of items.
func (q *Queue) Pop() any {
if len(q.items) == 0 {
return nil
}
q.lock.Lock()
head := q.items[0]
q.items = q.items[1:]
q.lock.Unlock()
return head
}
// Last returns the last of item.
func (q *Queue) Last() any {
if len(q.items) == 0 {
return nil
}
q.lock.RLock()
last := q.items[len(q.items)-1]
q.lock.RUnlock()
return last
}
// Copy get the copy of queue.
func (q *Queue) Copy() []any {
items := []any{}
q.lock.RLock()
items = append(items, q.items...)
q.lock.RUnlock()
return items
}
// Len returns the number of items in this queue.
func (q *Queue) Len() int64 {
q.lock.Lock()
defer q.lock.Unlock()
return int64(len(q.items))
}
// New is a constructor for a new concurrent safe queue.
func New(hint int64) *Queue {
return &Queue{
items: make([]any, 0, hint),
}
}

View File

@ -0,0 +1,63 @@
package singledo
import (
"sync"
"time"
)
type call struct {
wg sync.WaitGroup
val any
err error
}
type Single struct {
mux sync.Mutex
last time.Time
wait time.Duration
call *call
result *Result
}
type Result struct {
Val any
Err error
}
// Do single.Do likes sync.singleFlight
func (s *Single) Do(fn func() (any, error)) (v any, 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.mux.Lock()
s.call = nil
s.result = &Result{call.val, call.err}
s.last = now
s.mux.Unlock()
return call.val, call.err, false
}
func (s *Single) Reset() {
s.last = time.Time{}
}
func NewSingle(wait time.Duration) *Single {
return &Single{wait: wait}
}

View File

@ -0,0 +1,69 @@
package singledo
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.uber.org/atomic"
)
func TestBasic(t *testing.T) {
single := NewSingle(time.Millisecond * 30)
foo := 0
shardCount := atomic.NewInt32(0)
call := func() (any, error) {
foo++
time.Sleep(time.Millisecond * 5)
return nil, nil
}
var wg sync.WaitGroup
const n = 5
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
_, _, shard := single.Do(call)
if shard {
shardCount.Inc()
}
wg.Done()
}()
}
wg.Wait()
assert.Equal(t, 1, foo)
assert.Equal(t, int32(4), shardCount.Load())
}
func TestTimer(t *testing.T) {
single := NewSingle(time.Millisecond * 30)
foo := 0
call := func() (any, 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)
}
func TestReset(t *testing.T) {
single := NewSingle(time.Millisecond * 30)
foo := 0
call := func() (any, error) {
foo++
return nil, nil
}
single.Do(call)
single.Reset()
single.Do(call)
assert.Equal(t, 2, foo)
}

View File

@ -0,0 +1,19 @@
package sockopt
import (
"net"
"syscall"
)
func UDPReuseaddr(c *net.UDPConn) (err error) {
rc, err := c.SyscallConn()
if err != nil {
return
}
rc.Control(func(fd uintptr) {
err = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
})
return
}

View File

@ -0,0 +1,11 @@
//go:build !linux
package sockopt
import (
"net"
)
func UDPReuseaddr(c *net.UDPConn) (err error) {
return
}

View File

@ -1,5 +1,7 @@
package structure package structure
// references: https://github.com/mitchellh/mapstructure
import ( import (
"fmt" "fmt"
"reflect" "reflect"
@ -26,8 +28,8 @@ func NewDecoder(option Option) *Decoder {
return &Decoder{option: &option} return &Decoder{option: &option}
} }
// Decode transform a map[string]interface{} to a struct // Decode transform a map[string]any to a struct
func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error { func (d *Decoder) Decode(src map[string]any, dst any) error {
if reflect.TypeOf(dst).Kind() != reflect.Ptr { if reflect.TypeOf(dst).Kind() != reflect.Ptr {
return fmt.Errorf("Decode must recive a ptr struct") return fmt.Errorf("Decode must recive a ptr struct")
} }
@ -35,21 +37,23 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
v := reflect.ValueOf(dst).Elem() v := reflect.ValueOf(dst).Elem()
for idx := 0; idx < v.NumField(); idx++ { for idx := 0; idx < v.NumField(); idx++ {
field := t.Field(idx) field := t.Field(idx)
if field.Anonymous {
tag := field.Tag.Get(d.option.TagName) if err := d.decodeStruct(field.Name, src, v.Field(idx)); err != nil {
str := strings.SplitN(tag, ",", 2) return err
key := str[0] }
omitempty := false continue
if len(str) > 1 {
omitempty = str[1] == "omitempty"
} }
tag := field.Tag.Get(d.option.TagName)
key, omitKey, found := strings.Cut(tag, ",")
omitempty := found && omitKey == "omitempty"
value, ok := src[key] value, ok := src[key]
if !ok { if !ok || value == nil {
if omitempty { if omitempty {
continue continue
} }
return fmt.Errorf("key %s missing", key) return fmt.Errorf("key '%s' missing", key)
} }
err := d.decode(key, value, v.Field(idx)) err := d.decode(key, value, v.Field(idx))
@ -60,7 +64,7 @@ func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error {
return nil return nil
} }
func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error { func (d *Decoder) decode(name string, data any, val reflect.Value) error {
switch val.Kind() { switch val.Kind() {
case reflect.Int: case reflect.Int:
return d.decodeInt(name, data, val) return d.decodeInt(name, data, val)
@ -70,17 +74,25 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error
return d.decodeBool(name, data, val) return d.decodeBool(name, data, val)
case reflect.Slice: case reflect.Slice:
return d.decodeSlice(name, data, val) return d.decodeSlice(name, data, val)
case reflect.Map:
return d.decodeMap(name, data, val)
case reflect.Interface:
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())
} }
} }
func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (err error) { func (d *Decoder) decodeInt(name string, data any, val reflect.Value) (err error) {
dataVal := reflect.ValueOf(data) dataVal := reflect.ValueOf(data)
kind := dataVal.Kind() kind := dataVal.Kind()
switch { switch {
case kind == reflect.Int: case kind == reflect.Int:
val.SetInt(dataVal.Int()) val.SetInt(dataVal.Int())
case kind == reflect.Float64 && d.option.WeaklyTypedInput:
val.SetInt(int64(dataVal.Float()))
case kind == reflect.String && d.option.WeaklyTypedInput: case kind == reflect.String && d.option.WeaklyTypedInput:
var i int64 var i int64
i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits()) i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits())
@ -98,7 +110,7 @@ func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (e
return err return err
} }
func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) (err error) { func (d *Decoder) decodeString(name string, data any, val reflect.Value) (err error) {
dataVal := reflect.ValueOf(data) dataVal := reflect.ValueOf(data)
kind := dataVal.Kind() kind := dataVal.Kind()
switch { switch {
@ -108,14 +120,14 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value)
val.SetString(strconv.FormatInt(dataVal.Int(), 10)) val.SetString(strconv.FormatInt(dataVal.Int(), 10))
default: default:
err = fmt.Errorf( err = fmt.Errorf(
"'%s' expected type'%s', got unconvertible type '%s'", "'%s' expected type '%s', got unconvertible type '%s'",
name, val.Type(), dataVal.Type(), name, val.Type(), dataVal.Type(),
) )
} }
return err return err
} }
func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (err error) { func (d *Decoder) decodeBool(name string, data any, val reflect.Value) (err error) {
dataVal := reflect.ValueOf(data) dataVal := reflect.ValueOf(data)
kind := dataVal.Kind() kind := dataVal.Kind()
switch { switch {
@ -125,14 +137,14 @@ func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (
val.SetBool(dataVal.Int() != 0) val.SetBool(dataVal.Int() != 0)
default: default:
err = fmt.Errorf( err = fmt.Errorf(
"'%s' expected type'%s', got unconvertible type '%s'", "'%s' expected type '%s', got unconvertible type '%s'",
name, val.Type(), dataVal.Type(), name, val.Type(), dataVal.Type(),
) )
} }
return err return err
} }
func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { func (d *Decoder) decodeSlice(name string, data any, val reflect.Value) error {
dataVal := reflect.Indirect(reflect.ValueOf(data)) dataVal := reflect.Indirect(reflect.ValueOf(data))
valType := val.Type() valType := val.Type()
valElemType := valType.Elem() valElemType := valType.Elem()
@ -147,9 +159,19 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
for valSlice.Len() <= i { for valSlice.Len() <= i {
valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) valSlice = reflect.Append(valSlice, reflect.Zero(valElemType))
} }
currentField := valSlice.Index(i)
fieldName := fmt.Sprintf("%s[%d]", name, i) fieldName := fmt.Sprintf("%s[%d]", name, i)
if currentData == nil {
// in weakly type mode, null will convert to zero value
if d.option.WeaklyTypedInput {
continue
}
// in non-weakly type mode, null will convert to nil if element's zero value is nil, otherwise return an error
if elemKind := valElemType.Kind(); elemKind == reflect.Map || elemKind == reflect.Slice {
continue
}
return fmt.Errorf("'%s' can not be null", fieldName)
}
currentField := valSlice.Index(i)
if err := d.decode(fieldName, currentData, currentField); err != nil { if err := d.decode(fieldName, currentData, currentField); err != nil {
return err return err
} }
@ -158,3 +180,234 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
val.Set(valSlice) val.Set(valSlice)
return nil return nil
} }
func (d *Decoder) decodeMap(name string, data any, val reflect.Value) error {
valType := val.Type()
valKeyType := valType.Key()
valElemType := valType.Elem()
valMap := val
if valMap.IsNil() {
mapType := reflect.MapOf(valKeyType, valElemType)
valMap = reflect.MakeMap(mapType)
}
dataVal := reflect.Indirect(reflect.ValueOf(data))
if dataVal.Kind() != reflect.Map {
return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind())
}
return d.decodeMapFromMap(name, dataVal, val, valMap)
}
func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error {
valType := val.Type()
valKeyType := valType.Key()
valElemType := valType.Elem()
errors := make([]string, 0)
if dataVal.Len() == 0 {
if dataVal.IsNil() {
if !val.IsNil() {
val.Set(dataVal)
}
} else {
val.Set(valMap)
}
return nil
}
for _, k := range dataVal.MapKeys() {
fieldName := fmt.Sprintf("%s[%s]", name, k)
currentKey := reflect.Indirect(reflect.New(valKeyType))
if err := d.decode(fieldName, k.Interface(), currentKey); err != nil {
errors = append(errors, err.Error())
continue
}
v := dataVal.MapIndex(k).Interface()
if v == nil {
errors = append(errors, fmt.Sprintf("filed %s invalid", fieldName))
continue
}
currentVal := reflect.Indirect(reflect.New(valElemType))
if err := d.decode(fieldName, v, currentVal); err != nil {
errors = append(errors, err.Error())
continue
}
valMap.SetMapIndex(currentKey, currentVal)
}
val.Set(valMap)
if len(errors) > 0 {
return fmt.Errorf(strings.Join(errors, ","))
}
return nil
}
func (d *Decoder) decodeStruct(name string, data any, 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[any]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 any, val reflect.Value) (err error) {
dataVal := reflect.ValueOf(data)
val.Set(dataVal)
return nil
}

View File

@ -1,12 +1,15 @@
package structure package structure
import ( import (
"reflect"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
var decoder = NewDecoder(Option{TagName: "test"}) var (
var weakTypeDecoder = NewDecoder(Option{TagName: "test", WeaklyTypedInput: true}) decoder = NewDecoder(Option{TagName: "test"})
weakTypeDecoder = NewDecoder(Option{TagName: "test", WeaklyTypedInput: true})
)
type Baz struct { type Baz struct {
Foo int `test:"foo"` Foo int `test:"foo"`
@ -24,7 +27,7 @@ type BazOptional struct {
} }
func TestStructure_Basic(t *testing.T) { func TestStructure_Basic(t *testing.T) {
rawMap := map[string]interface{}{ rawMap := map[string]any{
"foo": 1, "foo": 1,
"bar": "test", "bar": "test",
"extra": false, "extra": false,
@ -37,16 +40,12 @@ func TestStructure_Basic(t *testing.T) {
s := &Baz{} s := &Baz{}
err := decoder.Decode(rawMap, s) err := decoder.Decode(rawMap, s)
if err != nil { assert.Nil(t, err)
t.Fatal(err.Error()) assert.Equal(t, goal, s)
}
if !reflect.DeepEqual(s, goal) {
t.Fatalf("bad: %#v", s)
}
} }
func TestStructure_Slice(t *testing.T) { func TestStructure_Slice(t *testing.T) {
rawMap := map[string]interface{}{ rawMap := map[string]any{
"foo": 1, "foo": 1,
"bar": []string{"one", "two"}, "bar": []string{"one", "two"},
} }
@ -58,16 +57,12 @@ func TestStructure_Slice(t *testing.T) {
s := &BazSlice{} s := &BazSlice{}
err := decoder.Decode(rawMap, s) err := decoder.Decode(rawMap, s)
if err != nil { assert.Nil(t, err)
t.Fatal(err.Error()) assert.Equal(t, goal, s)
}
if !reflect.DeepEqual(s, goal) {
t.Fatalf("bad: %#v", s)
}
} }
func TestStructure_Optional(t *testing.T) { func TestStructure_Optional(t *testing.T) {
rawMap := map[string]interface{}{ rawMap := map[string]any{
"foo": 1, "foo": 1,
} }
@ -77,50 +72,40 @@ func TestStructure_Optional(t *testing.T) {
s := &BazOptional{} s := &BazOptional{}
err := decoder.Decode(rawMap, s) err := decoder.Decode(rawMap, s)
if err != nil { assert.Nil(t, err)
t.Fatal(err.Error()) assert.Equal(t, goal, s)
}
if !reflect.DeepEqual(s, goal) {
t.Fatalf("bad: %#v", s)
}
} }
func TestStructure_MissingKey(t *testing.T) { func TestStructure_MissingKey(t *testing.T) {
rawMap := map[string]interface{}{ rawMap := map[string]any{
"foo": 1, "foo": 1,
} }
s := &Baz{} s := &Baz{}
err := decoder.Decode(rawMap, s) err := decoder.Decode(rawMap, s)
if err == nil { assert.NotNilf(t, err, "should throw error: %#v", s)
t.Fatalf("should throw error: %#v", s)
}
} }
func TestStructure_ParamError(t *testing.T) { func TestStructure_ParamError(t *testing.T) {
rawMap := map[string]interface{}{} rawMap := map[string]any{}
s := Baz{} s := Baz{}
err := decoder.Decode(rawMap, s) err := decoder.Decode(rawMap, s)
if err == nil { assert.NotNilf(t, err, "should throw error: %#v", s)
t.Fatalf("should throw error: %#v", s)
}
} }
func TestStructure_SliceTypeError(t *testing.T) { func TestStructure_SliceTypeError(t *testing.T) {
rawMap := map[string]interface{}{ rawMap := map[string]any{
"foo": 1, "foo": 1,
"bar": []int{1, 2}, "bar": []int{1, 2},
} }
s := &BazSlice{} s := &BazSlice{}
err := decoder.Decode(rawMap, s) err := decoder.Decode(rawMap, s)
if err == nil { assert.NotNilf(t, err, "should throw error: %#v", s)
t.Fatalf("should throw error: %#v", s)
}
} }
func TestStructure_WeakType(t *testing.T) { func TestStructure_WeakType(t *testing.T) {
rawMap := map[string]interface{}{ rawMap := map[string]any{
"foo": "1", "foo": "1",
"bar": []int{1}, "bar": []int{1},
} }
@ -132,10 +117,65 @@ func TestStructure_WeakType(t *testing.T) {
s := &BazSlice{} s := &BazSlice{}
err := weakTypeDecoder.Decode(rawMap, s) err := weakTypeDecoder.Decode(rawMap, s)
if err != nil { assert.Nil(t, err)
t.Fatal(err.Error()) assert.Equal(t, goal, s)
} }
if !reflect.DeepEqual(s, goal) {
t.Fatalf("bad: %#v", s) func TestStructure_Nest(t *testing.T) {
} rawMap := map[string]any{
"foo": 1,
}
goal := BazOptional{
Foo: 1,
}
s := &struct {
BazOptional
}{}
err := decoder.Decode(rawMap, s)
assert.Nil(t, err)
assert.Equal(t, s.BazOptional, goal)
}
func TestStructure_SliceNilValue(t *testing.T) {
rawMap := map[string]any{
"foo": 1,
"bar": []any{"bar", nil},
}
goal := &BazSlice{
Foo: 1,
Bar: []string{"bar", ""},
}
s := &BazSlice{}
err := weakTypeDecoder.Decode(rawMap, s)
assert.Nil(t, err)
assert.Equal(t, goal.Bar, s.Bar)
s = &BazSlice{}
err = decoder.Decode(rawMap, s)
assert.NotNil(t, err)
}
func TestStructure_SliceNilValueComplex(t *testing.T) {
rawMap := map[string]any{
"bar": []any{map[string]any{"bar": "foo"}, nil},
}
s := &struct {
Bar []map[string]any `test:"bar"`
}{}
err := decoder.Decode(rawMap, s)
assert.Nil(t, err)
assert.Nil(t, s.Bar[1])
ss := &struct {
Bar []Baz `test:"bar"`
}{}
err = decoder.Decode(rawMap, ss)
assert.NotNil(t, err)
} }

46
component/auth/auth.go Normal file
View File

@ -0,0 +1,46 @@
package auth
import (
"sync"
)
type Authenticator interface {
Verify(user string, pass string) bool
Users() []string
}
type AuthUser struct {
User string
Pass string
}
type inMemoryAuthenticator struct {
storage *sync.Map
usernames []string
}
func (au *inMemoryAuthenticator) Verify(user string, pass string) bool {
realPass, ok := au.storage.Load(user)
return ok && realPass == pass
}
func (au *inMemoryAuthenticator) Users() []string { return au.usernames }
func NewAuthenticator(users []AuthUser) Authenticator {
if len(users) == 0 {
return nil
}
au := &inMemoryAuthenticator{storage: &sync.Map{}}
for _, user := range users {
au.storage.Store(user.User, user.Pass)
}
usernames := make([]string, 0, len(users))
au.storage.Range(func(key, value any) bool {
usernames = append(usernames, key.(string))
return true
})
au.usernames = usernames
return au
}

28
component/dhcp/conn.go Normal file
View File

@ -0,0 +1,28 @@
package dhcp
import (
"context"
"net"
"runtime"
"github.com/Dreamacro/clash/component/dialer"
)
func ListenDHCPClient(ctx context.Context, ifaceName string) (net.PacketConn, error) {
listenAddr := "0.0.0.0:68"
if runtime.GOOS == "linux" || runtime.GOOS == "android" {
listenAddr = "255.255.255.255:68"
}
options := []dialer.Option{
dialer.WithInterface(ifaceName),
dialer.WithAddrReuse(true),
}
// fallback bind on windows, because syscall bind can not receive broadcast
if runtime.GOOS == "windows" {
options = append(options, dialer.WithFallbackBind(true))
}
return dialer.ListenPacket(ctx, "udp4", listenAddr, options...)
}

88
component/dhcp/dhcp.go Normal file
View File

@ -0,0 +1,88 @@
package dhcp
import (
"context"
"errors"
"net"
"github.com/Dreamacro/clash/component/iface"
"github.com/insomniacslk/dhcp/dhcpv4"
)
var (
ErrNotResponding = errors.New("DHCP not responding")
ErrNotFound = errors.New("DNS option not found")
)
func ResolveDNSFromDHCP(context context.Context, ifaceName string) ([]net.IP, error) {
conn, err := ListenDHCPClient(context, ifaceName)
if err != nil {
return nil, err
}
defer conn.Close()
result := make(chan []net.IP, 1)
ifaceObj, err := iface.ResolveInterface(ifaceName)
if err != nil {
return nil, err
}
discovery, err := dhcpv4.NewDiscovery(ifaceObj.HardwareAddr, dhcpv4.WithBroadcast(true), dhcpv4.WithRequestedOptions(dhcpv4.OptionDomainNameServer))
if err != nil {
return nil, err
}
go receiveOffer(conn, discovery.TransactionID, result)
_, err = conn.WriteTo(discovery.ToBytes(), &net.UDPAddr{IP: net.IPv4bcast, Port: 67})
if err != nil {
return nil, err
}
select {
case r, ok := <-result:
if !ok {
return nil, ErrNotFound
}
return r, nil
case <-context.Done():
return nil, ErrNotResponding
}
}
func receiveOffer(conn net.PacketConn, id dhcpv4.TransactionID, result chan<- []net.IP) {
defer close(result)
buf := make([]byte, dhcpv4.MaxMessageSize)
for {
n, _, err := conn.ReadFrom(buf)
if err != nil {
return
}
pkt, err := dhcpv4.FromBytes(buf[:n])
if err != nil {
continue
}
if pkt.MessageType() != dhcpv4.MessageTypeOffer {
continue
}
if pkt.TransactionID != id {
continue
}
dns := pkt.DNS()
if len(dns) == 0 {
return
}
result <- dns
return
}
}

View File

@ -0,0 +1,66 @@
package dialer
import (
"net"
"syscall"
"github.com/Dreamacro/clash/component/iface"
"golang.org/x/sys/unix"
)
type controlFn = func(network, address string, c syscall.RawConn) error
func bindControl(ifaceIdx int, chain controlFn) controlFn {
return func(network, address string, c syscall.RawConn) (err error) {
defer func() {
if err == nil && chain != nil {
err = chain(network, address, c)
}
}()
ipStr, _, err := net.SplitHostPort(address)
if err == nil {
ip := net.ParseIP(ipStr)
if ip != nil && !ip.IsGlobalUnicast() {
return
}
}
var innerErr error
err = c.Control(func(fd uintptr) {
switch network {
case "tcp4", "udp4":
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, ifaceIdx)
case "tcp6", "udp6":
innerErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, ifaceIdx)
}
})
if innerErr != nil {
err = innerErr
}
return
}
}
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ net.IP) error {
ifaceObj, err := iface.ResolveInterface(ifaceName)
if err != nil {
return err
}
dialer.Control = bindControl(ifaceObj.Index, dialer.Control)
return nil
}
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
ifaceObj, err := iface.ResolveInterface(ifaceName)
if err != nil {
return "", err
}
lc.Control = bindControl(ifaceObj.Index, lc.Control)
return address, nil
}

View File

@ -0,0 +1,51 @@
package dialer
import (
"net"
"syscall"
"golang.org/x/sys/unix"
)
type controlFn = func(network, address string, c syscall.RawConn) error
func bindControl(ifaceName string, chain controlFn) controlFn {
return func(network, address string, c syscall.RawConn) (err error) {
defer func() {
if err == nil && chain != nil {
err = chain(network, address, c)
}
}()
ipStr, _, err := net.SplitHostPort(address)
if err == nil {
ip := net.ParseIP(ipStr)
if ip != nil && !ip.IsGlobalUnicast() {
return
}
}
var innerErr error
err = c.Control(func(fd uintptr) {
innerErr = unix.BindToDevice(int(fd), ifaceName)
})
if innerErr != nil {
err = innerErr
}
return
}
}
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ net.IP) error {
dialer.Control = bindControl(ifaceName, dialer.Control)
return nil
}
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
lc.Control = bindControl(ifaceName, lc.Control)
return address, nil
}

View File

@ -0,0 +1,47 @@
//go:build !linux && !darwin && !windows
package dialer
import (
"net"
"strconv"
)
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, destination net.IP) error {
if !destination.IsGlobalUnicast() {
return nil
}
local := uint64(0)
if dialer.LocalAddr != nil {
_, port, err := net.SplitHostPort(dialer.LocalAddr.String())
if err == nil {
local, _ = strconv.ParseUint(port, 10, 16)
}
}
addr, err := lookupLocalAddr(ifaceName, network, destination, int(local))
if err != nil {
return err
}
dialer.LocalAddr = addr
return nil
}
func bindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, address string) (string, error) {
_, port, err := net.SplitHostPort(address)
if err != nil {
port = "0"
}
local, _ := strconv.ParseUint(port, 10, 16)
addr, err := lookupLocalAddr(ifaceName, network, nil, int(local))
if err != nil {
return "", err
}
return addr.String(), nil
}

View File

@ -0,0 +1,98 @@
package dialer
import (
"encoding/binary"
"net"
"strings"
"syscall"
"unsafe"
"github.com/Dreamacro/clash/component/iface"
"golang.org/x/sys/windows"
)
const (
IP_UNICAST_IF = 31
IPV6_UNICAST_IF = 31
)
type controlFn = func(network, address string, c syscall.RawConn) error
func bindControl(ifaceIdx int, chain controlFn) controlFn {
return func(network, address string, c syscall.RawConn) (err error) {
defer func() {
if err == nil && chain != nil {
err = chain(network, address, c)
}
}()
ipStr, _, err := net.SplitHostPort(address)
if err == nil {
ip := net.ParseIP(ipStr)
if ip != nil && !ip.IsGlobalUnicast() {
return
}
}
var innerErr error
err = c.Control(func(fd uintptr) {
if ipStr == "" && strings.HasPrefix(network, "udp") {
// When listening udp ":0", we should bind socket to interface4 and interface6 at the same time
// and ignore the error of bind6
_ = bindSocketToInterface6(windows.Handle(fd), ifaceIdx)
innerErr = bindSocketToInterface4(windows.Handle(fd), ifaceIdx)
return
}
switch network {
case "tcp4", "udp4":
innerErr = bindSocketToInterface4(windows.Handle(fd), ifaceIdx)
case "tcp6", "udp6":
innerErr = bindSocketToInterface6(windows.Handle(fd), ifaceIdx)
}
})
if innerErr != nil {
err = innerErr
}
return
}
}
func bindSocketToInterface4(handle windows.Handle, ifaceIdx int) error {
// MSDN says for IPv4 this needs to be in net byte order, so that it's like an IP address with leading zeros.
// Ref: https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-ip-socket-options
var bytes [4]byte
binary.BigEndian.PutUint32(bytes[:], uint32(ifaceIdx))
index := *(*uint32)(unsafe.Pointer(&bytes[0]))
err := windows.SetsockoptInt(handle, windows.IPPROTO_IP, IP_UNICAST_IF, int(index))
if err != nil {
return err
}
return nil
}
func bindSocketToInterface6(handle windows.Handle, ifaceIdx int) error {
return windows.SetsockoptInt(handle, windows.IPPROTO_IPV6, IPV6_UNICAST_IF, ifaceIdx)
}
func bindIfaceToDialer(ifaceName string, dialer *net.Dialer, _ string, _ net.IP) error {
ifaceObj, err := iface.ResolveInterface(ifaceName)
if err != nil {
return err
}
dialer.Control = bindControl(ifaceObj.Index, dialer.Control)
return nil
}
func bindIfaceToListenConfig(ifaceName string, lc *net.ListenConfig, _, address string) (string, error) {
ifaceObj, err := iface.ResolveInterface(ifaceName)
if err != nil {
return "", err
}
lc.Control = bindControl(ifaceObj.Index, lc.Control)
return address, nil
}

182
component/dialer/dialer.go Normal file
View File

@ -0,0 +1,182 @@
package dialer
import (
"context"
"errors"
"net"
"github.com/Dreamacro/clash/component/resolver"
)
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
switch network {
case "tcp4", "tcp6", "udp4", "udp6":
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
var ip net.IP
switch network {
case "tcp4", "udp4":
ip, err = resolver.ResolveIPv4(host)
default:
ip, err = resolver.ResolveIPv6(host)
}
if err != nil {
return nil, err
}
return dialContext(ctx, network, ip, port, options)
case "tcp", "udp":
return dualStackDialContext(ctx, network, address, options)
default:
return nil, errors.New("network invalid")
}
}
func ListenPacket(ctx context.Context, network, address string, options ...Option) (net.PacketConn, error) {
cfg := &option{
interfaceName: DefaultInterface.Load(),
routingMark: int(DefaultRoutingMark.Load()),
}
for _, o := range DefaultOptions {
o(cfg)
}
for _, o := range options {
o(cfg)
}
lc := &net.ListenConfig{}
if cfg.interfaceName != "" {
var (
addr string
err error
)
if cfg.fallbackBind {
addr, err = fallbackBindIfaceToListenConfig(cfg.interfaceName, lc, network, address)
} else {
addr, err = bindIfaceToListenConfig(cfg.interfaceName, lc, network, address)
}
if err != nil {
return nil, err
}
address = addr
}
if cfg.addrReuse {
addrReuseToListenConfig(lc)
}
if cfg.routingMark != 0 {
bindMarkToListenConfig(cfg.routingMark, lc, network, address)
}
return lc.ListenPacket(ctx, network, address)
}
func dialContext(ctx context.Context, network string, destination net.IP, port string, options []Option) (net.Conn, error) {
opt := &option{
interfaceName: DefaultInterface.Load(),
routingMark: int(DefaultRoutingMark.Load()),
}
for _, o := range DefaultOptions {
o(opt)
}
for _, o := range options {
o(opt)
}
dialer := &net.Dialer{}
if opt.interfaceName != "" {
if opt.fallbackBind {
if err := fallbackBindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
return nil, err
}
} else {
if err := bindIfaceToDialer(opt.interfaceName, dialer, network, destination); err != nil {
return nil, err
}
}
}
if opt.routingMark != 0 {
bindMarkToDialer(opt.routingMark, dialer, network, destination)
}
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
}
func dualStackDialContext(ctx context.Context, network, address string, options []Option) (net.Conn, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
returned := make(chan struct{})
defer close(returned)
type dialResult struct {
net.Conn
error
resolved bool
ipv6 bool
done bool
}
results := make(chan dialResult)
var primary, fallback dialResult
startRacer := func(ctx context.Context, network, host string, ipv6 bool) {
result := dialResult{ipv6: ipv6, done: true}
defer func() {
select {
case results <- result:
case <-returned:
if result.Conn != nil {
result.Conn.Close()
}
}
}()
var ip net.IP
if ipv6 {
ip, result.error = resolver.ResolveIPv6(host)
} else {
ip, result.error = resolver.ResolveIPv4(host)
}
if result.error != nil {
return
}
result.resolved = true
result.Conn, result.error = dialContext(ctx, network, ip, port, options)
}
go startRacer(ctx, network+"4", host, false)
go startRacer(ctx, network+"6", host, true)
for res := range results {
if res.error == nil {
return res.Conn, nil
}
if !res.ipv6 {
primary = res
} else {
fallback = res
}
if primary.done && fallback.done {
if primary.resolved {
return nil, primary.error
} else if fallback.resolved {
return nil, fallback.error
} else {
return nil, primary.error
}
}
}
return nil, errors.New("never touched")
}

View File

@ -0,0 +1,90 @@
package dialer
import (
"net"
"strconv"
"strings"
"github.com/Dreamacro/clash/component/iface"
)
func lookupLocalAddr(ifaceName string, network string, destination net.IP, port int) (net.Addr, error) {
ifaceObj, err := iface.ResolveInterface(ifaceName)
if err != nil {
return nil, err
}
var addr *net.IPNet
switch network {
case "udp4", "tcp4":
addr, err = ifaceObj.PickIPv4Addr(destination)
case "tcp6", "udp6":
addr, err = ifaceObj.PickIPv6Addr(destination)
default:
if destination != nil {
if destination.To4() != nil {
addr, err = ifaceObj.PickIPv4Addr(destination)
} else {
addr, err = ifaceObj.PickIPv6Addr(destination)
}
} else {
addr, err = ifaceObj.PickIPv4Addr(destination)
}
}
if err != nil {
return nil, err
}
if strings.HasPrefix(network, "tcp") {
return &net.TCPAddr{
IP: addr.IP,
Port: port,
}, nil
} else if strings.HasPrefix(network, "udp") {
return &net.UDPAddr{
IP: addr.IP,
Port: port,
}, nil
}
return nil, iface.ErrAddrNotFound
}
func fallbackBindIfaceToDialer(ifaceName string, dialer *net.Dialer, network string, destination net.IP) error {
if !destination.IsGlobalUnicast() {
return nil
}
local := uint64(0)
if dialer.LocalAddr != nil {
_, port, err := net.SplitHostPort(dialer.LocalAddr.String())
if err == nil {
local, _ = strconv.ParseUint(port, 10, 16)
}
}
addr, err := lookupLocalAddr(ifaceName, network, destination, int(local))
if err != nil {
return err
}
dialer.LocalAddr = addr
return nil
}
func fallbackBindIfaceToListenConfig(ifaceName string, _ *net.ListenConfig, network, address string) (string, error) {
_, port, err := net.SplitHostPort(address)
if err != nil {
port = "0"
}
local, _ := strconv.ParseUint(port, 10, 16)
addr, err := lookupLocalAddr(ifaceName, network, nil, int(local))
if err != nil {
return "", err
}
return addr.String(), nil
}

View File

@ -0,0 +1,43 @@
//go:build linux
package dialer
import (
"net"
"syscall"
)
func bindMarkToDialer(mark int, dialer *net.Dialer, _ string, _ net.IP) {
dialer.Control = bindMarkToControl(mark, dialer.Control)
}
func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, address string) {
lc.Control = bindMarkToControl(mark, lc.Control)
}
func bindMarkToControl(mark int, chain controlFn) controlFn {
return func(network, address string, c syscall.RawConn) (err error) {
defer func() {
if err == nil && chain != nil {
err = chain(network, address, c)
}
}()
ipStr, _, err := net.SplitHostPort(address)
if err == nil {
ip := net.ParseIP(ipStr)
if ip != nil && !ip.IsGlobalUnicast() {
return
}
}
var innerErr error
err = c.Control(func(fd uintptr) {
innerErr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, mark)
})
if innerErr != nil {
err = innerErr
}
return
}
}

View File

@ -0,0 +1,26 @@
//go:build !linux
package dialer
import (
"net"
"sync"
"github.com/Dreamacro/clash/log"
)
var printMarkWarnOnce sync.Once
func printMarkWarn() {
printMarkWarnOnce.Do(func() {
log.Warnln("Routing mark on socket is not supported on current platform")
})
}
func bindMarkToDialer(mark int, dialer *net.Dialer, _ string, _ net.IP) {
printMarkWarn()
}
func bindMarkToListenConfig(mark int, lc *net.ListenConfig, _, address string) {
printMarkWarn()
}

View File

@ -0,0 +1,42 @@
package dialer
import "go.uber.org/atomic"
var (
DefaultOptions []Option
DefaultInterface = atomic.NewString("")
DefaultRoutingMark = atomic.NewInt32(0)
)
type option struct {
interfaceName string
fallbackBind bool
addrReuse bool
routingMark int
}
type Option func(opt *option)
func WithInterface(name string) Option {
return func(opt *option) {
opt.interfaceName = name
}
}
func WithFallbackBind(fallback bool) Option {
return func(opt *option) {
opt.fallbackBind = fallback
}
}
func WithAddrReuse(reuse bool) Option {
return func(opt *option) {
opt.addrReuse = reuse
}
}
func WithRoutingMark(mark int) Option {
return func(opt *option) {
opt.routingMark = mark
}
}

Some files were not shown because too many files have changed in this diff Show More