Compare commits

..
352 Commits
Author SHA1 Message Date
世界 a72e18bac2 Bump version 2022-09-09 14:43:42 +08:00
世界 138756d638 Fix match 4in6 address in ip_cidr 2022-09-09 14:07:02 +08:00
世界 64db6e9d64 Fix documentation 2022-09-09 13:54:02 +08:00
世界 1ccc37694b Minor fixes 2022-09-08 18:33:59 +08:00
GyDiandGitHub 956445435e Fix clashapi log level format error 2022-09-08 18:04:06 +08:00
世界 e53e408fa8 Update documentation 2022-09-07 23:10:36 +08:00
世界 d77c26ed0d Fix hysteria stream error 2022-09-07 19:16:20 +08:00
世界 78519abb66 Refine test 2022-09-07 19:16:20 +08:00
世界 888dd95d44 Fix processing vmess termination signal 2022-09-07 19:16:20 +08:00
世界 d3d4a6e88f Fix json format error message 2022-09-07 13:23:26 +08:00
世界 2b064ee395 Fix naive inbound temporary 2022-09-07 12:30:54 +08:00
zakuwakiand世界 4f772b014e Suppress accept proxyproto failed #65 2022-09-06 23:16:31 +08:00
世界 db43deed77 Fix wireguard reconnect 2022-09-06 00:11:43 +08:00
世界 956c70c65e Update documentation 2022-09-04 13:15:10 +08:00
世界 90407bab12 Fix DNS routing 2022-09-04 12:49:38 +08:00
世界 fa9450da1e Fix write trojan udp 2022-09-03 16:58:55 +08:00
世界 baa3c2f735 Update documentation for dial fields 2022-09-03 13:02:41 +08:00
世界 273652ae23 Merge dialer options 2022-09-03 12:55:10 +08:00
世界 e290aaaf5c Fix dial parallel in direct outbound 2022-09-03 12:01:48 +08:00
世界 dd1f222840 Fix write zero 2022-09-03 09:25:30 +08:00
void aire()and世界 c22d4a85c0 Fix documentation typo (#60) 2022-09-02 19:04:03 +08:00
世界 65df98a60d Add ws compatibility test 2022-09-01 20:32:47 +08:00
世界 77bb8c2ae8 Fix server install script 2022-09-01 20:32:47 +08:00
世界 0c331b5fea Add with_wireguard to default server tag 2022-09-01 20:16:20 +08:00
世界 97de31e957 Move unstable branch to dev-next 2022-08-31 23:45:42 +08:00
0x7d274284andGitHub 9bc37de02c Fix documentation typo (#57) 2022-08-31 23:42:36 +08:00
世界 4f805ce45f Fix install documentation 2022-08-31 23:37:30 +08:00
世界 abbff39758 Fix write log timestamp 2022-08-31 23:35:43 +08:00
世界 457f13639a Update documentation 2022-08-31 14:34:32 +08:00
世界andGitHub 73746383cc Add shadowtls (#49)
* Add shadowtls outbound

* Add shadowtls inbound

* Add shadowtls example

* Add shadowtls documentation
2022-08-31 14:21:53 +08:00
dyhkwongandGitHub 917c4f0e91 darwin pf support (#52) 2022-08-31 14:21:37 +08:00
世界 5fe5646b6f Refactor outbound documentation 2022-08-31 13:42:30 +08:00
世界 cb523dd454 Fix process_name rule item 2022-08-31 12:51:38 +08:00
世界 ced67719a9 Refactor inbound documetation 2022-08-31 12:50:26 +08:00
世界 421b3ba7a6 Fix smux session status 2022-08-31 10:00:15 +08:00
dyhkwongandGitHub 664c6b68b6 Add process_path rule item (#51)
* process matching supports full path
* Remove strings.ToLower
2022-08-30 10:44:40 +08:00
世界 38a69dac07 Fix socksaddr type condition 2022-08-29 19:58:58 +08:00
世界 56119da3e0 Add chained inbound support 2022-08-29 19:50:28 +08:00
世界 1c6d039e3f Fix inject conn 2022-08-29 19:02:41 +08:00
0x7d274284andGitHub 06cd8f8117 Fix issue template (#48)
The correct command to get the version is `sing-box version`
2022-08-29 16:52:15 +08:00
世界 a008f5f117 Fix search android package in non-owner users 2022-08-29 12:02:29 +08:00
世界 c4a7d8d209 Add grpc compatibility test 2022-08-29 10:15:25 +08:00
世界 4ae78c2db8 Fix log item on document menu 2022-08-28 12:47:23 +08:00
HellojackandGitHub 78a363ba05 Minor fixes (#45)
* Cleanup code
* Fix documentation typo
2022-08-28 12:40:44 +08:00
世界 301512ee4b Update dependencies 2022-08-28 12:21:22 +08:00
世界 7d608c54e6 Add docker image 2022-08-28 00:23:41 +08:00
世界 9dc003c87b Simplify server installation 2022-08-28 00:23:41 +08:00
世界 0e1502ca6c Update documentation 2022-08-28 00:23:41 +08:00
HellojackandGitHub 077969c709 Add gun-lite gRPC implementation (#44) 2022-08-27 21:05:15 +08:00
世界 c169f1b0c7 Fix sniff override destination 2022-08-27 14:37:14 +08:00
rand0mgh0standGitHub efff61021c Fix documentation for socks inbound (#42) 2022-08-27 13:16:04 +08:00
世界 56e0ffeb3a Add vmess packetaddr option 2022-08-27 11:28:01 +08:00
世界 4df3843d86 Add documentation for strict_route 2022-08-27 09:31:17 +08:00
rand0mgh0standGitHub a5d04de985 docs-zh-CN: use English for License section (#40) 2022-08-26 23:21:32 +08:00
世界 731e7fab95 Move documentation branch to main 2022-08-26 21:53:46 +08:00
世界 bfcf1017f0 Add strict_route option 2022-08-26 21:53:08 +08:00
世界 a0d35cf3dc Fix dns hijack on android
iproute2 on android does not support port rules
2022-08-26 21:05:45 +08:00
世界 1e596c25b1 Fix TLS documentation 2022-08-26 18:36:56 +08:00
世界 0bcd2df9c6 Revert linux process searcher 2022-08-26 17:36:06 +08:00
世界 f320a584f6 Initial release 2022-08-26 16:40:37 +08:00
世界 4ea259a94f Fix read DNS message 2022-08-26 13:35:27 +08:00
世界 330826f597 Fix ipv6 route on linux 2022-08-26 12:30:31 +08:00
世界 b0d01c209e Update documentation 2022-08-26 11:10:02 +08:00
世界 8584538e81 Cleanup vmessws 2022-08-26 10:22:29 +08:00
世界 c015310ddb Cleanup vmesshttp 2022-08-26 08:41:45 +08:00
世界 477a730322 Update documentation 2022-08-25 22:49:23 +08:00
世界 b05ead5709 Improve ip_cidr rule 2022-08-25 22:23:26 +08:00
世界 82cd08371a Add contributing documentation 2022-08-25 21:08:29 +08:00
世界 9c7910e75c Fix route connections 2022-08-25 20:48:59 +08:00
世界 273a6b6ad5 Fix ipv6 route on linux 2022-08-25 18:57:36 +08:00
世界 cc353e0d81 Fix http proxy with compressed response 2022-08-25 18:40:13 +08:00
世界 361076a5d5 Fix issue template 2022-08-25 18:40:13 +08:00
世界 8f67ed0750 Fix bind_address 2022-08-25 14:50:10 +08:00
Steven TangandGitHub 9d151eb86a Fix typo in features.md (#32) 2022-08-25 13:42:22 +08:00
zakuwakiand世界 cd29049889 Add trojan fallback for ALPN #31 2022-08-25 13:37:32 +08:00
世界 66e51c5bfb Let vmess use zero instead of auto if TLS enabled 2022-08-25 11:51:17 +08:00
世界 b5d4b267e2 Suppress expected error 2022-08-25 11:02:27 +08:00
世界 9af746ba2f Remove TLS requirement on gRPC server 2022-08-25 10:52:16 +08:00
世界 6b7e9f7949 Close websocket conn gracefully 2022-08-25 10:46:14 +08:00
世界 df073989d2 Add stale workflow 2022-08-25 10:24:11 +08:00
世界 d3e6be3980 Update documentation 2022-08-25 10:04:51 +08:00
ReeceandGitHub c5bee2c2a2 Fix zh-CN document symbol and format (#29) 2022-08-25 09:45:22 +08:00
世界 de944ef795 Initial zh-CN document translation: outbound 2022-08-24 21:02:28 +08:00
世界 a6a3038fd0 Fix early close on windows and catch any 2022-08-24 19:03:15 +08:00
世界 41d9c0d23a Initial zh-CN document translation: inbound 2022-08-24 18:43:39 +08:00
世界 52107ffa56 Initial zh-CN document translation: shared 2022-08-24 17:39:37 +08:00
世界 d0fc15ca54 Add ACME EAB support 2022-08-24 17:06:28 +08:00
世界 7d7acacaf5 Initial zh-CN document translation: route 2022-08-24 16:56:29 +08:00
世界 484f0bb567 Initial zh-CN document translation: DNS 2022-08-24 16:37:06 +08:00
HellojackandGitHub 76f41e5731 Fix TLS insecure (#27) 2022-08-24 16:11:41 +08:00
世界 5732c92943 Fix close non-duplex connections 2022-08-24 14:32:18 +08:00
世界 71c7f4b35d Initial zh-CN document translation: examples 2022-08-24 13:14:12 +08:00
世界 596a34fe2c Initial zh-CN document translation: FAQ 2022-08-24 13:04:47 +08:00
世界 336d9485c4 Initial zh-CN document translation 2022-08-24 12:45:51 +08:00
世界 a1223ce227 Fix unix search path 2022-08-24 12:27:36 +08:00
世界 91cc9534d2 Fix naive padding 2022-08-24 10:21:56 +08:00
世界 1b0f135d7c Update documentation 2022-08-24 00:39:25 +08:00
世界 4eec66d21b Check configuration before reload 2022-08-23 23:44:44 +08:00
世界 a69eddc618 Add proxy protocol support 2022-08-23 21:07:35 +08:00
世界 fe25c4b2dd Handle SIGHUP signal 2022-08-23 19:56:28 +08:00
世界 7288d74b8d Parse X-Forward-For in HTTP requests 2022-08-23 19:53:04 +08:00
世界 b7f61e0993 Fix test naive inbound with nginx 2022-08-23 14:41:31 +08:00
世界 1078439201 Accept HTTP1 in naive inbound 2022-08-23 13:25:03 +08:00
世界 227a6e9921 Add v2ray transport to trojan 2022-08-23 13:24:52 +08:00
世界 fd625f4485 Free memory after start 2022-08-22 23:17:08 +08:00
世界 10a202eb85 Allow http1 in v2ray HTTP transport 2022-08-22 23:02:25 +08:00
世界 46ed01b4c9 Add v2ray HTTP transport 2022-08-22 22:20:19 +08:00
世界 192c360801 Add v2ray QUIC transport 2022-08-22 22:20:19 +08:00
世界 ebc3c54618 Add v2ray WebSocket transport 2022-08-22 22:20:18 +08:00
世界 dbf12fb14d Prepare v2ray client/server transport 2022-08-22 18:57:05 +08:00
世界 fbda05239d Fix clash server early close 2022-08-22 16:33:33 +08:00
世界 68f4a744df Minor fixes 2022-08-22 16:14:53 +08:00
世界 515b350328 Apply bind address to udp connect 2022-08-22 14:35:05 +08:00
世界 6e41cc18f1 Add bind address to outbound options 2022-08-22 14:28:23 +08:00
世界 b6125cb585 Update documentation 2022-08-22 14:19:32 +08:00
世界 045e6d1976 Fix tests 2022-08-22 12:02:16 +08:00
世界 6109040c4c Add strategy setting for each dns server 2022-08-22 12:01:50 +08:00
世界 e18acc7db9 Fix vectorised writer 2022-08-21 22:35:58 +08:00
世界 9ac5648eb8 Add ssh outbound 2022-08-21 22:30:48 +08:00
世界 e883ed3681 Add FAQ page 2022-08-21 22:26:08 +08:00
世界 c2f1cb07af Update release config 2022-08-21 13:03:19 +08:00
世界 f6e163efd7 Fix gvisor udp write back 2022-08-21 11:40:04 +08:00
世界 990a80c2d3 Add tor outbound 2022-08-21 01:06:34 +08:00
世界 0686ad25fd Fix typo in documentation 2022-08-20 21:16:14 +08:00
世界 fb03bb3edd Add trojan connection fallback 2022-08-20 21:08:53 +08:00
世界 53ce452767 Wait a second before check route update 2022-08-20 13:42:28 +08:00
世界 a5f0041cf6 Skip bind connection with private destination to interface 2022-08-20 13:31:15 +08:00
世界 3f41b14d3b Fix write socks5 username password auth request 2022-08-20 13:26:49 +08:00
世界 7909d58f86 Improve process searcher 2022-08-20 12:11:27 +08:00
世界 dcdf6fae31 Fix route on android 2022-08-20 10:27:13 +08:00
世界 a3ce808911 Start outbounds before router 2022-08-20 09:13:00 +08:00
世界 27392068ae Fix read packages in android 13 2022-08-20 03:05:50 +08:00
世界 781952ab3c Attempt to unwrap ip-in-fqdn socksaddr 2022-08-20 00:01:08 +08:00
世界 f3b372a7d0 Update documentation 2022-08-19 22:30:12 +08:00
世界 2cbdc0354f Fix acme issuer 2022-08-19 18:42:12 +08:00
世界 bd88c48b11 Add with_acme to server scripts 2022-08-19 17:48:56 +08:00
世界 467065951c Update gVisor to 20220815.0 2022-08-19 17:47:54 +08:00
世界 cbbdd5bed5 Allow read config from stdin 2022-08-19 15:43:13 +08:00
世界andGitHub 9bfef39b32 Add hysteria and acme TLS certificate issuer (#18)
* Add hysteria client/server
* Add acme TLS certificate issuer
2022-08-19 15:42:57 +08:00
世界 d854a567cc Add back dns concurrent write lock 2022-08-19 10:51:26 +08:00
世界 7fb6788547 Fix darwin tun 2022-08-19 08:35:08 +08:00
世界 6522c0affb Fix log to file 2022-08-19 08:26:26 +08:00
世界 4044d41e0f Fix format 2022-08-19 08:26:26 +08:00
世界 1b261e843c Add write lock to shadowsocks aead writer 2022-08-19 08:26:26 +08:00
世界 d4dcd879ec Fix close shadowsocks server conn 2022-08-18 23:16:05 +08:00
世界 83860510fd Fix find process with lwip stack 2022-08-18 10:10:30 +08:00
Tianling ShenandGitHub e9e002dc67 Fix geosite path (#17)
`geoIPOptions` -> `geositeOptions`

Signed-off-by: Tianling Shen <i@cnsztl.eu.org>
2022-08-18 10:00:56 +08:00
世界 ae1e78b409 Fix lint 2022-08-17 20:15:35 +08:00
世界 e0aaddfe45 Improve async dns transports 2022-08-17 20:10:59 +08:00
世界 dbca1fc507 Update documentation 2022-08-17 15:19:10 +08:00
世界 90328934f3 Add ip_version rule item 2022-08-16 23:47:14 +08:00
世界 1ef9449ca0 Add wireguard outbound and test 2022-08-16 23:39:11 +08:00
世界 0e38106312 Improve tproxy udp write back 2022-08-16 18:37:37 +08:00
世界 26e0c91fe3 Update exec/control usage 2022-08-16 18:19:48 +08:00
世界 29a9b1b84a Fix include_android_user option 2022-08-16 12:16:59 +08:00
世界 32b1fc67f1 Fix copy stream 2022-08-15 16:53:12 +08:00
世界 be04eb3bea Add android package rules support in tun routing 2022-08-15 11:44:59 +08:00
世界 91fd4bacbd Add uid and android user rules support in tun routing 2022-08-15 11:41:00 +08:00
世界 740eb96fa8 Improve cmd 2022-08-13 18:37:51 +08:00
HellojackandGitHub ce02da8698 Fix documentation typo (#13) 2022-08-13 11:01:22 +08:00
世界 f215b21d51 Fix dns concurrent write 2022-08-13 11:00:15 +08:00
世界 c1dad92914 Improve build 2022-08-12 22:58:28 +08:00
世界 86bfe052ac Add UoT option to socks outbound too 2022-08-12 17:55:52 +08:00
世界 0a84f60c32 Improve smux write 2022-08-12 16:49:25 +08:00
HellojackandGitHub 8421a979b4 Add CGO hint in version cmd (#12) 2022-08-12 15:46:26 +08:00
世界 0905d87cc8 Minor fixes 2022-08-12 12:13:57 +08:00
世界 de9fe64751 Update dependencies 2022-08-12 10:58:16 +08:00
世界 cc5440aa67 Refactor bufio 2022-08-11 23:59:22 +08:00
世界 aa0cd04622 Show memory stats in debug 2022-08-11 12:42:17 +08:00
世界 e733bfb803 Enable QUIC in server scripts 2022-08-11 11:45:33 +08:00
世界 1a34319c95 Add back UoT support 2022-08-11 10:36:28 +08:00
ReeceandGitHub 2e675c2808 Fix documentation typo (#10) 2022-08-11 10:06:10 +08:00
世界 0441d2cdd7 Update documentation 2022-08-10 21:21:02 +08:00
世界 312d89980b Add naive inbound and test 2022-08-10 20:36:29 +08:00
iKirbyandGitHub 6d5d74e011 Fix default dns server option (#9) 2022-08-10 12:18:03 +08:00
世界 daca216fe4 Remove incorrect warning 2022-08-09 17:27:22 +08:00
世界 ae40258f87 Update dependencies 2022-08-09 15:55:16 +08:00
世界 266416183e Improve cmd 2022-08-09 14:49:17 +08:00
世界 c0c91cd191 Fix direct connect 2022-08-09 14:48:08 +08:00
世界 25cbcafb90 Improve wintun read 2022-08-08 21:35:59 +08:00
世界 3594fd4593 Update documentation 2022-08-08 21:10:37 +08:00
世界 c95e23d755 Fix copy early conn 2022-08-08 20:56:53 +08:00
世界 769521cafe Add trojan inbound/outbound 2022-08-08 09:08:12 +08:00
世界 6e057a3318 Simplify vmess test 2022-08-08 09:08:12 +08:00
世界 70842ad0ac Fix mux overflow 2022-08-08 08:09:17 +08:00
世界 37771a57e7 Add optional LWIP tun stack support 2022-08-07 17:21:49 +08:00
世界 44732053d0 Update gVisor to 20220801.0 2022-08-07 14:58:07 +08:00
世界 2d6546705a Fix linux unprivileged tun usage 2022-08-07 11:21:10 +08:00
世界 93fb7aa371 Fix wininet wrapper 2022-08-06 17:28:51 +08:00
世界 02832fb136 Add tun support for macOS 2022-08-05 17:02:51 +08:00
世界 ed900a990e Add set system proxy support for macOS 2022-08-05 16:55:59 +08:00
世界 ed32fa60df Add multiplexer for vmess 2022-08-04 10:38:20 +08:00
世界 a6e5654436 Improve multiplex log 2022-08-04 09:12:57 +08:00
世界 ae73634640 Add unsafe tag to multiplexer writer 2022-08-04 00:00:22 +08:00
世界 86442662ea Add documentation for simple linux installation 2022-08-03 22:23:40 +08:00
世界 cc17627a0b Improve multiplexer 2022-08-03 22:01:18 +08:00
世界 b1fa60eabc Improve dns log 2022-08-03 20:17:05 +08:00
世界 07eff298ab Update WriteToUDPAddrPort usage since fixed by go1.18.5 2022-08-03 17:49:04 +08:00
世界 575dce6fb0 Update task usage 2022-08-03 17:44:19 +08:00
世界 5c756f9000 Replace netlink with fork 2022-08-03 12:02:22 +08:00
世界 56e63609c6 Fix windows tun leak memory 2022-08-03 10:14:00 +08:00
世界 cf425de106 Minor fixes 2022-08-02 18:47:23 +08:00
世界 49f4145b23 Improve mux server 2022-08-02 15:11:51 +08:00
世界 4ecb7d2c04 Fix buffer usage 2022-08-02 13:43:25 +08:00
世界 ffec06e730 Fix dns sniff 2022-08-02 13:42:31 +08:00
世界 c7a9272113 Add documentation for vmess 2022-08-01 17:02:13 +08:00
世界 d0c9fdcf66 Add vmess legacy server and test 2022-08-01 12:23:34 +08:00
世界 15c8853f66 Fix netlink subscription leak 2022-07-31 19:58:32 +08:00
世界 9fbaff4b23 Make socks request buffered 2022-07-31 19:58:32 +08:00
世界 2a0499d8fc Close tun endpoint faster 2022-07-31 19:58:32 +08:00
世界 fb16f5a2d6 Add retry for mux stream open 2022-07-31 18:08:24 +08:00
世界 1c50521985 Fix tcp keep alive 2022-07-31 09:53:29 +08:00
世界 770e58a79d Fix dns outbound 2022-07-31 08:48:56 +08:00
世界 d182ec0430 Add omitempty for listen_port 2022-07-30 22:05:06 +08:00
世界 235d9ec12a Add TLS certificate reload 2022-07-30 22:04:01 +08:00
世界 e0eaae9b69 Add documentation for shadowsocks multiplexer 2022-07-30 21:23:45 +08:00
世界 0dedbbf37a Fix copy with src buffer to headroom writer 2022-07-30 21:23:45 +08:00
世界 ee6f271456 Minor fixes 2022-07-30 14:50:33 +08:00
世界 81fc09d190 Improve error processing 2022-07-30 09:57:02 +08:00
世界 336bceeb97 Add linux server scripts 2022-07-30 09:04:01 +08:00
世界 1570c3b6f5 Use connect for quic/dns udp connections 2022-07-30 09:04:01 +08:00
世界 10531c9f9a Add multiplexer 2022-07-30 09:04:01 +08:00
世界 8e8b1b974e Hide dns outbound in clash-dashboard 2022-07-28 16:40:06 +08:00
世界 806ec58d43 Remove urltest outbound 2022-07-28 16:36:31 +08:00
世界 4bd6eee63e Add shadowsocks-multiuser control api 2022-07-27 21:59:40 +08:00
世界 70f48ddc3f Update documentation 2022-07-27 12:13:31 +08:00
世界 f0a53b5cae Add endpoint independent nat support for tun inbound 2022-07-27 11:59:36 +08:00
世界 3a7a4bab12 Remove go-json 2022-07-26 13:53:25 +08:00
世界 0abf9a06c3 Add optional DoT, DoH3 support 2022-07-26 12:48:10 +08:00
世界 46744ec75b Fix clash tracker timeout 2022-07-26 06:56:24 +08:00
世界 832f906700 Improve udp timeout 2022-07-25 22:15:16 +08:00
世界 c3053249fe Print stack if no context 2022-07-25 16:18:22 +08:00
世界 b23a8dd0a5 Fix format command 2022-07-25 16:18:11 +08:00
世界 6bac91c849 Fix direct udp outbound 2022-07-25 16:18:11 +08:00
世界 18bdfbf187 Improve config struct 2022-07-25 16:18:11 +08:00
世界 94ae7403ef Improve tls dialer and listener 2022-07-25 16:18:11 +08:00
世界 3241e5e968 Add runtime warnings 2022-07-25 07:19:15 +08:00
世界 d52456b74e Add retry for linux process search 2022-07-24 21:43:05 +08:00
世界 223f68b7c3 Add default tcp keep alive settings 2022-07-24 21:29:39 +08:00
世界 7fa1f2dcac Improve udp dns close 2022-07-24 21:25:41 +08:00
世界 698da23a10 Add lint workflow 2022-07-24 21:22:19 +08:00
世界 fd8359df77 Add with_std_json build tag 2022-07-24 21:22:19 +08:00
世界 a56f4bda5c Add route.default_mark option 2022-07-24 17:46:25 +08:00
世界 2bea4818b5 Add source_port_range/port_range rule item 2022-07-24 16:21:35 +08:00
世界 68e8c59225 Add disable_cache option to dns rule 2022-07-24 16:21:31 +08:00
世界 6d8e3235ac Add rcode dns transport 2022-07-24 16:21:31 +08:00
世界 d0f1d7f3dc Add invert rule item 2022-07-24 16:21:31 +08:00
世界 fbdf3e4b38 Fix direct inbound 2022-07-24 13:42:58 +08:00
世界 783ff628db Add process_name/package_name/user/user_id rule item 2022-07-23 21:28:13 +08:00
世界 8009f581fe Fix urltest log 2022-07-23 10:28:32 +08:00
世界 5ab60c4004 Update documentations 2022-07-23 09:29:37 +08:00
世界 d53056360b Deprecate dns_hijack and dns inbound 2022-07-23 09:15:47 +08:00
世界 466912ad4a Improve 4in6 processing 2022-07-22 17:57:23 +08:00
世界 c45e229ce2 Fix tproxy inbound 2022-07-22 16:18:56 +08:00
世界 cfe2a0d4f3 Fix log format 2022-07-22 14:28:29 +08:00
世界 2d78fbb314 Fix dns inbound 2022-07-22 14:25:04 +08:00
世界 17ff830fed Add documentation for selector/urltest outbound 2022-07-22 14:07:27 +08:00
世界 1fef7d93f2 Add urltest outbound 2022-07-22 13:51:08 +08:00
世界 1f3cc0ca7d Expand env in clash external-ui 2022-07-22 09:49:35 +08:00
世界 15ee00c24b Fix integration with clash-dashboard 2022-07-22 09:41:12 +08:00
世界 544fca8257 Add selector outbound 2022-07-21 21:13:16 +08:00
世界 2946ee1267 Improve socksaddr 2022-07-20 22:05:11 +08:00
世界 585e3b325c Minor fixes 2022-07-20 13:46:47 +08:00
世界 c7c66c49ed Add documentation for clash_api 2022-07-20 07:37:50 +08:00
世界 98adef316a Make clash api and gVisor optional 2022-07-20 07:12:40 +08:00
世界 5905ad3278 Add basic clash api 2022-07-19 22:45:55 +08:00
世界 eacf611ee9 Improve connection timeout 2022-07-18 20:53:13 +08:00
世界 f7fa342b31 Add vmess compatibility test 2022-07-18 20:14:53 +08:00
世界 4fce3cff24 Add vmess inbound/outbound 2022-07-18 12:32:31 +08:00
世界 02ef795581 Add user rule item 2022-07-17 17:38:11 +08:00
世界 392a9da692 Exclude gVisor for unsupported arch 2022-07-17 11:16:13 +08:00
世界 9debfd4cc6 Disable gVisor log 2022-07-17 11:15:56 +08:00
世界 175f1f2ba7 Improve workflow build 2022-07-17 09:54:34 +08:00
世界 27423768ac Update dependencies 2022-07-17 09:18:36 +08:00
世界 92df9ff065 Add debug build for all arch 2022-07-17 09:11:23 +08:00
世界 7339521397 Fix build 2022-07-17 08:48:57 +08:00
世界 57a9928fdb Minor fixes 2022-07-16 22:03:35 +08:00
世界 cc711a141a Add stun sniffer 2022-07-16 12:01:02 +08:00
世界 acccd2968c Fix private addr check 2022-07-16 10:19:18 +08:00
世界 9908b4ee6c Fix linux tun 2022-07-15 22:40:42 +08:00
世界 6b4eeda413 Fix set_system_proxy when using sudo 2022-07-15 18:30:01 +08:00
世界 daaa089b31 Fix tun auto_route on android 2022-07-15 18:29:29 +08:00
世界 0c5e07b2d2 Add route.default_interface option 2022-07-15 15:00:54 +08:00
世界 12795bc504 Add ss aead tests 2022-07-15 11:18:19 +08:00
世界 00f1faeea5 Add redir tproxy and dns inbound 2022-07-15 08:42:02 +08:00
世界 7686fd0ecb Improve bind interface 2022-07-14 23:11:53 +08:00
世界 a257c481c3 Add set_system_proxy for linux and android 2022-07-14 20:32:17 +08:00
世界 1d9913604c Add documentation for set_system_proxy 2022-07-14 14:41:35 +08:00
世界 1314345f28 Add set_system_proxy option for windows 2022-07-14 14:41:35 +08:00
世界 901a41d350 Add tun inbound for windows 2022-07-13 22:41:21 +08:00
世界 e3b186733e Refactor log 2022-07-12 17:44:12 +08:00
世界 39c6784ba7 Improve copy early conn 2022-07-11 20:55:14 +08:00
世界 a4ad38a0a9 Fix tcp sniffing 2022-07-11 20:37:57 +08:00
世界 3d16df288c Migrate components to library 2022-07-11 18:44:59 +08:00
世界 f548511d7e Make dns.strategy take effect in dns exchange 2022-07-11 13:21:17 +08:00
世界 90450c4d06 Fix hijack_dns 2022-07-11 12:56:57 +08:00
世界 730599470e Remove ToString0[T] usage to fix golangci-lint 2022-07-10 22:00:28 +08:00
世界 725b15175d Fix create gVisor endpoint 2022-07-10 19:17:44 +08:00
世界 3d5bd9eb1f Add documentation and example for linux tun 2022-07-10 16:44:12 +08:00
世界 70901c0946 Minor fixes 2022-07-10 16:19:42 +08:00
世界 ddfae8cd07 Add hijack_dns for tun 2022-07-10 10:14:45 +08:00
世界 a34057753c Add auto_route and auto_detect_interface for linux 2022-07-10 08:18:52 +08:00
世界 08e03345d5 Fix quic sniff irl 2022-07-10 07:52:33 +08:00
世界 6795fe15dd Add tun inbound for linux 2022-07-09 22:44:18 +08:00
世界 cee09c6e9d Fix pages 2022-07-09 15:09:50 +08:00
世界 e518a26dc2 Add benchmark page 2022-07-09 15:00:31 +08:00
世界 4a7739393f Fix direct udp 2022-07-09 10:28:22 +08:00
世界 b1ad598def Add bug template 2022-07-09 09:34:16 +08:00
世界 a41127179d Declare required fields in the documentation 2022-07-09 09:28:54 +08:00
世界 34a99b5509 Add debug workflow 2022-07-09 09:02:06 +08:00
世界 3a298245a9 Add shadowsocks tests 2022-07-09 08:59:34 +08:00
世界 2cc746aafe Update gci format 2022-07-08 23:03:57 +08:00
世界 1053bcaada Fix handle missing err on quic sniff 2022-07-08 22:49:17 +08:00
世界 1b05b56f04 Add examples 2022-07-08 22:45:06 +08:00
世界 4bab84be67 Add route documentation 2022-07-08 20:20:38 +08:00
世界 b383757742 Add outbound documentation 2022-07-08 19:58:56 +08:00
世界 b39a776785 Add inbound documentation 2022-07-08 18:42:29 +08:00
世界 bd914916b3 Add README 2022-07-08 18:41:18 +08:00
世界 493f517d93 Add log and dns documentation 2022-07-08 18:41:18 +08:00
世界 0cc16a7836 Add dial parallel for outbound dialer 2022-07-08 13:08:29 +08:00
世界 f121a6d723 Improve load geosite 2022-07-08 11:00:46 +08:00
世界 b91ed698cd Add resolver for inbound 2022-07-07 23:45:05 +08:00
世界 f65f3f1ba0 Add resolver for outbound dialer 2022-07-07 21:47:21 +08:00
世界 d921797e3c Add disableCache/disableExpire option for dns client 2022-07-06 23:43:20 +08:00
世界 001dc5f62c Add dns client 2022-07-06 23:14:19 +08:00
世界 63e1b53a49 Add dns transports 2022-07-06 19:01:46 +08:00
世界 a3a61c174f Remove lint action 2022-07-06 15:45:13 +08:00
世界 9107a2fe33 Update gci format 2022-07-06 15:01:09 +08:00
世界 070d3c56ed Add protect path dialer option 2022-07-06 14:45:56 +08:00
世界 8867768a7d Rename find path 2022-07-06 14:44:51 +08:00
世界 3e2dddfb16 Add domain sniffer 2022-07-06 12:39:44 +08:00
世界 625bc649ee Refactor geo resources 2022-07-05 13:23:47 +08:00
世界 f9d8fa2b91 Add geosite 2022-07-05 09:05:35 +08:00
世界 86456b9cbc Add geosite protocol 2022-07-04 19:39:58 +08:00
世界 b8e45853c0 Fix route 2022-07-04 19:34:45 +08:00
世界 dfde4e34c0 Add version command 2022-07-04 17:14:15 +08:00
世界 bcf0bb26a7 Add check/format command 2022-07-04 16:59:27 +08:00
世界 c33a079c88 Refine log output 2022-07-04 16:45:32 +08:00
世界 616b599104 Add domain_regex rule 2022-07-04 15:51:41 +08:00
世界 6af52f8bb6 Shadowsocks multi-user/relay inbound 2022-07-04 15:34:43 +08:00
世界 13c069740f Add http/block outbound & Improve route 2022-07-04 08:16:25 +08:00
世界 f510323dca Refactor struct & Add override dialer options 2022-07-03 20:59:25 +08:00
世界 ffedce0f5f Refactor json 2022-07-03 19:43:27 +08:00
世界 5fc6e2c0db Add internal private geoip rule 2022-07-03 15:57:09 +08:00
世界 388b9f06e9 Add socks outbound 2022-07-03 13:14:49 +08:00
世界 d8cff01c4a Ordered json output & Disallow unknown fields 2022-07-03 11:28:15 +08:00
世界 71d9772913 Add format config support 2022-07-03 03:42:57 +08:00
世界 add5896378 Invalid config check 2022-07-03 01:57:04 +08:00
世界 ad01befeee Implement route rules 2022-07-02 23:19:14 +08:00
世界 0e9bd9b091 Inbound rule support 2022-07-02 14:07:50 +08:00
世界 737a61be66 Refactor adapter 2022-07-01 19:37:41 +08:00
世界 cfa35e5a92 Init commit 2022-07-01 16:58:18 +08:00
393 changed files with 3252 additions and 20333 deletions
+1 -1
View File
@@ -12,7 +12,7 @@ body:
required: true required: true
- label: Yes, I've searched similar issues on GitHub and didn't find any. - label: Yes, I've searched similar issues on GitHub and didn't find any.
required: true required: true
- label: Yes, I've included all information below (version, **FULL** config, **FULL** log, etc). - label: Yes, I've included all information below (version, config, log, etc).
required: true required: true
- type: textarea - type: textarea
-28
View File
@@ -1,28 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"commitMessagePrefix": "[dependencies]",
"extends": [
"config:base",
":disableRateLimiting"
],
"baseBranches": [
"dev-next"
],
"golang": {
"enabled": false
},
"packageRules": [
{
"matchManagers": [
"github-actions"
],
"groupName": "github-actions"
},
{
"matchManagers": [
"dockerfile"
],
"groupName": "Dockerfile"
}
]
}
+16 -35
View File
@@ -3,7 +3,7 @@ name: Debug build
on: on:
push: push:
branches: branches:
- main-next - dev
- dev-next - dev-next
paths-ignore: paths-ignore:
- '**.md' - '**.md'
@@ -11,7 +11,7 @@ on:
- '!.github/workflows/debug.yml' - '!.github/workflows/debug.yml'
pull_request: pull_request:
branches: branches:
- main-next - dev
- dev-next - dev-next
jobs: jobs:
@@ -19,20 +19,24 @@ jobs:
name: Debug build name: Debug build
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Cancel previous
uses: styfle/cancel-workflow-action@0.7.0
with:
access_token: ${{ github.token }}
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Get latest go version - name: Get latest go version
id: version id: version
run: | run: |
echo go_version=$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g') >> $GITHUB_OUTPUT echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
- name: Setup Go - name: Setup Go
uses: actions/setup-go@v3 uses: actions/setup-go@v2
with: with:
go-version: ${{ steps.version.outputs.go_version }} go-version: ${{ steps.version.outputs.go_version }}
- name: Cache go module - name: Cache go module
uses: actions/cache@v3 uses: actions/cache@v2
with: with:
path: | path: |
~/go/pkg/mod ~/go/pkg/mod
@@ -49,26 +53,6 @@ jobs:
- name: Run Test - name: Run Test
run: | run: |
go test -v ./... go test -v ./...
build_go118:
name: Debug build (Go 1.18)
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Go
uses: actions/setup-go@v3
with:
go-version: 1.18.10
- name: Cache go module
uses: actions/cache@v3
with:
path: |
~/go/pkg/mod
key: go118-${{ hashFiles('**/go.sum') }}
- name: Run Test
run: make
cross: cross:
strategy: strategy:
matrix: matrix:
@@ -142,9 +126,6 @@ jobs:
- name: linux-mips64el - name: linux-mips64el
goos: linux goos: linux
goarch: mips64le goarch: mips64le
- name: linux-s390x
goos: linux
goarch: s390x
# darwin # darwin
- name: darwin-amd64 - name: darwin-amd64
goos: darwin goos: darwin
@@ -185,19 +166,19 @@ jobs:
TAGS: with_clash_api,with_quic TAGS: with_clash_api,with_quic
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Get latest go version - name: Get latest go version
id: version id: version
run: | run: |
echo go_version=$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g') >> $GITHUB_OUTPUT echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
- name: Setup Go - name: Setup Go
uses: actions/setup-go@v3 uses: actions/setup-go@v2
with: with:
go-version: ${{ steps.version.outputs.go_version }} go-version: ${{ steps.version.outputs.go_version }}
- name: Cache go module - name: Cache go module
uses: actions/cache@v3 uses: actions/cache@v2
with: with:
path: | path: |
~/go/pkg/mod ~/go/pkg/mod
@@ -206,7 +187,7 @@ jobs:
id: build id: build
run: make run: make
- name: Upload artifact - name: Upload artifact
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v2
with: with:
name: sing-box-${{ matrix.name }} name: sing-box-${{ matrix.name }}
path: sing-box* path: sing-box*
+13 -15
View File
@@ -1,5 +1,8 @@
name: Build Docker Images name: Build Docker Images
on: on:
push:
tags:
- v*
workflow_dispatch: workflow_dispatch:
inputs: inputs:
tag: tag:
@@ -9,37 +12,32 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
- name: Setup Docker Buildx - name: Setup Docker Buildx
uses: docker/setup-buildx-action@v2 uses: docker/setup-buildx-action@v1
- name: Setup QEMU for Docker Buildx
uses: docker/setup-qemu-action@v2
- name: Login to GitHub Container Registry - name: Login to GitHub Container Registry
uses: docker/login-action@v2 uses: docker/login-action@v1
with: with:
registry: ghcr.io registry: ghcr.io
username: ${{ github.repository_owner }} username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Docker metadata - name: Docker metadata
id: metadata id: metadata
uses: docker/metadata-action@v4 uses: docker/metadata-action@v3
with: with:
images: ghcr.io/sagernet/sing-box images: ghcr.io/sagernet/sing-box
- name: Get tag to build - name: Get tag to build
id: tag id: tag
run: | run: |
echo "latest=ghcr.io/sagernet/sing-box:latest" >> $GITHUB_OUTPUT
if [[ -z "${{ github.event.inputs.tag }}" ]]; then if [[ -z "${{ github.event.inputs.tag }}" ]]; then
echo "versioned=ghcr.io/sagernet/sing-box:${{ github.ref_name }}" >> $GITHUB_OUTPUT echo ::set-output name=tag::ghcr.io/sagernet/sing-box:${{ github.ref_name }}
else else
echo "versioned=ghcr.io/sagernet/sing-box:${{ github.event.inputs.tag }}" >> $GITHUB_OUTPUT echo ::set-output name=tag::ghcr.io/sagernet/sing-box:${{ github.event.inputs.tag }}
fi fi
- name: Build and release Docker images - name: Build and release Docker images
uses: docker/build-push-action@v4 uses: docker/build-push-action@v2
with: with:
platforms: linux/386,linux/amd64,linux/arm64,linux/s390x platforms: linux/386,linux/amd64
target: dist target: dist
tags: | tags: ${{ steps.tag.outputs.tag }}
${{ steps.tag.outputs.latest }} push: true
${{ steps.tag.outputs.versioned }}
push: true
+14 -9
View File
@@ -3,40 +3,45 @@ name: Lint
on: on:
push: push:
branches: branches:
- main-next - dev
- dev-next
paths-ignore: paths-ignore:
- '**.md' - '**.md'
- '.github/**' - '.github/**'
- '!.github/workflows/lint.yml' - '!.github/workflows/debug.yml'
pull_request: pull_request:
branches: branches:
- main-next - dev
- dev-next
jobs: jobs:
build: build:
name: Build name: Build
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Cancel previous
uses: styfle/cancel-workflow-action@0.7.0
with:
access_token: ${{ github.token }}
- name: Checkout - name: Checkout
uses: actions/checkout@v3 uses: actions/checkout@v2
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Get latest go version - name: Get latest go version
id: version id: version
run: | run: |
echo go_version=$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g') >> $GITHUB_OUTPUT echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
- name: Setup Go - name: Setup Go
uses: actions/setup-go@v3 uses: actions/setup-go@v2
with: with:
go-version: ${{ steps.version.outputs.go_version }} go-version: ${{ steps.version.outputs.go_version }}
- name: Cache go module - name: Cache go module
uses: actions/cache@v3 uses: actions/cache@v2
with: with:
path: | path: |
~/go/pkg/mod ~/go/pkg/mod
key: go-${{ hashFiles('**/go.sum') }} key: go-${{ hashFiles('**/go.sum') }}
- name: Get dependencies
run: |
go mod download -x
- name: golangci-lint - name: golangci-lint
uses: golangci/golangci-lint-action@v3 uses: golangci/golangci-lint-action@v3
with: with:
+4 -6
View File
@@ -10,11 +10,9 @@ jobs:
deploy: deploy:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v2
- uses: actions/setup-python@v4 - uses: actions/setup-python@v2
with: with:
python-version: 3.x python-version: 3.x
- run: | - run: pip install mkdocs-material mkdocs-static-i18n
pip install mkdocs-material=="9.*" mkdocs-static-i18n=="0.53" - run: mkdocs gh-deploy -m "{sha}" --force --ignore-version --no-history
- run: |
mkdocs gh-deploy -m "{sha}" --force --ignore-version --no-history
+1 -1
View File
@@ -8,7 +8,7 @@ jobs:
stale: stale:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/stale@v7 - uses: actions/stale@v5
with: 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' 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-stale: 60
+1 -8
View File
@@ -4,11 +4,4 @@
/*.db /*.db
/site/ /site/
/bin/ /bin/
/dist/ /dist/
/sing-box
/sing-box.exe
/build/
/*.jar
/*.aar
/*.xcframework/
.DS_Store
+7 -16
View File
@@ -3,24 +3,15 @@ linters:
enable: enable:
- gofumpt - gofumpt
- govet - govet
- gci # - gci
- staticcheck - staticcheck
- paralleltest - paralleltest
run:
skip-dirs:
- transport/simple-obfs
- transport/clashssr
- transport/cloudflaretls
- transport/shadowtls/tls
- transport/shadowtls/tls_go119
linters-settings: linters-settings:
gci: # gci:
custom-order: true # sections:
sections: # - standard
- standard # - prefix(github.com/sagernet/)
- prefix(github.com/sagernet/) # - default
- default
staticcheck: staticcheck:
go: '1.20' go: '1.19'
+5 -57
View File
@@ -1,7 +1,6 @@
project_name: sing-box project_name: sing-box
builds: builds:
- id: main - main: ./cmd/sing-box
main: ./cmd/sing-box
flags: flags:
- -v - -v
- -trimpath - -trimpath
@@ -10,21 +9,21 @@ builds:
gcflags: gcflags:
- all=-trimpath={{.Env.GOPATH}} - all=-trimpath={{.Env.GOPATH}}
ldflags: ldflags:
- -X github.com/sagernet/sing-box/constant.Version={{ .Version }} -s -w -buildid= - -X github.com/sagernet/sing-box/constant.Commit={{ .ShortCommit }} -s -w -buildid=
tags: tags:
- with_gvisor
- with_quic - with_quic
- with_wireguard - with_wireguard
- with_utls
- with_clash_api - with_clash_api
env: env:
- CGO_ENABLED=0 - CGO_ENABLED=0
targets: targets:
- android_arm64
- android_amd64
- android_amd64_v3
- linux_amd64_v1 - linux_amd64_v1
- linux_amd64_v3 - linux_amd64_v3
- linux_arm64 - linux_arm64
- linux_arm_7 - linux_arm_7
- linux_s390x
- windows_amd64_v1 - windows_amd64_v1
- windows_amd64_v3 - windows_amd64_v3
- windows_386 - windows_386
@@ -33,54 +32,6 @@ builds:
- darwin_amd64_v3 - darwin_amd64_v3
- darwin_arm64 - darwin_arm64
mod_timestamp: '{{ .CommitTimestamp }}' mod_timestamp: '{{ .CommitTimestamp }}'
- id: android
main: ./cmd/sing-box
flags:
- -v
- -trimpath
asmflags:
- all=-trimpath={{.Env.GOPATH}}
gcflags:
- all=-trimpath={{.Env.GOPATH}}
ldflags:
- -X github.com/sagernet/sing-box/constant.Version={{ .Version }} -s -w -buildid=
tags:
- with_gvisor
- with_quic
- with_wireguard
- with_utls
- with_clash_api
env:
- CGO_ENABLED=1
overrides:
- goos: android
goarch: arm
goarm: 7
env:
- CC=armv7a-linux-androideabi19-clang
- CXX=armv7a-linux-androideabi19-clang++
- goos: android
goarch: arm64
env:
- CC=aarch64-linux-android21-clang
- CXX=aarch64-linux-android21-clang++
- goos: android
goarch: 386
env:
- CC=i686-linux-android19-clang
- CXX=i686-linux-android19-clang++
- goos: android
goarch: amd64
goamd64: v1
env:
- CC=x86_64-linux-android21-clang
- CXX=x86_64-linux-android21-clang++
targets:
- android_arm_7
- android_arm64
- android_386
- android_amd64
mod_timestamp: '{{ .CommitTimestamp }}'
snapshot: snapshot:
name_template: "{{ .Version }}.{{ .ShortCommit }}" name_template: "{{ .Version }}.{{ .ShortCommit }}"
archives: archives:
@@ -116,9 +67,6 @@ nfpms:
dst: /etc/systemd/system/sing-box@.service dst: /etc/systemd/system/sing-box@.service
- src: LICENSE - src: LICENSE
dst: /usr/share/licenses/sing-box/LICENSE dst: /usr/share/licenses/sing-box/LICENSE
scripts:
postinstall: release/config/postinstall.sh
postremove: release/config/postremove.sh
source: source:
enabled: false enabled: false
name_template: '{{ .ProjectName }}-{{ .Version }}.source' name_template: '{{ .ProjectName }}-{{ .Version }}.source'
+4 -4
View File
@@ -1,4 +1,4 @@
FROM golang:1.20-alpine AS builder FROM golang:1.19-alpine AS builder
LABEL maintainer="nekohasekai <contact-git@sekai.icu>" LABEL maintainer="nekohasekai <contact-git@sekai.icu>"
COPY . /go/src/github.com/sagernet/sing-box COPY . /go/src/github.com/sagernet/sing-box
WORKDIR /go/src/github.com/sagernet/sing-box WORKDIR /go/src/github.com/sagernet/sing-box
@@ -8,13 +8,13 @@ ENV CGO_ENABLED=0
RUN set -ex \ RUN set -ex \
&& apk add git build-base \ && apk add git build-base \
&& export COMMIT=$(git rev-parse --short HEAD) \ && export COMMIT=$(git rev-parse --short HEAD) \
&& export VERSION=$(go run ./cmd/internal/read_tag) \ && go build -v -trimpath -tags 'no_gvisor,with_quic,with_wireguard,with_acme' \
&& go build -v -trimpath -tags with_quic,with_wireguard,with_acme \
-o /go/bin/sing-box \ -o /go/bin/sing-box \
-ldflags "-X \"github.com/sagernet/sing-box/constant.Version=$VERSION\" -s -w -buildid=" \ -ldflags "-X github.com/sagernet/sing-box/constant.Commit=${COMMIT} -w -s -buildid=" \
./cmd/sing-box ./cmd/sing-box
FROM alpine AS dist FROM alpine AS dist
LABEL maintainer="nekohasekai <contact-git@sekai.icu>" LABEL maintainer="nekohasekai <contact-git@sekai.icu>"
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
RUN set -ex \ RUN set -ex \
&& apk upgrade \ && apk upgrade \
&& apk add bash tzdata ca-certificates \ && apk add bash tzdata ca-certificates \
+13 -26
View File
@@ -1,9 +1,9 @@
NAME = sing-box NAME = sing-box
COMMIT = $(shell git rev-parse --short HEAD) COMMIT = $(shell git rev-parse --short HEAD)
TAGS ?= with_gvisor,with_quic,with_wireguard,with_utls,with_reality_server,with_clash_api TAGS ?= with_quic,with_wireguard,with_clash_api
TAGS_TEST ?= with_gvisor,with_quic,with_wireguard,with_grpc,with_ech,with_utls,with_reality_server,with_shadowsocksr PARAMS = -v -trimpath -tags '$(TAGS)' -ldflags \
VERSION=$(shell go run ./cmd/internal/read_tag) '-X "github.com/sagernet/sing-box/constant.Commit=$(COMMIT)" \
PARAMS = -v -trimpath -tags "$(TAGS)" -ldflags "-X \"github.com/sagernet/sing-box/constant.Version=$(VERSION)\" -s -w -buildid=" -w -s -buildid='
MAIN = ./cmd/sing-box MAIN = ./cmd/sing-box
.PHONY: test release .PHONY: test release
@@ -17,11 +17,11 @@ install:
fmt: fmt:
@gofumpt -l -w . @gofumpt -l -w .
@gofmt -s -w . @gofmt -s -w .
@gci write --custom-order -s "standard,prefix(github.com/sagernet/),default" . @gci write -s "standard,prefix(github.com/sagernet/),default" .
fmt_install: fmt_install:
go install -v mvdan.cc/gofumpt@latest go install -v mvdan.cc/gofumpt@latest
go install -v github.com/daixiang0/gci@latest go install -v github.com/daixiang0/gci@v0.4.0
lint: lint:
GOOS=linux golangci-lint run ./... GOOS=linux golangci-lint run ./...
@@ -43,14 +43,14 @@ proto_install:
go install -v google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest go install -v google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
snapshot: snapshot:
go run ./cmd/internal/build goreleaser release --rm-dist --snapshot || exit 1 goreleaser release --rm-dist --snapshot
mkdir dist/release mkdir dist/release
mv dist/*.tar.gz dist/*.zip dist/*.deb dist/*.rpm dist/release mv dist/*.tar.gz dist/*.zip dist/*.deb dist/*.rpm dist/release
ghr --delete --draft --prerelease -p 1 nightly dist/release ghr --delete --draft --prerelease -p 1 nightly dist/release
rm -r dist rm -r dist
release: release:
go run ./cmd/internal/build goreleaser release --rm-dist --skip-publish || exit 1 goreleaser release --rm-dist --skip-publish
mkdir dist/release mkdir dist/release
mv dist/*.tar.gz dist/*.zip dist/*.deb dist/*.rpm dist/release mv dist/*.tar.gz dist/*.zip dist/*.deb dist/*.rpm dist/release
ghr --delete --draft --prerelease -p 3 $(shell git describe --tags) dist/release ghr --delete --draft --prerelease -p 3 $(shell git describe --tags) dist/release
@@ -61,27 +61,14 @@ release_install:
go install -v github.com/tcnksm/ghr@latest go install -v github.com/tcnksm/ghr@latest
test: test:
@go test -v ./... && \ @go test -v . && \
cd test && \ pushd test && \
go mod tidy && \ go mod tidy && \
go test -v -tags "$(TAGS_TEST)" . go test -v -tags with_quic,with_wireguard,with_grpc . && \
popd
test_stdio:
@go test -v ./... && \
cd test && \
go mod tidy && \
go test -v -tags "$(TAGS_TEST),force_stdio" .
lib:
go run ./cmd/internal/build_libbox
lib_install:
go get -v -d
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.0.0-20221130124640-349ebaa752ca
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.0.0-20221130124640-349ebaa752ca
clean: clean:
rm -rf bin dist sing-box rm -rf bin dist
rm -f $(shell go env GOPATH)/sing-box rm -f $(shell go env GOPATH)/sing-box
update: update:
+6 -22
View File
@@ -4,29 +4,23 @@ import (
"context" "context"
"net" "net"
"github.com/sagernet/sing-box/common/urltest"
N "github.com/sagernet/sing/common/network" N "github.com/sagernet/sing/common/network"
) )
type ClashServer interface { type ClashServer interface {
Service Service
Mode() string TrafficController
StoreSelected() bool
CacheFile() ClashCacheFile
HistoryStorage() *urltest.HistoryStorage
RoutedConnection(ctx context.Context, conn net.Conn, metadata InboundContext, matchedRule Rule) (net.Conn, Tracker)
RoutedPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext, matchedRule Rule) (N.PacketConn, Tracker)
}
type ClashCacheFile interface {
LoadSelected(group string) string
StoreSelected(group string, selected string) error
} }
type Tracker interface { type Tracker interface {
Leave() Leave()
} }
type TrafficController interface {
RoutedConnection(ctx context.Context, conn net.Conn, metadata InboundContext, matchedRule Rule) (net.Conn, Tracker)
RoutedPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext, matchedRule Rule) (N.PacketConn, Tracker)
}
type OutboundGroup interface { type OutboundGroup interface {
Now() string Now() string
All() []string All() []string
@@ -38,13 +32,3 @@ func OutboundTag(detour Outbound) string {
} }
return detour.Tag() return detour.Tag()
} }
type V2RayServer interface {
Service
StatsService() V2RayStatsService
}
type V2RayStatsService interface {
RoutedConnection(inbound string, outbound string, user string, conn net.Conn) net.Conn
RoutedPacketConnection(inbound string, outbound string, user string, conn N.PacketConn) N.PacketConn
}
+11 -13
View File
@@ -6,7 +6,7 @@ import (
"net/netip" "net/netip"
"github.com/sagernet/sing-box/common/process" "github.com/sagernet/sing-box/common/process"
"github.com/sagernet/sing-box/option" "github.com/sagernet/sing-dns"
M "github.com/sagernet/sing/common/metadata" M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network" N "github.com/sagernet/sing/common/network"
) )
@@ -38,18 +38,16 @@ type InboundContext struct {
// cache // cache
InboundDetour string InboundDetour string
LastInbound string LastInbound string
OriginDestination M.Socksaddr OriginDestination M.Socksaddr
InboundOptions option.InboundOptions DomainStrategy dns.DomainStrategy
DestinationAddresses []netip.Addr SniffEnabled bool
SourceGeoIPCode string SniffOverrideDestination bool
GeoIPCode string DestinationAddresses []netip.Addr
ProcessInfo *process.Info SourceGeoIPCode string
GeoIPCode string
// dns cache ProcessInfo *process.Info
QueryType uint16
} }
type inboundContextKey struct{} type inboundContextKey struct{}
+4 -30
View File
@@ -11,7 +11,7 @@ import (
"github.com/sagernet/sing/common/control" "github.com/sagernet/sing/common/control"
N "github.com/sagernet/sing/common/network" N "github.com/sagernet/sing/common/network"
mdns "github.com/miekg/dns" "golang.org/x/net/dns/dnsmessage"
) )
type Router interface { type Router interface {
@@ -27,41 +27,19 @@ type Router interface {
GeoIPReader() *geoip.Reader GeoIPReader() *geoip.Reader
LoadGeosite(code string) (Rule, error) LoadGeosite(code string) (Rule, error)
Exchange(ctx context.Context, message *mdns.Msg) (*mdns.Msg, error) Exchange(ctx context.Context, message *dnsmessage.Message) (*dnsmessage.Message, error)
Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error) Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error)
LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error) LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error)
InterfaceFinder() control.InterfaceFinder InterfaceBindManager() control.BindManager
DefaultInterface() string DefaultInterface() string
AutoDetectInterface() bool AutoDetectInterface() bool
AutoDetectInterfaceFunc() control.Func
DefaultMark() int DefaultMark() int
NetworkMonitor() tun.NetworkUpdateMonitor NetworkMonitor() tun.NetworkUpdateMonitor
InterfaceMonitor() tun.DefaultInterfaceMonitor InterfaceMonitor() tun.DefaultInterfaceMonitor
PackageManager() tun.PackageManager PackageManager() tun.PackageManager
Rules() []Rule Rules() []Rule
SetTrafficController(controller TrafficController)
TimeService
ClashServer() ClashServer
SetClashServer(server ClashServer)
V2RayServer() V2RayServer
SetV2RayServer(server V2RayServer)
}
type routerContextKey struct{}
func ContextWithRouter(ctx context.Context, router Router) context.Context {
return context.WithValue(ctx, (*routerContextKey)(nil), router)
}
func RouterFromContext(ctx context.Context) Router {
metadata := ctx.Value((*routerContextKey)(nil))
if metadata == nil {
return nil
}
return metadata.(Router)
} }
type Rule interface { type Rule interface {
@@ -77,7 +55,3 @@ type DNSRule interface {
Rule Rule
DisableCache() bool DisableCache() bool
} }
type InterfaceUpdateListener interface {
InterfaceUpdated() error
}
-8
View File
@@ -1,8 +0,0 @@
package adapter
import "time"
type TimeService interface {
Service
TimeFunc() func() time.Time
}
+6 -28
View File
@@ -38,25 +38,13 @@ type myUpstreamHandlerWrapper struct {
} }
func (w *myUpstreamHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { func (w *myUpstreamHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
myMetadata := w.metadata w.metadata.Destination = metadata.Destination
if metadata.Source.IsValid() { return w.connectionHandler(ctx, conn, w.metadata)
myMetadata.Source = metadata.Source
}
if metadata.Destination.IsValid() {
myMetadata.Destination = metadata.Destination
}
return w.connectionHandler(ctx, conn, myMetadata)
} }
func (w *myUpstreamHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error { func (w *myUpstreamHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
myMetadata := w.metadata w.metadata.Destination = metadata.Destination
if metadata.Source.IsValid() { return w.packetHandler(ctx, conn, w.metadata)
myMetadata.Source = metadata.Source
}
if metadata.Destination.IsValid() {
myMetadata.Destination = metadata.Destination
}
return w.packetHandler(ctx, conn, myMetadata)
} }
func (w *myUpstreamHandlerWrapper) NewError(ctx context.Context, err error) { func (w *myUpstreamHandlerWrapper) NewError(ctx context.Context, err error) {
@@ -90,23 +78,13 @@ func NewUpstreamContextHandler(
func (w *myUpstreamContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { func (w *myUpstreamContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
myMetadata := ContextFrom(ctx) myMetadata := ContextFrom(ctx)
if metadata.Source.IsValid() { myMetadata.Destination = metadata.Destination
myMetadata.Source = metadata.Source
}
if metadata.Destination.IsValid() {
myMetadata.Destination = metadata.Destination
}
return w.connectionHandler(ctx, conn, *myMetadata) return w.connectionHandler(ctx, conn, *myMetadata)
} }
func (w *myUpstreamContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error { func (w *myUpstreamContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
myMetadata := ContextFrom(ctx) myMetadata := ContextFrom(ctx)
if metadata.Source.IsValid() { myMetadata.Destination = metadata.Destination
myMetadata.Source = metadata.Source
}
if metadata.Destination.IsValid() {
myMetadata.Destination = metadata.Destination
}
return w.packetHandler(ctx, conn, *myMetadata) return w.packetHandler(ctx, conn, *myMetadata)
} }
-10
View File
@@ -3,10 +3,6 @@ package adapter
import ( import (
"context" "context"
"net" "net"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
) )
type V2RayServerTransport interface { type V2RayServerTransport interface {
@@ -16,12 +12,6 @@ type V2RayServerTransport interface {
Close() error Close() error
} }
type V2RayServerTransportHandler interface {
N.TCPConnectionHandler
E.Handler
FallbackConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error
}
type V2RayClientTransport interface { type V2RayClientTransport interface {
DialContext(ctx context.Context) (net.Conn, error) DialContext(ctx context.Context) (net.Conn, error)
} }
+28 -90
View File
@@ -9,9 +9,7 @@ import (
"time" "time"
"github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/experimental" "github.com/sagernet/sing-box/experimental"
"github.com/sagernet/sing-box/experimental/libbox/platform"
"github.com/sagernet/sing-box/inbound" "github.com/sagernet/sing-box/inbound"
"github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/option"
@@ -33,47 +31,34 @@ type Box struct {
logger log.ContextLogger logger log.ContextLogger
logFile *os.File logFile *os.File
clashServer adapter.ClashServer clashServer adapter.ClashServer
v2rayServer adapter.V2RayServer
done chan struct{} done chan struct{}
} }
func New(ctx context.Context, options option.Options, platformInterface platform.Interface) (*Box, error) { func New(ctx context.Context, options option.Options) (*Box, error) {
createdAt := time.Now() createdAt := time.Now()
logOptions := common.PtrValueOrDefault(options.Log) logOptions := common.PtrValueOrDefault(options.Log)
var needClashAPI bool var needClashAPI bool
var needV2RayAPI bool if options.Experimental != nil && options.Experimental.ClashAPI != nil && options.Experimental.ClashAPI.ExternalController != "" {
if options.Experimental != nil { needClashAPI = true
if options.Experimental.ClashAPI != nil && options.Experimental.ClashAPI.ExternalController != "" {
needClashAPI = true
}
if options.Experimental.V2RayAPI != nil && options.Experimental.V2RayAPI.Listen != "" {
needV2RayAPI = true
}
} }
var logFactory log.Factory var logFactory log.Factory
var observableLogFactory log.ObservableFactory var observableLogFactory log.ObservableFactory
var logFile *os.File var logFile *os.File
var logWriter io.Writer
if logOptions.Disabled { if logOptions.Disabled {
observableLogFactory = log.NewNOPFactory() observableLogFactory = log.NewNOPFactory()
logFactory = observableLogFactory logFactory = observableLogFactory
} else { } else {
var logWriter io.Writer
switch logOptions.Output { switch logOptions.Output {
case "": case "", "stderr":
if platformInterface != nil {
logWriter = io.Discard
} else {
logWriter = os.Stdout
}
case "stderr":
logWriter = os.Stderr logWriter = os.Stderr
case "stdout": case "stdout":
logWriter = os.Stdout logWriter = os.Stdout
default: default:
var err error var err error
logFile, err = os.OpenFile(C.BasePath(logOptions.Output), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) logFile, err = os.OpenFile(logOptions.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -87,10 +72,10 @@ func New(ctx context.Context, options option.Options, platformInterface platform
TimestampFormat: "-0700 2006-01-02 15:04:05", TimestampFormat: "-0700 2006-01-02 15:04:05",
} }
if needClashAPI { if needClashAPI {
observableLogFactory = log.NewObservableFactory(logFormatter, logWriter, platformInterface) observableLogFactory = log.NewObservableFactory(logFormatter, logWriter)
logFactory = observableLogFactory logFactory = observableLogFactory
} else { } else {
logFactory = log.NewFactory(logFormatter, logWriter, platformInterface) logFactory = log.NewFactory(logFormatter, logWriter)
} }
if logOptions.Level != "" { if logOptions.Level != "" {
logLevel, err := log.ParseLevel(logOptions.Level) logLevel, err := log.ParseLevel(logOptions.Level)
@@ -105,12 +90,11 @@ func New(ctx context.Context, options option.Options, platformInterface platform
router, err := route.NewRouter( router, err := route.NewRouter(
ctx, ctx,
logFactory, logFactory.NewLogger("router"),
logFactory.NewLogger("dns"),
common.PtrValueOrDefault(options.Route), common.PtrValueOrDefault(options.Route),
common.PtrValueOrDefault(options.DNS), common.PtrValueOrDefault(options.DNS),
common.PtrValueOrDefault(options.NTP),
options.Inbounds, options.Inbounds,
platformInterface,
) )
if err != nil { if err != nil {
return nil, E.Cause(err, "parse route options") return nil, E.Cause(err, "parse route options")
@@ -130,7 +114,6 @@ func New(ctx context.Context, options option.Options, platformInterface platform
router, router,
logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")), logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
inboundOptions, inboundOptions,
platformInterface,
) )
if err != nil { if err != nil {
return nil, E.Cause(err, "parse inbound[", i, "]") return nil, E.Cause(err, "parse inbound[", i, "]")
@@ -166,20 +149,12 @@ func New(ctx context.Context, options option.Options, platformInterface platform
} }
var clashServer adapter.ClashServer var clashServer adapter.ClashServer
var v2rayServer adapter.V2RayServer
if needClashAPI { if needClashAPI {
clashServer, err = experimental.NewClashServer(router, observableLogFactory, common.PtrValueOrDefault(options.Experimental.ClashAPI)) clashServer, err = experimental.NewClashServer(router, observableLogFactory, common.PtrValueOrDefault(options.Experimental.ClashAPI))
if err != nil { if err != nil {
return nil, E.Cause(err, "create clash api server") return nil, E.Cause(err, "create clash api server")
} }
router.SetClashServer(clashServer) router.SetTrafficController(clashServer)
}
if needV2RayAPI {
v2rayServer, err = experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(options.Experimental.V2RayAPI))
if err != nil {
return nil, E.Cause(err, "create v2ray api server")
}
router.SetV2RayServer(v2rayServer)
} }
return &Box{ return &Box{
router: router, router: router,
@@ -187,10 +162,9 @@ func New(ctx context.Context, options option.Options, platformInterface platform
outbounds: outbounds, outbounds: outbounds,
createdAt: createdAt, createdAt: createdAt,
logFactory: logFactory, logFactory: logFactory,
logger: logFactory.Logger(), logger: logFactory.NewLogger(""),
logFile: logFile, logFile: logFile,
clashServer: clashServer, clashServer: clashServer,
v2rayServer: v2rayServer,
done: make(chan struct{}), done: make(chan struct{}),
}, nil }, nil
} }
@@ -213,18 +187,6 @@ func (s *Box) Start() error {
} }
func (s *Box) start() error { func (s *Box) start() error {
if s.clashServer != nil {
err := s.clashServer.Start()
if err != nil {
return E.Cause(err, "start clash api server")
}
}
if s.v2rayServer != nil {
err := s.v2rayServer.Start()
if err != nil {
return E.Cause(err, "start v2ray api server")
}
}
for i, out := range s.outbounds { for i, out := range s.outbounds {
if starter, isStarter := out.(common.Starter); isStarter { if starter, isStarter := out.(common.Starter); isStarter {
err := starter.Start() err := starter.Start()
@@ -255,7 +217,12 @@ func (s *Box) start() error {
return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]") return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]")
} }
} }
if s.clashServer != nil {
err = s.clashServer.Start()
if err != nil {
return E.Cause(err, "start clash api server")
}
}
s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)") s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
return nil return nil
} }
@@ -267,45 +234,16 @@ func (s *Box) Close() error {
default: default:
close(s.done) close(s.done)
} }
var errors error for _, in := range s.inbounds {
for i, in := range s.inbounds { in.Close()
errors = E.Append(errors, in.Close(), func(err error) error {
return E.Cause(err, "close inbound/", in.Type(), "[", i, "]")
})
} }
for i, out := range s.outbounds { for _, out := range s.outbounds {
errors = E.Append(errors, common.Close(out), func(err error) error { common.Close(out)
return E.Cause(err, "close inbound/", out.Type(), "[", i, "]")
})
} }
if err := common.Close(s.router); err != nil { return common.Close(
errors = E.Append(errors, err, func(err error) error { s.router,
return E.Cause(err, "close router") s.logFactory,
}) s.clashServer,
} common.PtrOrNil(s.logFile),
if err := common.Close(s.logFactory); err != nil { )
errors = E.Append(errors, err, func(err error) error {
return E.Cause(err, "close log factory")
})
}
if err := common.Close(s.clashServer); err != nil {
errors = E.Append(errors, err, func(err error) error {
return E.Cause(err, "close clash api server")
})
}
if err := common.Close(s.v2rayServer); err != nil {
errors = E.Append(errors, err, func(err error) error {
return E.Cause(err, "close v2ray api server")
})
}
if s.logFile != nil {
errors = E.Append(errors, s.logFile.Close(), func(err error) error {
return E.Cause(err, "close log file")
})
}
return errors
}
func (s *Box) Router() adapter.Router {
return s.router
} }
-21
View File
@@ -1,21 +0,0 @@
package main
import (
"os"
"os/exec"
"github.com/sagernet/sing-box/cmd/internal/build_shared"
"github.com/sagernet/sing-box/log"
)
func main() {
build_shared.FindSDK()
command := exec.Command(os.Args[1], os.Args[2:]...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
err := command.Run()
if err != nil {
log.Fatal(err)
}
}
-136
View File
@@ -1,136 +0,0 @@
package main
import (
"flag"
"os"
"os/exec"
"path/filepath"
_ "github.com/sagernet/gomobile/event/key"
"github.com/sagernet/sing-box/cmd/internal/build_shared"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common/rw"
)
var (
debugEnabled bool
target string
)
func init() {
flag.BoolVar(&debugEnabled, "debug", false, "enable debug")
flag.StringVar(&target, "target", "android", "target platform")
}
func main() {
flag.Parse()
build_shared.FindMobile()
switch target {
case "android":
buildAndroid()
case "ios":
buildiOS()
}
}
var (
sharedFlags []string
debugFlags []string
)
func init() {
sharedFlags = append(sharedFlags, "-trimpath")
sharedFlags = append(sharedFlags, "-ldflags")
currentTag, err := build_shared.ReadTag()
if err != nil {
currentTag = "unknown"
}
sharedFlags = append(sharedFlags, "-X github.com/sagernet/sing-box/constant.Version="+currentTag+" -s -w -buildid=")
debugFlags = append(debugFlags, "-X github.com/sagernet/sing-box/constant.Version="+currentTag)
}
func buildAndroid() {
build_shared.FindSDK()
args := []string{
"bind",
"-v",
"-androidapi", "21",
"-javapkg=io.nekohasekai",
"-libname=box",
}
if !debugEnabled {
args = append(args, sharedFlags...)
} else {
args = append(args, debugFlags...)
}
args = append(args, "-tags")
if !debugEnabled {
args = append(args, "with_gvisor,with_quic,with_wireguard,with_utls,with_clash_api")
} else {
args = append(args, "with_gvisor,with_quic,with_wireguard,with_utls,with_clash_api,debug")
}
args = append(args, "./experimental/libbox")
command := exec.Command(build_shared.GoBinPath+"/gomobile", args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
err := command.Run()
if err != nil {
log.Fatal(err)
}
const name = "libbox.aar"
copyPath := filepath.Join("..", "sing-box-for-android", "app", "libs")
if rw.FileExists(copyPath) {
copyPath, _ = filepath.Abs(copyPath)
err = rw.CopyFile(name, filepath.Join(copyPath, name))
if err != nil {
log.Fatal(err)
}
log.Info("copied to ", copyPath)
}
}
func buildiOS() {
args := []string{
"bind",
"-v",
"-target", "ios,iossimulator,macos",
"-libname=box",
}
if !debugEnabled {
args = append(args, sharedFlags...)
} else {
args = append(args, debugFlags...)
}
args = append(args, "-tags")
if !debugEnabled {
args = append(args, "with_gvisor,with_utls,with_clash_api,with_conntrack")
} else {
args = append(args, "with_gvisor,with_utls,with_clash_api,with_conntrack,debug")
}
args = append(args, "./experimental/libbox")
command := exec.Command(build_shared.GoBinPath+"/gomobile", args...)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
err := command.Run()
if err != nil {
log.Fatal(err)
}
copyPath := filepath.Join("..", "sing-box-for-ios")
if rw.FileExists(copyPath) {
targetDir := filepath.Join(copyPath, "Libbox.xcframework")
targetDir, _ = filepath.Abs(targetDir)
os.RemoveAll(targetDir)
os.Rename("Libbox.xcframework", targetDir)
log.Info("copied to ", targetDir)
}
}
-92
View File
@@ -1,92 +0,0 @@
package build_shared
import (
"go/build"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/rw"
)
var (
androidSDKPath string
androidNDKPath string
)
func FindSDK() {
searchPath := []string{
"$ANDROID_HOME",
"$HOME/Android/Sdk",
"$HOME/.local/lib/android/sdk",
"$HOME/Library/Android/sdk",
}
for _, path := range searchPath {
path = os.ExpandEnv(path)
if rw.FileExists(path + "/licenses/android-sdk-license") {
androidSDKPath = path
break
}
}
if androidSDKPath == "" {
log.Fatal("android SDK not found")
}
if !findNDK() {
log.Fatal("android NDK not found")
}
os.Setenv("ANDROID_HOME", androidSDKPath)
os.Setenv("ANDROID_SDK_HOME", androidSDKPath)
os.Setenv("ANDROID_NDK_HOME", androidNDKPath)
os.Setenv("NDK", androidNDKPath)
os.Setenv("PATH", os.Getenv("PATH")+":"+filepath.Join(androidNDKPath, "toolchains", "llvm", "prebuilt", runtime.GOOS+"-x86_64", "bin"))
}
func findNDK() bool {
if rw.FileExists(androidSDKPath + "/ndk/25.1.8937393") {
androidNDKPath = androidSDKPath + "/ndk/25.1.8937393"
return true
}
ndkVersions, err := os.ReadDir(androidSDKPath + "/ndk")
if err != nil {
return false
}
versionNames := common.Map(ndkVersions, os.DirEntry.Name)
if len(versionNames) == 0 {
return false
}
sort.Slice(versionNames, func(i, j int) bool {
iVersions := strings.Split(versionNames[i], ".")
jVersions := strings.Split(versionNames[j], ".")
for k := 0; k < len(iVersions) && k < len(jVersions); k++ {
iVersion, _ := strconv.Atoi(iVersions[k])
jVersion, _ := strconv.Atoi(jVersions[k])
if iVersion != jVersion {
return iVersion > jVersion
}
}
return true
})
for _, versionName := range versionNames {
if rw.FileExists(androidSDKPath + "/ndk/" + versionName) {
androidNDKPath = androidSDKPath + "/ndk/" + versionName
return true
}
}
return false
}
var GoBinPath string
func FindMobile() {
goBin := filepath.Join(build.Default.GOPATH, "bin")
if !rw.FileExists(goBin + "/" + "gobind") {
log.Fatal("missing gomobile installation")
}
GoBinPath = goBin
}
-18
View File
@@ -1,18 +0,0 @@
package build_shared
import (
"github.com/sagernet/sing/common"
)
func ReadTag() (string, error) {
currentTag, err := common.Exec("git", "describe", "--tags").ReadOutput()
if err != nil {
return currentTag, err
}
currentTagRev, _ := common.Exec("git", "describe", "--tags", "--abbrev=0").ReadOutput()
if currentTagRev == currentTag {
return currentTag[1:], nil
}
shortCommit, _ := common.Exec("git", "rev-parse", "--short", "HEAD").ReadOutput()
return currentTagRev[1:] + "-" + shortCommit, nil
}
-21
View File
@@ -1,21 +0,0 @@
package main
import (
"os"
"github.com/sagernet/sing-box/cmd/internal/build_shared"
"github.com/sagernet/sing-box/log"
)
func main() {
currentTag, err := build_shared.ReadTag()
if err != nil {
log.Error(err)
_, err = os.Stdout.WriteString("unknown\n")
} else {
_, err = os.Stdout.WriteString(currentTag + "\n")
}
if err != nil {
log.Error(err)
}
}
+1 -4
View File
@@ -31,10 +31,7 @@ func check() error {
return err return err
} }
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
instance, err := box.New(ctx, options, nil) _, err = box.New(ctx, options)
if err == nil {
instance.Close()
}
cancel() cancel()
return err return err
} }
-139
View File
@@ -1,139 +0,0 @@
package main
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"os"
"strconv"
"github.com/sagernet/sing-box/log"
"github.com/gofrs/uuid"
"github.com/spf13/cobra"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
var commandGenerate = &cobra.Command{
Use: "generate",
Short: "Generate things",
}
func init() {
commandGenerate.AddCommand(commandGenerateUUID)
commandGenerate.AddCommand(commandGenerateRandom)
commandGenerate.AddCommand(commandGenerateWireGuardKeyPair)
commandGenerate.AddCommand(commandGenerateRealityKeyPair)
mainCommand.AddCommand(commandGenerate)
}
var (
outputBase64 bool
outputHex bool
)
var commandGenerateRandom = &cobra.Command{
Use: "rand <length>",
Short: "Generate random bytes",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
err := generateRandom(args)
if err != nil {
log.Fatal(err)
}
},
}
func init() {
commandGenerateRandom.Flags().BoolVar(&outputBase64, "base64", false, "Generate base64 string")
commandGenerateRandom.Flags().BoolVar(&outputHex, "hex", false, "Generate hex string")
}
func generateRandom(args []string) error {
length, err := strconv.Atoi(args[0])
if err != nil {
return err
}
randomBytes := make([]byte, length)
_, err = rand.Read(randomBytes)
if err != nil {
return err
}
if outputBase64 {
_, err = os.Stdout.WriteString(base64.StdEncoding.EncodeToString(randomBytes) + "\n")
} else if outputHex {
_, err = os.Stdout.WriteString(hex.EncodeToString(randomBytes) + "\n")
} else {
_, err = os.Stdout.Write(randomBytes)
}
return err
}
var commandGenerateUUID = &cobra.Command{
Use: "uuid",
Short: "Generate UUID string",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
err := generateUUID()
if err != nil {
log.Fatal(err)
}
},
}
func generateUUID() error {
newUUID, err := uuid.NewV4()
if err != nil {
return err
}
_, err = os.Stdout.WriteString(newUUID.String() + "\n")
return err
}
var commandGenerateWireGuardKeyPair = &cobra.Command{
Use: "wg-keypair",
Short: "Generate WireGuard key pair",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
err := generateWireGuardKey()
if err != nil {
log.Fatal(err)
}
},
}
func generateWireGuardKey() error {
privateKey, err := wgtypes.GeneratePrivateKey()
if err != nil {
return err
}
os.Stdout.WriteString("PrivateKey: " + privateKey.String() + "\n")
os.Stdout.WriteString("PublicKey: " + privateKey.PublicKey().String() + "\n")
return nil
}
var commandGenerateRealityKeyPair = &cobra.Command{
Use: "reality-keypair",
Short: "Generate reality key pair",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
err := generateRealityKey()
if err != nil {
log.Fatal(err)
}
},
}
func generateRealityKey() error {
privateKey, err := wgtypes.GeneratePrivateKey()
if err != nil {
return err
}
publicKey := privateKey.PublicKey()
os.Stdout.WriteString("PrivateKey: " + base64.RawURLEncoding.EncodeToString(privateKey[:]) + "\n")
os.Stdout.WriteString("PublicKey: " + base64.RawURLEncoding.EncodeToString(publicKey[:]) + "\n")
return nil
}
+1 -16
View File
@@ -64,25 +64,11 @@ func create() (*box.Box, context.CancelFunc, error) {
options.Log.DisableColor = true options.Log.DisableColor = true
} }
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
instance, err := box.New(ctx, options, nil) instance, err := box.New(ctx, options)
if err != nil { if err != nil {
cancel() cancel()
return nil, nil, E.Cause(err, "create service") return nil, nil, E.Cause(err, "create service")
} }
osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
defer func() {
signal.Stop(osSignals)
close(osSignals)
}()
go func() {
_, loaded := <-osSignals
if loaded {
cancel()
}
}()
err = instance.Start() err = instance.Start()
if err != nil { if err != nil {
cancel() cancel()
@@ -94,7 +80,6 @@ func create() (*box.Box, context.CancelFunc, error) {
func run() error { func run() error {
osSignals := make(chan os.Signal, 1) osSignals := make(chan os.Signal, 1)
signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP) signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
defer signal.Stop(osSignals)
for { for {
instance, cancel, err := create() instance, cancel, err := create()
if err != nil { if err != nil {
+23 -33
View File
@@ -3,9 +3,9 @@ package main
import ( import (
"os" "os"
"runtime" "runtime"
"runtime/debug"
C "github.com/sagernet/sing-box/constant" C "github.com/sagernet/sing-box/constant"
F "github.com/sagernet/sing/common/format"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -25,40 +25,30 @@ func init() {
} }
func printVersion(cmd *cobra.Command, args []string) { func printVersion(cmd *cobra.Command, args []string) {
if nameOnly { var version string
os.Stdout.WriteString(C.Version + "\n") if !nameOnly {
return version = "sing-box "
} }
version := "sing-box version " + C.Version + "\n\n" version += F.ToString(C.Version)
version += "Environment: " + runtime.Version() + " " + runtime.GOOS + "/" + runtime.GOARCH + "\n" if C.Commit != "" {
version += "." + C.Commit
var tags string }
var revision string if !nameOnly {
version += " ("
debugInfo, loaded := debug.ReadBuildInfo() version += runtime.Version()
if loaded { version += ", "
for _, setting := range debugInfo.Settings { version += runtime.GOOS
switch setting.Key { version += "/"
case "-tags": version += runtime.GOARCH
tags = setting.Value version += ", "
case "vcs.revision": version += "CGO "
revision = setting.Value if C.CGO_ENABLED {
} version += "enabled"
} else {
version += "disabled"
} }
version += ")"
} }
version += "\n"
if tags != "" {
version += "Tags: " + tags + "\n"
}
if revision != "" {
version += "Revision: " + revision + "\n"
}
if C.CGO_ENABLED {
version += "CGO: enabled\n"
} else {
version += "CGO: disabled\n"
}
os.Stdout.WriteString(version) os.Stdout.WriteString(version)
} }
-1
View File
@@ -3,7 +3,6 @@ package main
import ( import (
"os" "os"
_ "github.com/sagernet/sing-box/include"
"github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/log"
"github.com/spf13/cobra" "github.com/spf13/cobra"
+1 -1
View File
@@ -26,7 +26,7 @@ func WrapH2(err error) error {
if err == io.ErrUnexpectedEOF { if err == io.ErrUnexpectedEOF {
return io.EOF return io.EOF
} }
if Contains(err, "client disconnected", "body closed by handler", "response body closed", "; CANCEL") { if Contains(err, "client disconnected", "body closed by handler") {
return net.ErrClosed return net.ErrClosed
} }
return err return err
-210
View File
@@ -1,210 +0,0 @@
//go:build go1.19 && !go1.20
package badtls
import (
"crypto/cipher"
"crypto/rand"
"crypto/tls"
"encoding/binary"
"io"
"net"
"reflect"
"sync"
"sync/atomic"
"unsafe"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
N "github.com/sagernet/sing/common/network"
)
type Conn struct {
*tls.Conn
writer N.ExtendedWriter
activeCall *int32
closeNotifySent *bool
version *uint16
rand io.Reader
halfAccess *sync.Mutex
halfError *error
cipher cipher.AEAD
explicitNonceLen int
halfPtr uintptr
halfSeq []byte
halfScratchBuf []byte
}
func Create(conn *tls.Conn) (TLSConn, error) {
if !handshakeComplete(conn) {
return nil, E.New("handshake not finished")
}
rawConn := reflect.Indirect(reflect.ValueOf(conn))
rawActiveCall := rawConn.FieldByName("activeCall")
if !rawActiveCall.IsValid() || rawActiveCall.Kind() != reflect.Int32 {
return nil, E.New("badtls: invalid active call")
}
activeCall := (*int32)(unsafe.Pointer(rawActiveCall.UnsafeAddr()))
rawHalfConn := rawConn.FieldByName("out")
if !rawHalfConn.IsValid() || rawHalfConn.Kind() != reflect.Struct {
return nil, E.New("badtls: invalid half conn")
}
rawVersion := rawConn.FieldByName("vers")
if !rawVersion.IsValid() || rawVersion.Kind() != reflect.Uint16 {
return nil, E.New("badtls: invalid version")
}
version := (*uint16)(unsafe.Pointer(rawVersion.UnsafeAddr()))
rawCloseNotifySent := rawConn.FieldByName("closeNotifySent")
if !rawCloseNotifySent.IsValid() || rawCloseNotifySent.Kind() != reflect.Bool {
return nil, E.New("badtls: invalid notify")
}
closeNotifySent := (*bool)(unsafe.Pointer(rawCloseNotifySent.UnsafeAddr()))
rawConfig := reflect.Indirect(rawConn.FieldByName("config"))
if !rawConfig.IsValid() || rawConfig.Kind() != reflect.Struct {
return nil, E.New("badtls: bad config")
}
config := (*tls.Config)(unsafe.Pointer(rawConfig.UnsafeAddr()))
randReader := config.Rand
if randReader == nil {
randReader = rand.Reader
}
rawHalfMutex := rawHalfConn.FieldByName("Mutex")
if !rawHalfMutex.IsValid() || rawHalfMutex.Kind() != reflect.Struct {
return nil, E.New("badtls: invalid half mutex")
}
halfAccess := (*sync.Mutex)(unsafe.Pointer(rawHalfMutex.UnsafeAddr()))
rawHalfError := rawHalfConn.FieldByName("err")
if !rawHalfError.IsValid() || rawHalfError.Kind() != reflect.Interface {
return nil, E.New("badtls: invalid half error")
}
halfError := (*error)(unsafe.Pointer(rawHalfError.UnsafeAddr()))
rawHalfCipherInterface := rawHalfConn.FieldByName("cipher")
if !rawHalfCipherInterface.IsValid() || rawHalfCipherInterface.Kind() != reflect.Interface {
return nil, E.New("badtls: invalid cipher interface")
}
rawHalfCipher := rawHalfCipherInterface.Elem()
aeadCipher, loaded := valueInterface(rawHalfCipher, false).(cipher.AEAD)
if !loaded {
return nil, E.New("badtls: invalid AEAD cipher")
}
var explicitNonceLen int
switch cipherName := reflect.Indirect(rawHalfCipher).Type().String(); cipherName {
case "tls.prefixNonceAEAD":
explicitNonceLen = aeadCipher.NonceSize()
case "tls.xorNonceAEAD":
default:
return nil, E.New("badtls: unknown cipher type: ", cipherName)
}
rawHalfSeq := rawHalfConn.FieldByName("seq")
if !rawHalfSeq.IsValid() || rawHalfSeq.Kind() != reflect.Array {
return nil, E.New("badtls: invalid seq")
}
halfSeq := rawHalfSeq.Bytes()
rawHalfScratchBuf := rawHalfConn.FieldByName("scratchBuf")
if !rawHalfScratchBuf.IsValid() || rawHalfScratchBuf.Kind() != reflect.Array {
return nil, E.New("badtls: invalid scratchBuf")
}
halfScratchBuf := rawHalfScratchBuf.Bytes()
return &Conn{
Conn: conn,
writer: bufio.NewExtendedWriter(conn.NetConn()),
activeCall: activeCall,
closeNotifySent: closeNotifySent,
version: version,
halfAccess: halfAccess,
halfError: halfError,
cipher: aeadCipher,
explicitNonceLen: explicitNonceLen,
rand: randReader,
halfPtr: rawHalfConn.UnsafeAddr(),
halfSeq: halfSeq,
halfScratchBuf: halfScratchBuf,
}, nil
}
func (c *Conn) WriteBuffer(buffer *buf.Buffer) error {
if buffer.Len() > maxPlaintext {
defer buffer.Release()
return common.Error(c.Write(buffer.Bytes()))
}
for {
x := atomic.LoadInt32(c.activeCall)
if x&1 != 0 {
return net.ErrClosed
}
if atomic.CompareAndSwapInt32(c.activeCall, x, x+2) {
break
}
}
defer atomic.AddInt32(c.activeCall, -2)
c.halfAccess.Lock()
defer c.halfAccess.Unlock()
if err := *c.halfError; err != nil {
return err
}
if *c.closeNotifySent {
return errShutdown
}
dataLen := buffer.Len()
dataBytes := buffer.Bytes()
outBuf := buffer.ExtendHeader(recordHeaderLen + c.explicitNonceLen)
outBuf[0] = 23
version := *c.version
if version == 0 {
version = tls.VersionTLS10
} else if version == tls.VersionTLS13 {
version = tls.VersionTLS12
}
binary.BigEndian.PutUint16(outBuf[1:], version)
var nonce []byte
if c.explicitNonceLen > 0 {
nonce = outBuf[5 : 5+c.explicitNonceLen]
if c.explicitNonceLen < 16 {
copy(nonce, c.halfSeq)
} else {
if _, err := io.ReadFull(c.rand, nonce); err != nil {
return err
}
}
}
if len(nonce) == 0 {
nonce = c.halfSeq
}
if *c.version == tls.VersionTLS13 {
buffer.FreeBytes()[0] = 23
binary.BigEndian.PutUint16(outBuf[3:], uint16(dataLen+1+c.cipher.Overhead()))
c.cipher.Seal(outBuf, nonce, outBuf[recordHeaderLen:recordHeaderLen+c.explicitNonceLen+dataLen+1], outBuf[:recordHeaderLen])
buffer.Extend(1 + c.cipher.Overhead())
} else {
binary.BigEndian.PutUint16(outBuf[3:], uint16(dataLen))
additionalData := append(c.halfScratchBuf[:0], c.halfSeq...)
additionalData = append(additionalData, outBuf[:recordHeaderLen]...)
c.cipher.Seal(outBuf, nonce, dataBytes, additionalData)
buffer.Extend(c.cipher.Overhead())
binary.BigEndian.PutUint16(outBuf[3:], uint16(dataLen+c.explicitNonceLen+c.cipher.Overhead()))
}
incSeq(c.halfPtr)
return c.writer.WriteBuffer(buffer)
}
func (c *Conn) FrontHeadroom() int {
return recordHeaderLen + c.explicitNonceLen
}
func (c *Conn) RearHeadroom() int {
return 1 + c.cipher.Overhead()
}
func (c *Conn) WriterMTU() int {
return maxPlaintext
}
func (c *Conn) Upstream() any {
return c.Conn
}
func (c *Conn) UpstreamWriter() any {
return c.NetConn()
}
-12
View File
@@ -1,12 +0,0 @@
//go:build !go1.19 || go1.20
package badtls
import (
"crypto/tls"
"os"
)
func Create(conn *tls.Conn) (TLSConn, error) {
return nil, os.ErrInvalid
}
-13
View File
@@ -1,13 +0,0 @@
package badtls
import (
"context"
"crypto/tls"
"net"
)
type TLSConn interface {
net.Conn
HandshakeContext(ctx context.Context) error
ConnectionState() tls.ConnectionState
}
-26
View File
@@ -1,26 +0,0 @@
//go:build go1.19 && !go.1.20
package badtls
import (
"crypto/tls"
"reflect"
_ "unsafe"
)
const (
maxPlaintext = 16384 // maximum plaintext payload length
recordHeaderLen = 5 // record header length
)
//go:linkname errShutdown crypto/tls.errShutdown
var errShutdown error
//go:linkname handshakeComplete crypto/tls.(*Conn).handshakeComplete
func handshakeComplete(conn *tls.Conn) bool
//go:linkname incSeq crypto/tls.(*halfConn).incSeq
func incSeq(conn uintptr)
//go:linkname valueInterface reflect.valueInterface
func valueInterface(v reflect.Value, safe bool) any
-51
View File
@@ -1,51 +0,0 @@
package conntrack
import (
"net"
"runtime/debug"
"github.com/sagernet/sing/common/x/list"
)
type Conn struct {
net.Conn
element *list.Element[*ConnEntry]
}
func NewConn(conn net.Conn) *Conn {
entry := &ConnEntry{
Conn: conn,
Stack: debug.Stack(),
}
connAccess.Lock()
element := openConnection.PushBack(entry)
connAccess.Unlock()
return &Conn{
Conn: conn,
element: element,
}
}
func (c *Conn) Close() error {
if c.element.Value != nil {
connAccess.Lock()
if c.element.Value != nil {
openConnection.Remove(c.element)
c.element.Value = nil
}
connAccess.Unlock()
}
return c.Conn.Close()
}
func (c *Conn) Upstream() any {
return c.Conn
}
func (c *Conn) ReaderReplaceable() bool {
return true
}
func (c *Conn) WriterReplaceable() bool {
return true
}
-51
View File
@@ -1,51 +0,0 @@
package conntrack
import (
"net"
"runtime/debug"
"github.com/sagernet/sing/common/x/list"
)
type PacketConn struct {
net.PacketConn
element *list.Element[*ConnEntry]
}
func NewPacketConn(conn net.PacketConn) *PacketConn {
entry := &ConnEntry{
Conn: conn,
Stack: debug.Stack(),
}
connAccess.Lock()
element := openConnection.PushBack(entry)
connAccess.Unlock()
return &PacketConn{
PacketConn: conn,
element: element,
}
}
func (c *PacketConn) Close() error {
if c.element.Value != nil {
connAccess.Lock()
if c.element.Value != nil {
openConnection.Remove(c.element)
c.element.Value = nil
}
connAccess.Unlock()
}
return c.PacketConn.Close()
}
func (c *PacketConn) Upstream() any {
return c.PacketConn
}
func (c *PacketConn) ReaderReplaceable() bool {
return true
}
func (c *PacketConn) WriterReplaceable() bool {
return true
}
-43
View File
@@ -1,43 +0,0 @@
package conntrack
import (
"io"
"sync"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/x/list"
)
var (
connAccess sync.RWMutex
openConnection list.List[*ConnEntry]
)
type ConnEntry struct {
Conn io.Closer
Stack []byte
}
func Count() int {
return openConnection.Len()
}
func List() []*ConnEntry {
connAccess.RLock()
defer connAccess.RUnlock()
connList := make([]*ConnEntry, 0, openConnection.Len())
for element := openConnection.Front(); element != nil; element = element.Next() {
connList = append(connList, element.Value)
}
return connList
}
func Close() {
connAccess.Lock()
defer connAccess.Unlock()
for element := openConnection.Front(); element != nil; element = element.Next() {
common.Close(element.Value.Conn)
element.Value = nil
}
openConnection = list.List[*ConnEntry]{}
}
-5
View File
@@ -1,5 +0,0 @@
//go:build !with_conntrack
package conntrack
const Enabled = false
-5
View File
@@ -1,5 +0,0 @@
//go:build with_conntrack
package conntrack
const Enabled = true
+38 -81
View File
@@ -3,10 +3,10 @@ package dialer
import ( import (
"context" "context"
"net" "net"
"net/netip"
"time" "time"
"github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/dialer/conntrack"
"github.com/sagernet/sing-box/common/warning" "github.com/sagernet/sing-box/common/warning"
C "github.com/sagernet/sing-box/constant" C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/option"
@@ -14,7 +14,8 @@ import (
E "github.com/sagernet/sing/common/exceptions" E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata" M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network" N "github.com/sagernet/sing/common/network"
"github.com/sagernet/tfo-go"
"github.com/database64128/tfo-go"
) )
var warnBindInterfaceOnUnsupportedPlatform = warning.New( var warnBindInterfaceOnUnsupportedPlatform = warning.New(
@@ -53,13 +54,10 @@ var warnTFOOnUnsupportedPlatform = warning.New(
) )
type DefaultDialer struct { type DefaultDialer struct {
dialer4 tfo.Dialer dialer tfo.Dialer
dialer6 tfo.Dialer udpDialer net.Dialer
udpDialer4 net.Dialer
udpDialer6 net.Dialer
udpListener net.ListenConfig udpListener net.ListenConfig
udpAddr4 string bindUDPAddr string
udpAddr6 string
} }
func NewDefault(router adapter.Router, options option.DialerOptions) *DefaultDialer { func NewDefault(router adapter.Router, options option.DialerOptions) *DefaultDialer {
@@ -67,15 +65,25 @@ func NewDefault(router adapter.Router, options option.DialerOptions) *DefaultDia
var listener net.ListenConfig var listener net.ListenConfig
if options.BindInterface != "" { if options.BindInterface != "" {
warnBindInterfaceOnUnsupportedPlatform.Check() warnBindInterfaceOnUnsupportedPlatform.Check()
bindFunc := control.BindToInterface(router.InterfaceFinder(), options.BindInterface, -1) bindFunc := control.BindToInterface(router.InterfaceBindManager(), options.BindInterface)
dialer.Control = control.Append(dialer.Control, bindFunc) dialer.Control = control.Append(dialer.Control, bindFunc)
listener.Control = control.Append(listener.Control, bindFunc) listener.Control = control.Append(listener.Control, bindFunc)
} else if router.AutoDetectInterface() { } else if router.AutoDetectInterface() {
bindFunc := router.AutoDetectInterfaceFunc() if C.IsWindows {
dialer.Control = control.Append(dialer.Control, bindFunc) bindFunc := control.BindToInterfaceIndexFunc(func(network, address string) int {
listener.Control = control.Append(listener.Control, bindFunc) return router.InterfaceMonitor().DefaultInterfaceIndex(M.ParseSocksaddr(address).Addr)
})
dialer.Control = control.Append(dialer.Control, bindFunc)
listener.Control = control.Append(listener.Control, bindFunc)
} else {
bindFunc := control.BindToInterfaceFunc(router.InterfaceBindManager(), func(network, address string) string {
return router.InterfaceMonitor().DefaultInterfaceName(M.ParseSocksaddr(address).Addr)
})
dialer.Control = control.Append(dialer.Control, bindFunc)
listener.Control = control.Append(listener.Control, bindFunc)
}
} else if router.DefaultInterface() != "" { } else if router.DefaultInterface() != "" {
bindFunc := control.BindToInterface(router.InterfaceFinder(), router.DefaultInterface(), -1) bindFunc := control.BindToInterface(router.InterfaceBindManager(), router.DefaultInterface())
dialer.Control = control.Append(dialer.Control, bindFunc) dialer.Control = control.Append(dialer.Control, bindFunc)
listener.Control = control.Append(listener.Control, bindFunc) listener.Control = control.Append(listener.Control, bindFunc)
} }
@@ -104,47 +112,22 @@ func NewDefault(router adapter.Router, options option.DialerOptions) *DefaultDia
if options.TCPFastOpen { if options.TCPFastOpen {
warnTFOOnUnsupportedPlatform.Check() warnTFOOnUnsupportedPlatform.Check()
} }
var udpFragment bool var bindUDPAddr string
if options.UDPFragment != nil { udpDialer := dialer
udpFragment = *options.UDPFragment var bindAddress netip.Addr
} else { if options.BindAddress != nil {
udpFragment = options.UDPFragmentDefault bindAddress = options.BindAddress.Build()
} }
if !udpFragment { if bindAddress.IsValid() {
dialer.Control = control.Append(dialer.Control, control.DisableUDPFragment()) dialer.LocalAddr = &net.TCPAddr{
listener.Control = control.Append(listener.Control, control.DisableUDPFragment()) IP: bindAddress.AsSlice(),
} }
var ( udpDialer.LocalAddr = &net.UDPAddr{
dialer4 = dialer IP: bindAddress.AsSlice(),
udpDialer4 = dialer }
udpAddr4 string bindUDPAddr = M.SocksaddrFrom(bindAddress, 0).String()
)
if options.Inet4BindAddress != nil {
bindAddr := options.Inet4BindAddress.Build()
dialer4.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
udpDialer4.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
udpAddr4 = M.SocksaddrFrom(bindAddr, 0).String()
}
var (
dialer6 = dialer
udpDialer6 = dialer
udpAddr6 string
)
if options.Inet6BindAddress != nil {
bindAddr := options.Inet6BindAddress.Build()
dialer6.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
udpDialer6.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
udpAddr6 = M.SocksaddrFrom(bindAddr, 0).String()
}
return &DefaultDialer{
tfo.Dialer{Dialer: dialer4, DisableTFO: !options.TCPFastOpen},
tfo.Dialer{Dialer: dialer6, DisableTFO: !options.TCPFastOpen},
udpDialer4,
udpDialer6,
listener,
udpAddr4,
udpAddr6,
} }
return &DefaultDialer{tfo.Dialer{Dialer: dialer, DisableTFO: !options.TCPFastOpen}, udpDialer, listener, bindUDPAddr}
} }
func (d *DefaultDialer) DialContext(ctx context.Context, network string, address M.Socksaddr) (net.Conn, error) { func (d *DefaultDialer) DialContext(ctx context.Context, network string, address M.Socksaddr) (net.Conn, error) {
@@ -153,37 +136,11 @@ func (d *DefaultDialer) DialContext(ctx context.Context, network string, address
} }
switch N.NetworkName(network) { switch N.NetworkName(network) {
case N.NetworkUDP: case N.NetworkUDP:
if !address.IsIPv6() { return d.udpDialer.DialContext(ctx, network, address.String())
return d.udpDialer4.DialContext(ctx, network, address.String())
} else {
return d.udpDialer6.DialContext(ctx, network, address.String())
}
}
if !address.IsIPv6() {
return trackConn(DialSlowContext(&d.dialer4, ctx, network, address))
} else {
return trackConn(DialSlowContext(&d.dialer6, ctx, network, address))
} }
return d.dialer.DialContext(ctx, network, address.Unwrap().String())
} }
func (d *DefaultDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) { func (d *DefaultDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
if !destination.IsIPv6() { return d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.bindUDPAddr)
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr4))
} else {
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr6))
}
}
func trackConn(conn net.Conn, err error) (net.Conn, error) {
if !conntrack.Enabled || err != nil {
return conn, err
}
return conntrack.NewConn(conn), nil
}
func trackPacketConn(conn net.PacketConn, err error) (net.PacketConn, error) {
if !conntrack.Enabled || err != nil {
return conn, err
}
return conntrack.NewPacketConn(conn), nil
} }
-141
View File
@@ -1,141 +0,0 @@
package dialer
import (
"context"
"io"
"net"
"os"
"time"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/bufio"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/tfo-go"
)
type slowOpenConn struct {
dialer *tfo.Dialer
ctx context.Context
network string
destination M.Socksaddr
conn net.Conn
create chan struct{}
err error
}
func DialSlowContext(dialer *tfo.Dialer, ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
if dialer.DisableTFO || N.NetworkName(network) != N.NetworkTCP {
return dialer.DialContext(ctx, network, destination.String(), nil)
}
return &slowOpenConn{
dialer: dialer,
ctx: ctx,
network: network,
destination: destination,
create: make(chan struct{}),
}, nil
}
func (c *slowOpenConn) Read(b []byte) (n int, err error) {
if c.conn == nil {
select {
case <-c.create:
if c.err != nil {
return 0, c.err
}
case <-c.ctx.Done():
return 0, c.ctx.Err()
}
}
return c.conn.Read(b)
}
func (c *slowOpenConn) Write(b []byte) (n int, err error) {
if c.conn == nil {
c.conn, err = c.dialer.DialContext(c.ctx, c.network, c.destination.String(), b)
if err != nil {
c.err = E.Cause(err, "dial tcp fast open")
}
close(c.create)
return
}
return c.conn.Write(b)
}
func (c *slowOpenConn) Close() error {
return common.Close(c.conn)
}
func (c *slowOpenConn) LocalAddr() net.Addr {
if c.conn == nil {
return M.Socksaddr{}
}
return c.conn.LocalAddr()
}
func (c *slowOpenConn) RemoteAddr() net.Addr {
if c.conn == nil {
return M.Socksaddr{}
}
return c.conn.RemoteAddr()
}
func (c *slowOpenConn) SetDeadline(t time.Time) error {
if c.conn == nil {
return os.ErrInvalid
}
return c.conn.SetDeadline(t)
}
func (c *slowOpenConn) SetReadDeadline(t time.Time) error {
if c.conn == nil {
return os.ErrInvalid
}
return c.conn.SetReadDeadline(t)
}
func (c *slowOpenConn) SetWriteDeadline(t time.Time) error {
if c.conn == nil {
return os.ErrInvalid
}
return c.conn.SetWriteDeadline(t)
}
func (c *slowOpenConn) Upstream() any {
return c.conn
}
func (c *slowOpenConn) ReaderReplaceable() bool {
return c.conn != nil
}
func (c *slowOpenConn) WriterReplaceable() bool {
return c.conn != nil
}
func (c *slowOpenConn) LazyHeadroom() bool {
return c.conn == nil
}
func (c *slowOpenConn) ReadFrom(r io.Reader) (n int64, err error) {
if c.conn != nil {
return bufio.Copy(c.conn, r)
}
return bufio.ReadFrom0(c, r)
}
func (c *slowOpenConn) WriteTo(w io.Writer) (n int64, err error) {
if c.conn == nil {
select {
case <-c.create:
if c.err != nil {
return 0, c.err
}
case <-c.ctx.Done():
return 0, c.ctx.Err()
}
}
return bufio.Copy(w, c.conn)
}
@@ -1,55 +1,34 @@
package tls package dialer
import ( import (
"context"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"net" "net"
"net/netip" "net/netip"
"os" "os"
"github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions" E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
) )
type STDClientConfig struct { type TLSDialer struct {
dialer N.Dialer
config *tls.Config config *tls.Config
} }
func (s *STDClientConfig) ServerName() string { func TLSConfig(serverAddress string, options option.OutboundTLSOptions) (*tls.Config, error) {
return s.config.ServerName if !options.Enabled {
} return nil, nil
}
func (s *STDClientConfig) SetServerName(serverName string) {
s.config.ServerName = serverName
}
func (s *STDClientConfig) NextProtos() []string {
return s.config.NextProtos
}
func (s *STDClientConfig) SetNextProtos(nextProto []string) {
s.config.NextProtos = nextProto
}
func (s *STDClientConfig) Config() (*STDConfig, error) {
return s.config, nil
}
func (s *STDClientConfig) Client(conn net.Conn) (Conn, error) {
return tls.Client(conn, s.config), nil
}
func (s *STDClientConfig) Clone() Config {
return &STDClientConfig{s.config.Clone()}
}
func NewSTDClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
var serverName string var serverName string
if options.ServerName != "" { if options.ServerName != "" {
serverName = options.ServerName serverName = options.ServerName
} else if serverAddress != "" { } else if serverAddress != "" {
if _, err := netip.ParseAddr(serverName); err != nil { if _, err := netip.ParseAddr(serverName); err == nil {
serverName = serverAddress serverName = serverAddress
} }
} }
@@ -58,7 +37,6 @@ func NewSTDClient(router adapter.Router, serverAddress string, options option.Ou
} }
var tlsConfig tls.Config var tlsConfig tls.Config
tlsConfig.Time = router.TimeFunc()
if options.DisableSNI { if options.DisableSNI {
tlsConfig.ServerName = "127.0.0.1" tlsConfig.ServerName = "127.0.0.1"
} else { } else {
@@ -84,14 +62,14 @@ func NewSTDClient(router adapter.Router, serverAddress string, options option.Ou
tlsConfig.NextProtos = options.ALPN tlsConfig.NextProtos = options.ALPN
} }
if options.MinVersion != "" { if options.MinVersion != "" {
minVersion, err := ParseTLSVersion(options.MinVersion) minVersion, err := option.ParseTLSVersion(options.MinVersion)
if err != nil { if err != nil {
return nil, E.Cause(err, "parse min_version") return nil, E.Cause(err, "parse min_version")
} }
tlsConfig.MinVersion = minVersion tlsConfig.MinVersion = minVersion
} }
if options.MaxVersion != "" { if options.MaxVersion != "" {
maxVersion, err := ParseTLSVersion(options.MaxVersion) maxVersion, err := option.ParseTLSVersion(options.MaxVersion)
if err != nil { if err != nil {
return nil, E.Cause(err, "parse max_version") return nil, E.Cause(err, "parse max_version")
} }
@@ -126,5 +104,42 @@ func NewSTDClient(router adapter.Router, serverAddress string, options option.Ou
} }
tlsConfig.RootCAs = certPool tlsConfig.RootCAs = certPool
} }
return &STDClientConfig{&tlsConfig}, nil return &tlsConfig, nil
}
func NewTLS(dialer N.Dialer, serverAddress string, options option.OutboundTLSOptions) (N.Dialer, error) {
if !options.Enabled {
return dialer, nil
}
tlsConfig, err := TLSConfig(serverAddress, options)
if err != nil {
return nil, err
}
return &TLSDialer{
dialer: dialer,
config: tlsConfig,
}, nil
}
func (d *TLSDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
if network != N.NetworkTCP {
return nil, os.ErrInvalid
}
conn, err := d.dialer.DialContext(ctx, network, destination)
if err != nil {
return nil, err
}
return TLSClient(ctx, conn, d.config)
}
func (d *TLSDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
return nil, os.ErrInvalid
}
func TLSClient(ctx context.Context, conn net.Conn, tlsConfig *tls.Config) (*tls.Conn, error) {
tlsConn := tls.Client(conn, tlsConfig)
ctx, cancel := context.WithTimeout(ctx, C.TCPTimeout)
defer cancel()
err := tlsConn.HandshakeContext(ctx)
return tlsConn, err
} }
+4
View File
@@ -4,6 +4,7 @@ import (
"net/netip" "net/netip"
E "github.com/sagernet/sing/common/exceptions" E "github.com/sagernet/sing/common/exceptions"
N "github.com/sagernet/sing/common/network"
"github.com/oschwald/maxminddb-golang" "github.com/oschwald/maxminddb-golang"
) )
@@ -30,5 +31,8 @@ func (r *Reader) Lookup(addr netip.Addr) string {
if code != "" { if code != "" {
return code return code
} }
if !N.IsPublicAddr(addr) {
return "private"
}
return "unknown" return "unknown"
} }
-128
View File
@@ -1,128 +0,0 @@
package json
import (
"bufio"
"io"
)
// kanged from v2ray
type commentFilterState = byte
const (
commentFilterStateContent commentFilterState = iota
commentFilterStateEscape
commentFilterStateDoubleQuote
commentFilterStateDoubleQuoteEscape
commentFilterStateSingleQuote
commentFilterStateSingleQuoteEscape
commentFilterStateComment
commentFilterStateSlash
commentFilterStateMultilineComment
commentFilterStateMultilineCommentStar
)
type CommentFilter struct {
br *bufio.Reader
state commentFilterState
}
func NewCommentFilter(reader io.Reader) io.Reader {
return &CommentFilter{br: bufio.NewReader(reader)}
}
func (v *CommentFilter) Read(b []byte) (int, error) {
p := b[:0]
for len(p) < len(b)-2 {
x, err := v.br.ReadByte()
if err != nil {
if len(p) == 0 {
return 0, err
}
return len(p), nil
}
switch v.state {
case commentFilterStateContent:
switch x {
case '"':
v.state = commentFilterStateDoubleQuote
p = append(p, x)
case '\'':
v.state = commentFilterStateSingleQuote
p = append(p, x)
case '\\':
v.state = commentFilterStateEscape
case '#':
v.state = commentFilterStateComment
case '/':
v.state = commentFilterStateSlash
default:
p = append(p, x)
}
case commentFilterStateEscape:
p = append(p, '\\', x)
v.state = commentFilterStateContent
case commentFilterStateDoubleQuote:
switch x {
case '"':
v.state = commentFilterStateContent
p = append(p, x)
case '\\':
v.state = commentFilterStateDoubleQuoteEscape
default:
p = append(p, x)
}
case commentFilterStateDoubleQuoteEscape:
p = append(p, '\\', x)
v.state = commentFilterStateDoubleQuote
case commentFilterStateSingleQuote:
switch x {
case '\'':
v.state = commentFilterStateContent
p = append(p, x)
case '\\':
v.state = commentFilterStateSingleQuoteEscape
default:
p = append(p, x)
}
case commentFilterStateSingleQuoteEscape:
p = append(p, '\\', x)
v.state = commentFilterStateSingleQuote
case commentFilterStateComment:
if x == '\n' {
v.state = commentFilterStateContent
p = append(p, '\n')
}
case commentFilterStateSlash:
switch x {
case '/':
v.state = commentFilterStateComment
case '*':
v.state = commentFilterStateMultilineComment
default:
p = append(p, '/', x)
}
case commentFilterStateMultilineComment:
switch x {
case '*':
v.state = commentFilterStateMultilineCommentStar
case '\n':
p = append(p, '\n')
}
case commentFilterStateMultilineCommentStar:
switch x {
case '/':
v.state = commentFilterStateContent
case '*':
// Stay
case '\n':
p = append(p, '\n')
default:
v.state = commentFilterStateMultilineComment
}
default:
panic("Unknown state.")
}
}
return len(p), nil
}
+4 -23
View File
@@ -329,23 +329,6 @@ func (c *ClientPacketConn) Write(b []byte) (n int, err error) {
return c.ExtendedConn.Write(b) return c.ExtendedConn.Write(b)
} }
func (c *ClientPacketConn) ReadBuffer(buffer *buf.Buffer) (err error) {
if !c.responseRead {
err = c.readResponse()
if err != nil {
return
}
c.responseRead = true
}
var length uint16
err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
if err != nil {
return
}
_, err = buffer.ReadFullFrom(c.ExtendedConn, int(length))
return
}
func (c *ClientPacketConn) WriteBuffer(buffer *buf.Buffer) error { func (c *ClientPacketConn) WriteBuffer(buffer *buf.Buffer) error {
if !c.requestWrite { if !c.requestWrite {
defer buffer.Release() defer buffer.Release()
@@ -360,11 +343,6 @@ func (c *ClientPacketConn) FrontHeadroom() int {
return 2 return 2
} }
func (c *ClientPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
err = c.ReadBuffer(buffer)
return
}
func (c *ClientPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error { func (c *ClientPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
return c.WriteBuffer(buffer) return c.WriteBuffer(buffer)
} }
@@ -488,7 +466,10 @@ func (c *ClientPacketAddrConn) ReadPacket(buffer *buf.Buffer) (destination M.Soc
if err != nil { if err != nil {
return return
} }
_, err = buffer.ReadFullFrom(c.ExtendedConn, int(length)) if buffer.FreeLen() < int(length) {
return destination, io.ErrShortBuffer
}
_, err = io.ReadFull(c.ExtendedConn, buffer.Extend(int(length)))
return return
} }
+2 -8
View File
@@ -43,7 +43,7 @@ func ParseProtocol(name string) (Protocol, error) {
func (p Protocol) newServer(conn net.Conn) (abstractSession, error) { func (p Protocol) newServer(conn net.Conn) (abstractSession, error) {
switch p { switch p {
case ProtocolSMux: case ProtocolSMux:
session, err := smux.Server(conn, smuxConfig()) session, err := smux.Server(conn, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -58,7 +58,7 @@ func (p Protocol) newServer(conn net.Conn) (abstractSession, error) {
func (p Protocol) newClient(conn net.Conn) (abstractSession, error) { func (p Protocol) newClient(conn net.Conn) (abstractSession, error) {
switch p { switch p {
case ProtocolSMux: case ProtocolSMux:
session, err := smux.Client(conn, smuxConfig()) session, err := smux.Client(conn, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -70,12 +70,6 @@ func (p Protocol) newClient(conn net.Conn) (abstractSession, error) {
} }
} }
func smuxConfig() *smux.Config {
config := smux.DefaultConfig()
config.KeepAliveDisabled = true
return config
}
func yaMuxConfig() *yamux.Config { func yaMuxConfig() *yamux.Config {
config := yamux.DefaultConfig() config := yamux.DefaultConfig()
config.LogOutput = io.Discard config.LogOutput = io.Discard
+14 -15
View File
@@ -3,6 +3,7 @@ package mux
import ( import (
"context" "context"
"encoding/binary" "encoding/binary"
"io"
"net" "net"
"github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/adapter"
@@ -14,7 +15,6 @@ import (
M "github.com/sagernet/sing/common/metadata" M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network" N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/rw" "github.com/sagernet/sing/common/rw"
"github.com/sagernet/sing/common/task"
) )
func NewConnection(ctx context.Context, router adapter.Router, errorHandler E.Handler, logger log.ContextLogger, conn net.Conn, metadata adapter.InboundContext) error { func NewConnection(ctx context.Context, router adapter.Router, errorHandler E.Handler, logger log.ContextLogger, conn net.Conn, metadata adapter.InboundContext) error {
@@ -26,21 +26,14 @@ func NewConnection(ctx context.Context, router adapter.Router, errorHandler E.Ha
if err != nil { if err != nil {
return err return err
} }
var group task.Group var stream net.Conn
group.Append0(func(ctx context.Context) error { for {
var stream net.Conn stream, err = session.Accept()
for { if err != nil {
stream, err = session.Accept() return err
if err != nil {
return err
}
go newConnection(ctx, router, errorHandler, logger, stream, metadata)
} }
}) go newConnection(ctx, router, errorHandler, logger, stream, metadata)
group.Cleanup(func() { }
session.Close()
})
return group.Run(ctx)
} }
func newConnection(ctx context.Context, router adapter.Router, errorHandler E.Handler, logger log.ContextLogger, stream net.Conn, metadata adapter.InboundContext) { func newConnection(ctx context.Context, router adapter.Router, errorHandler E.Handler, logger log.ContextLogger, stream net.Conn, metadata adapter.InboundContext) {
@@ -165,6 +158,9 @@ func (c *ServerPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksad
if err != nil { if err != nil {
return return
} }
if buffer.FreeLen() < int(length) {
return destination, io.ErrShortBuffer
}
_, err = buffer.ReadFullFrom(c.ExtendedConn, int(length)) _, err = buffer.ReadFullFrom(c.ExtendedConn, int(length))
if err != nil { if err != nil {
return return
@@ -227,6 +223,9 @@ func (c *ServerPacketAddrConn) ReadPacket(buffer *buf.Buffer) (destination M.Soc
if err != nil { if err != nil {
return return
} }
if buffer.FreeLen() < int(length) {
return destination, io.ErrShortBuffer
}
_, err = buffer.ReadFullFrom(c.ExtendedConn, int(length)) _, err = buffer.ReadFullFrom(c.ExtendedConn, int(length))
if err != nil { if err != nil {
return return
+7 -1
View File
@@ -28,5 +28,11 @@ type Info struct {
} }
func FindProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) { func FindProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
return findProcessInfo(searcher, ctx, network, source, destination) info, err := findProcessInfo(searcher, ctx, network, source, destination)
if err != nil {
if source.Addr().Is4In6() {
info, err = findProcessInfo(searcher, ctx, network, netip.AddrPortFrom(netip.AddrFrom4(source.Addr().As4()), source.Port()), destination)
}
}
return info, err
} }
+1 -19
View File
@@ -5,8 +5,6 @@ import (
"encoding/binary" "encoding/binary"
"net/netip" "net/netip"
"os" "os"
"strconv"
"strings"
"syscall" "syscall"
"unsafe" "unsafe"
@@ -31,22 +29,6 @@ func (d *darwinSearcher) FindProcessInfo(ctx context.Context, network string, so
return &Info{ProcessPath: processName, UserId: -1}, nil return &Info{ProcessPath: processName, UserId: -1}, nil
} }
var structSize = func() int {
value, _ := syscall.Sysctl("kern.osrelease")
major, _, _ := strings.Cut(value, ".")
n, _ := strconv.ParseInt(major, 10, 64)
switch true {
case n >= 22:
return 408
default:
// from darwin-xnu/bsd/netinet/in_pcblist.c:get_pcblist_n
// size/offset are round up (aligned) to 8 bytes in darwin
// rup8(sizeof(xinpcb_n)) + rup8(sizeof(xsocket_n)) +
// 2 * rup8(sizeof(xsockbuf_n)) + rup8(sizeof(xsockstat_n))
return 384
}
}()
func findProcessName(network string, ip netip.Addr, port int) (string, error) { func findProcessName(network string, ip netip.Addr, port int) (string, error) {
var spath string var spath string
switch network { switch network {
@@ -71,7 +53,7 @@ func findProcessName(network string, ip netip.Addr, port int) (string, error) {
// size/offset are round up (aligned) to 8 bytes in darwin // size/offset are round up (aligned) to 8 bytes in darwin
// rup8(sizeof(xinpcb_n)) + rup8(sizeof(xsocket_n)) + // rup8(sizeof(xinpcb_n)) + rup8(sizeof(xsocket_n)) +
// 2 * rup8(sizeof(xsockbuf_n)) + rup8(sizeof(xsockstat_n)) // 2 * rup8(sizeof(xsockbuf_n)) + rup8(sizeof(xsockstat_n))
itemSize := structSize itemSize := 384
if network == N.NetworkTCP { if network == N.NetworkTCP {
// rup8(sizeof(xtcpcb_n)) // rup8(sizeof(xtcpcb_n))
itemSize += 208 itemSize += 208
+7 -29
View File
@@ -13,7 +13,6 @@ import (
type Listener struct { type Listener struct {
net.Listener net.Listener
AcceptNoHeader bool
} }
func (l *Listener) Accept() (net.Conn, error) { func (l *Listener) Accept() (net.Conn, error) {
@@ -23,40 +22,19 @@ func (l *Listener) Accept() (net.Conn, error) {
} }
bufReader := std_bufio.NewReader(conn) bufReader := std_bufio.NewReader(conn)
header, err := proxyproto.Read(bufReader) header, err := proxyproto.Read(bufReader)
if err != nil && !(l.AcceptNoHeader && err == proxyproto.ErrNoProxyProtocol) { if err != nil {
return nil, &Error{err} return nil, err
} }
if bufReader.Buffered() > 0 { if bufReader.Buffered() > 0 {
cache := buf.NewSize(bufReader.Buffered()) cache := buf.NewSize(bufReader.Buffered())
_, err = cache.ReadFullFrom(bufReader, cache.FreeLen()) _, err = cache.ReadFullFrom(bufReader, cache.FreeLen())
if err != nil { if err != nil {
return nil, &Error{err} return nil, err
} }
conn = bufio.NewCachedConn(conn, cache) conn = bufio.NewCachedConn(conn, cache)
} }
if header != nil { return &bufio.AddrConn{Conn: conn, Metadata: M.Metadata{
return &bufio.AddrConn{Conn: conn, Metadata: M.Metadata{ Source: M.SocksaddrFromNet(header.SourceAddr),
Source: M.SocksaddrFromNet(header.SourceAddr).Unwrap(), Destination: M.SocksaddrFromNet(header.DestinationAddr),
Destination: M.SocksaddrFromNet(header.DestinationAddr).Unwrap(), }}, nil
}}, nil
}
return conn, nil
}
var _ net.Error = (*Error)(nil)
type Error struct {
error
}
func (e *Error) Unwrap() error {
return e.error
}
func (e *Error) Timeout() bool {
return false
}
func (e *Error) Temporary() bool {
return true
} }
+1 -4
View File
@@ -1,7 +1,6 @@
package redir package redir
import ( import (
"encoding/binary"
"net" "net"
"net/netip" "net/netip"
"os" "os"
@@ -30,9 +29,7 @@ func GetOriginalDestination(conn net.Conn) (destination netip.AddrPort, err erro
if err != nil { if err != nil {
return err return err
} }
var port [2]byte destination = netip.AddrPortFrom(M.AddrFromIP(raw.Addr.Addr[:]), raw.Addr.Port)
binary.BigEndian.PutUint16(port[:], raw.Addr.Port)
destination = netip.AddrPortFrom(M.AddrFromIP(raw.Addr.Addr[:]), binary.LittleEndian.Uint16(port[:]))
} }
return nil return nil
}) })
+80 -13
View File
@@ -2,11 +2,14 @@ package redir
import ( import (
"encoding/binary" "encoding/binary"
"net"
"net/netip" "net/netip"
"os"
"strconv"
"syscall" "syscall"
"github.com/sagernet/sing/common/control"
E "github.com/sagernet/sing/common/exceptions" E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
M "github.com/sagernet/sing/common/metadata" M "github.com/sagernet/sing/common/metadata"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
@@ -29,18 +32,6 @@ func TProxy(fd uintptr, isIPv6 bool) error {
return err return err
} }
func TProxyWriteBack() control.Func {
return func(network, address string, conn syscall.RawConn) error {
return control.Raw(conn, func(fd uintptr) error {
if M.ParseSocksaddr(address).Addr.Is6() {
return syscall.SetsockoptInt(int(fd), syscall.SOL_IPV6, unix.IPV6_TRANSPARENT, 1)
} else {
return syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1)
}
})
}
}
func GetOriginalDestinationFromOOB(oob []byte) (netip.AddrPort, error) { func GetOriginalDestinationFromOOB(oob []byte) (netip.AddrPort, error) {
controlMessages, err := unix.ParseSocketControlMessage(oob) controlMessages, err := unix.ParseSocketControlMessage(oob)
if err != nil { if err != nil {
@@ -55,3 +46,79 @@ func GetOriginalDestinationFromOOB(oob []byte) (netip.AddrPort, error) {
} }
return netip.AddrPort{}, E.New("not found") return netip.AddrPort{}, E.New("not found")
} }
func DialUDP(lAddr *net.UDPAddr, rAddr *net.UDPAddr) (*net.UDPConn, error) {
rSockAddr, err := udpAddrToSockAddr(rAddr)
if err != nil {
return nil, err
}
lSockAddr, err := udpAddrToSockAddr(lAddr)
if err != nil {
return nil, err
}
fd, err := syscall.Socket(udpAddrFamily(lAddr, rAddr), syscall.SOCK_DGRAM, 0)
if err != nil {
return nil, err
}
if err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
syscall.Close(fd)
return nil, err
}
if err = syscall.SetsockoptInt(fd, syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
syscall.Close(fd)
return nil, err
}
if err = syscall.Bind(fd, lSockAddr); err != nil {
syscall.Close(fd)
return nil, err
}
if err = syscall.Connect(fd, rSockAddr); err != nil {
syscall.Close(fd)
return nil, err
}
fdFile := os.NewFile(uintptr(fd), F.ToString("net-udp-dial-", rAddr))
defer fdFile.Close()
c, err := net.FileConn(fdFile)
if err != nil {
syscall.Close(fd)
return nil, err
}
return c.(*net.UDPConn), nil
}
func udpAddrToSockAddr(addr *net.UDPAddr) (syscall.Sockaddr, error) {
switch {
case addr.IP.To4() != nil:
ip := [4]byte{}
copy(ip[:], addr.IP.To4())
return &syscall.SockaddrInet4{Addr: ip, Port: addr.Port}, nil
default:
ip := [16]byte{}
copy(ip[:], addr.IP.To16())
zoneID, err := strconv.ParseUint(addr.Zone, 10, 32)
if err != nil {
zoneID = 0
}
return &syscall.SockaddrInet6{Addr: ip, Port: addr.Port, ZoneId: uint32(zoneID)}, nil
}
}
func udpAddrFamily(lAddr, rAddr *net.UDPAddr) int {
if (lAddr == nil || lAddr.IP.To4() != nil) && (rAddr == nil || lAddr.IP.To4() != nil) {
return syscall.AF_INET
}
return syscall.AF_INET6
}
+5 -6
View File
@@ -3,20 +3,19 @@
package redir package redir
import ( import (
"net"
"net/netip" "net/netip"
"os" "os"
"github.com/sagernet/sing/common/control"
) )
func TProxy(fd uintptr, isIPv6 bool) error { func TProxy(fd uintptr, isIPv6 bool) error {
return os.ErrInvalid return os.ErrInvalid
} }
func TProxyWriteBack() control.Func {
return nil
}
func GetOriginalDestinationFromOOB(oob []byte) (netip.AddrPort, error) { func GetOriginalDestinationFromOOB(oob []byte) (netip.AddrPort, error) {
return netip.AddrPort{}, os.ErrInvalid return netip.AddrPort{}, os.ErrInvalid
} }
func DialUDP(lAddr *net.UDPAddr, rAddr *net.UDPAddr) (*net.UDPConn, error) {
return nil, os.ErrInvalid
}
+2 -2
View File
@@ -20,7 +20,7 @@ type systemProxy struct {
isMixed bool isMixed bool
} }
func (p *systemProxy) update(event int) error { func (p *systemProxy) update() error {
newInterfaceName := p.monitor.DefaultInterfaceName(netip.IPv4Unspecified()) newInterfaceName := p.monitor.DefaultInterfaceName(netip.IPv4Unspecified())
if p.interfaceName == newInterfaceName { if p.interfaceName == newInterfaceName {
return nil return nil
@@ -88,7 +88,7 @@ func SetSystemProxy(router adapter.Router, port uint16, isMixed bool) (func() er
port: port, port: port,
isMixed: isMixed, isMixed: isMixed,
} }
err := proxy.update(tun.EventInterfaceUpdate) err := proxy.update()
if err != nil { if err != nil {
return nil, err return nil, err
} }
+1 -1
View File
@@ -7,7 +7,7 @@ import (
) )
func SetSystemProxy(router adapter.Router, port uint16, isMixed bool) (func() error, error) { func SetSystemProxy(router adapter.Router, port uint16, isMixed bool) (func() error, error) {
err := wininet.SetSystemProxy(F.ToString("http://127.0.0.1:", port), "") err := wininet.SetSystemProxy(F.ToString("http://127.0.0.1:", port), "<local>")
if err != nil { if err != nil {
return nil, err return nil, err
} }
+10 -6
View File
@@ -11,10 +11,9 @@ import (
C "github.com/sagernet/sing-box/constant" C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing/common" "github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/common/task" "github.com/sagernet/sing/common/task"
mDNS "github.com/miekg/dns" "golang.org/x/net/dns/dnsmessage"
) )
func StreamDomainNameQuery(readCtx context.Context, reader io.Reader) (*adapter.InboundContext, error) { func StreamDomainNameQuery(readCtx context.Context, reader io.Reader) (*adapter.InboundContext, error) {
@@ -45,13 +44,18 @@ func StreamDomainNameQuery(readCtx context.Context, reader io.Reader) (*adapter.
} }
func DomainNameQuery(ctx context.Context, packet []byte) (*adapter.InboundContext, error) { func DomainNameQuery(ctx context.Context, packet []byte) (*adapter.InboundContext, error) {
var msg mDNS.Msg var parser dnsmessage.Parser
err := msg.Unpack(packet) _, err := parser.Start(packet)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if len(msg.Question) == 0 || msg.Question[0].Qclass != mDNS.ClassINET || !M.IsDomainName(msg.Question[0].Name) { question, err := parser.Question()
if err != nil {
return nil, os.ErrInvalid return nil, os.ErrInvalid
} }
return &adapter.InboundContext{Protocol: C.ProtocolDNS}, nil domain := question.Name.String()
if question.Class == dnsmessage.ClassINET && IsDomainName(domain) {
return &adapter.InboundContext{Protocol: C.ProtocolDNS /*, Domain: domain*/}, nil
}
return nil, os.ErrInvalid
} }
+6
View File
@@ -0,0 +1,6 @@
package sniff
import _ "unsafe" // for linkname
//go:linkname IsDomainName net.isDomainName
func IsDomainName(domain string) bool
+2 -2
View File
@@ -13,13 +13,13 @@ import (
const ( const (
VersionDraft29 = 0xff00001d VersionDraft29 = 0xff00001d
Version1 = 0x1 Version1 = 0x1
Version2 = 0x6b3343cf Version2 = 0x709a50c4
) )
var ( var (
SaltOld = []byte{0xaf, 0xbf, 0xec, 0x28, 0x99, 0x93, 0xd2, 0x4c, 0x9e, 0x97, 0x86, 0xf1, 0x9c, 0x61, 0x11, 0xe0, 0x43, 0x90, 0xa8, 0x99} SaltOld = []byte{0xaf, 0xbf, 0xec, 0x28, 0x99, 0x93, 0xd2, 0x4c, 0x9e, 0x97, 0x86, 0xf1, 0x9c, 0x61, 0x11, 0xe0, 0x43, 0x90, 0xa8, 0x99}
SaltV1 = []byte{0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a} SaltV1 = []byte{0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a}
SaltV2 = []byte{0x0d, 0xed, 0xe3, 0xde, 0xf7, 0x00, 0xa6, 0xdb, 0x81, 0x93, 0x81, 0xbe, 0x6e, 0x26, 0x9d, 0xcb, 0xf9, 0xbd, 0x2e, 0xd9} SaltV2 = []byte{0xa7, 0x07, 0xc2, 0x03, 0xa5, 0x9b, 0x47, 0x18, 0x4a, 0x1d, 0x62, 0xca, 0x57, 0x04, 0x06, 0xea, 0x7a, 0xe3, 0xe5, 0xd3}
) )
const ( const (
+28 -63
View File
@@ -24,7 +24,8 @@ func QUICClientHello(ctx context.Context, packet []byte) (*adapter.InboundContex
if err != nil { if err != nil {
return nil, err return nil, err
} }
if typeByte&0x40 == 0 {
if typeByte&0x80 == 0 || typeByte&0x40 == 0 {
return nil, E.New("bad type byte") return nil, E.New("bad type byte")
} }
var versionNumber uint32 var versionNumber uint32
@@ -144,6 +145,9 @@ func QUICClientHello(ctx context.Context, packet []byte) (*adapter.InboundContex
default: default:
return nil, E.New("bad packet number length") return nil, E.New("bad packet number length")
} }
if packetNumber != 0 {
return nil, E.New("bad packet number: ", packetNumber)
}
extHdrLen := hdrLen + int(packetNumberLength) extHdrLen := hdrLen + int(packetNumberLength)
copy(newPacket[extHdrLen:hdrLen+4], packet[extHdrLen:]) copy(newPacket[extHdrLen:hdrLen+4], packet[extHdrLen:])
data := newPacket[extHdrLen : int(packetLen)+hdrLen] data := newPacket[extHdrLen : int(packetLen)+hdrLen]
@@ -168,76 +172,37 @@ func QUICClientHello(ctx context.Context, packet []byte) (*adapter.InboundContex
if err != nil { if err != nil {
return nil, err return nil, err
} }
var frameType byte
var frameLen uint64
var fragments []struct {
offset uint64
length uint64
payload []byte
}
decryptedReader := bytes.NewReader(decrypted) decryptedReader := bytes.NewReader(decrypted)
for { frameType, err := decryptedReader.ReadByte()
if err != nil {
return nil, err
}
for frameType == 0x0 {
// skip padding
frameType, err = decryptedReader.ReadByte() frameType, err = decryptedReader.ReadByte()
if err == io.EOF { if err != nil {
break return nil, err
}
switch frameType {
case 0x0:
continue
case 0x1:
continue
case 0x6:
var offset uint64
offset, err = qtls.ReadUvarint(decryptedReader)
if err != nil {
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, err
}
var length uint64
length, err = qtls.ReadUvarint(decryptedReader)
if err != nil {
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, err
}
index := len(decrypted) - decryptedReader.Len()
fragments = append(fragments, struct {
offset uint64
length uint64
payload []byte
}{offset, length, decrypted[index : index+int(length)]})
frameLen += length
_, err = decryptedReader.Seek(int64(length), io.SeekCurrent)
if err != nil {
return nil, err
}
default:
// ignore unknown frame type
} }
} }
if frameType != 0x6 {
// not crypto frame
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, nil
}
_, err = qtls.ReadUvarint(decryptedReader)
if err != nil {
return nil, err
}
_, err = qtls.ReadUvarint(decryptedReader)
if err != nil {
return nil, err
}
tlsHdr := make([]byte, 5) tlsHdr := make([]byte, 5)
tlsHdr[0] = 0x16 tlsHdr[0] = 0x16
binary.BigEndian.PutUint16(tlsHdr[1:], uint16(0x0303)) binary.BigEndian.PutUint16(tlsHdr[1:], uint16(0x0303))
binary.BigEndian.PutUint16(tlsHdr[3:], uint16(frameLen)) binary.BigEndian.PutUint16(tlsHdr[3:], uint16(decryptedReader.Len()))
var index uint64 metadata, err := TLSClientHello(ctx, io.MultiReader(bytes.NewReader(tlsHdr), decryptedReader))
var length int
var readers []io.Reader
readers = append(readers, bytes.NewReader(tlsHdr))
find:
for {
for _, fragment := range fragments {
if fragment.offset == index {
readers = append(readers, bytes.NewReader(fragment.payload))
index = fragment.offset + fragment.length
length++
continue find
}
}
if length == len(fragments) {
break
}
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, E.New("bad fragments")
}
metadata, err := TLSClientHello(ctx, io.MultiReader(readers...))
if err != nil { if err != nil {
return &adapter.InboundContext{Protocol: C.ProtocolQUIC}, err return nil, err
} }
metadata.Protocol = C.ProtocolQUIC metadata.Protocol = C.ProtocolQUIC
return metadata, nil return metadata, nil
-9
View File
@@ -19,15 +19,6 @@ func TestSniffQUICv1(t *testing.T) {
require.Equal(t, metadata.Domain, "cloudflare-quic.com") require.Equal(t, metadata.Domain, "cloudflare-quic.com")
} }
func TestSniffQUICFragment(t *testing.T) {
t.Parallel()
pkt, err := hex.DecodeString("cc00000001082e3d5d1b64040c55000044d0ccea69e773f6631c1d18b04ae9ee75fcfc34ef74fa62533c93534338a86f101a05d70e0697fb483063fa85db1c59ccfbda5c35234931d8524d8aac37eaaad649470a67794cd754b23c98695238b8363452333bc8c4858376b4166e001da2006e35cf98a91e11a56419b2786775284942d0f7163982f7c248867d12dd374957481dbc564013ff785e1916195eef671f725908f761099d992d69231336ba81d9e25fe2fa3a6eff4318a6ccf10176fc841a1b315f7b35c5b292266fc869d76ca533e7d14e86d82db2e22eacd350977e47d2e012d8a5891c5aaf2a0f4c2b2dae897c161e5b68cbb4dee952472bdc1e21504b8f02534ec4366ce3f8bf86efc78e0232778fbd554457567112abdcafcf6d4d8fcf35083c25d9495679614aba21696e338c62b585046cc55ba8c09c844361d889a47c3ea703b4e23545a9ab2c0bb369693a9ddfb5daffa85cf80fdd6ad66738664e5b0a551729b4955cff7255afcb04dee88c2f072c9de7400947a1bd9327ac5d012a33000ada021d4c03d249fb017d6ac9200b2f9436beab8183ddfbe2d8aee31ffb7df9e1cc181c1af80c39a89965d18ed12da8e3ebe2ae1fbe4b348f83ba19e3e3d1c9b22bcf03ab6ad9b30fe180623faa291ebad83bcd71d7b57f2f5e2f3b8e81d24fb70b2f2159239e8f21ffafef2747aba47d97ab4081e603c018b10678cf99cab1fb42156a14486fa435153979d7279fd22cd40af7088bfc7eff41af2f4b3c0c8864d0040d74dff427f7bffdb8c278474ea00311326cf4925471a8cf596cb92119f19e0f789490ba9cb77b98015a987d93e0324cf1a38b55109f00c3e6ddc5180fb107bf468323afec9bb49fd6a86418569789d66cafe3b8253c2aebb3af3782c1c54dd560487d031d28e6a6e23e159581bb1d47efc4da3fe1d169f9ffb0ca9ba61af0a38a92fde5bc5e6ec026e8378a6315a7b95abf1d2da790a391306ce74d0baf8e2ce648ca74c487f2c0a76a28a80cdf5bd34316eb607684fe7e6d9e83824a00e07660d0b90e3cddd61ebf10748263474afa88c300549e64ce2e90560bb1a12dee7e9484f729a8a4ee7c5651adb5194b3b3ae38e501567c7dbf36e7bb37a2c20b74655f47f2d9af18e52e9d4c9c9eee8e63745779b8f0b06f3a09d846ba62eb978ad77c85de1ee2fee3fbb4c2d283c73e1ccba56a4658e48a2665d200f7f9342f8e84c2ba490094a4f94feec89e42d2f654f564c2beb2997bafa1fc2c68ad8e160b63587d49abc31b834878d52acfb05fb73d0e059b206162e3c90b40c4bc08407ffcb3c08431895b691a3fea923f1f3b48db75d3e6b91fd319ffe4d486e0e14bd5c6affc838dee63d9e0b80f169b5e6c02c7321dcb20deb2b8e707b60e345a308d505bbf26a93d8f18b39d62632e9a77cbe48b3b32eb8819d6311a49820d40f5acbf0273c91c36b2269a03e72ee64df3dfb10ddefe73c64ef60870b2b77bd99dea655f5fe791b538a929a14d99f6d69685d72431ea5f0f4b27a044f2f575ab474fcc3857895934de1ca2581798eaef2c17fe5aaf2e6add97fa32997c7026f15c1b1ad0e6043ae506027a7c0242546fdc851cca39a204e56879f2cef838be8ec66e0f2292f8c862e06f810eb9b80c7a467ce6e90155206352c7f82b1173ba3b98d35bb72c259a60db20dd1a43fe6d7aef0265e6eaa5caafd9b64b448ff745a2046acbdb65cf2a5007809808a4828dc99097feedc734c236260c584")
require.NoError(t, err)
metadata, err := sniff.QUICClientHello(context.Background(), pkt)
require.NoError(t, err)
require.Equal(t, metadata.Domain, "cloudflare-quic.com")
}
func FuzzSniffQUIC(f *testing.F) { func FuzzSniffQUIC(f *testing.F) {
f.Fuzz(func(t *testing.T, data []byte) { f.Fuzz(func(t *testing.T, data []byte) {
sniff.QUICClientHello(context.Background(), data) sniff.QUICClientHello(context.Background(), data)
+12 -16
View File
@@ -5,6 +5,7 @@ import (
"context" "context"
"io" "io"
"net" "net"
"os"
"time" "time"
"github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/adapter"
@@ -18,11 +19,8 @@ type (
PacketSniffer = func(ctx context.Context, packet []byte) (*adapter.InboundContext, error) PacketSniffer = func(ctx context.Context, packet []byte) (*adapter.InboundContext, error)
) )
func PeekStream(ctx context.Context, conn net.Conn, buffer *buf.Buffer, timeout time.Duration, sniffers ...StreamSniffer) (*adapter.InboundContext, error) { func PeekStream(ctx context.Context, conn net.Conn, buffer *buf.Buffer, sniffers ...StreamSniffer) (*adapter.InboundContext, error) {
if timeout == 0 { err := conn.SetReadDeadline(time.Now().Add(C.ReadPayloadTimeout))
timeout = C.ReadPayloadTimeout
}
err := conn.SetReadDeadline(time.Now().Add(timeout))
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -32,25 +30,23 @@ func PeekStream(ctx context.Context, conn net.Conn, buffer *buf.Buffer, timeout
return nil, err return nil, err
} }
var metadata *adapter.InboundContext var metadata *adapter.InboundContext
var errors []error
for _, sniffer := range sniffers { for _, sniffer := range sniffers {
metadata, err = sniffer(ctx, bytes.NewReader(buffer.Bytes())) metadata, err = sniffer(ctx, bytes.NewReader(buffer.Bytes()))
if metadata != nil { if err != nil {
return metadata, nil continue
} }
errors = append(errors, err) return metadata, nil
} }
return nil, E.Errors(errors...) return nil, os.ErrInvalid
} }
func PeekPacket(ctx context.Context, packet []byte, sniffers ...PacketSniffer) (*adapter.InboundContext, error) { func PeekPacket(ctx context.Context, packet []byte, sniffers ...PacketSniffer) (*adapter.InboundContext, error) {
var errors []error
for _, sniffer := range sniffers { for _, sniffer := range sniffers {
metadata, err := sniffer(ctx, packet) sniffMetadata, err := sniffer(ctx, packet)
if metadata != nil { if err != nil {
return metadata, nil continue
} }
errors = append(errors, err) return sniffMetadata, nil
} }
return nil, E.Errors(errors...) return nil, os.ErrInvalid
} }
-70
View File
@@ -1,70 +0,0 @@
package tls
import (
"context"
"net"
"os"
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
aTLS "github.com/sagernet/sing/common/tls"
)
func NewDialerFromOptions(router adapter.Router, dialer N.Dialer, serverAddress string, options option.OutboundTLSOptions) (N.Dialer, error) {
if !options.Enabled {
return dialer, nil
}
config, err := NewClient(router, serverAddress, options)
if err != nil {
return nil, err
}
return NewDialer(dialer, config), nil
}
func NewClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
if !options.Enabled {
return nil, nil
}
if options.ECH != nil && options.ECH.Enabled {
return NewECHClient(router, serverAddress, options)
} else if options.Reality != nil && options.Reality.Enabled {
return NewRealityClient(router, serverAddress, options)
} else if options.UTLS != nil && options.UTLS.Enabled {
return NewUTLSClient(router, serverAddress, options)
} else {
return NewSTDClient(router, serverAddress, options)
}
}
func ClientHandshake(ctx context.Context, conn net.Conn, config Config) (Conn, error) {
ctx, cancel := context.WithTimeout(ctx, C.TCPTimeout)
defer cancel()
return aTLS.ClientHandshake(ctx, conn, config)
}
type Dialer struct {
dialer N.Dialer
config Config
}
func NewDialer(dialer N.Dialer, config Config) N.Dialer {
return &Dialer{dialer, config}
}
func (d *Dialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
if network != N.NetworkTCP {
return nil, os.ErrInvalid
}
conn, err := d.dialer.DialContext(ctx, network, destination)
if err != nil {
return nil, err
}
return ClientHandshake(ctx, conn, d.config)
}
func (d *Dialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
return nil, os.ErrInvalid
}
-12
View File
@@ -1,12 +0,0 @@
package tls
const (
VersionTLS10 = 0x0301
VersionTLS11 = 0x0302
VersionTLS12 = 0x0303
VersionTLS13 = 0x0304
// Deprecated: SSLv3 is cryptographically broken, and is no longer
// supported by this package. See golang.org/issue/32716.
VersionSSL30 = 0x0300
)
-36
View File
@@ -1,36 +0,0 @@
package tls
import (
"crypto/tls"
E "github.com/sagernet/sing/common/exceptions"
aTLS "github.com/sagernet/sing/common/tls"
)
type (
Config = aTLS.Config
ConfigCompat = aTLS.ConfigCompat
ServerConfig = aTLS.ServerConfig
ServerConfigCompat = aTLS.ServerConfigCompat
WithSessionIDGenerator = aTLS.WithSessionIDGenerator
Conn = aTLS.Conn
STDConfig = tls.Config
STDConn = tls.Conn
ConnectionState = tls.ConnectionState
)
func ParseTLSVersion(version string) (uint16, error) {
switch version {
case "1.0":
return tls.VersionTLS10, nil
case "1.1":
return tls.VersionTLS11, nil
case "1.2":
return tls.VersionTLS12, nil
case "1.3":
return tls.VersionTLS13, nil
default:
return 0, E.New("unknown tls version:", version)
}
}
-226
View File
@@ -1,226 +0,0 @@
//go:build with_ech
package tls
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"net"
"net/netip"
"os"
cftls "github.com/sagernet/cloudflare-tls"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-dns"
E "github.com/sagernet/sing/common/exceptions"
mDNS "github.com/miekg/dns"
)
type ECHClientConfig struct {
config *cftls.Config
}
func (e *ECHClientConfig) ServerName() string {
return e.config.ServerName
}
func (e *ECHClientConfig) SetServerName(serverName string) {
e.config.ServerName = serverName
}
func (e *ECHClientConfig) NextProtos() []string {
return e.config.NextProtos
}
func (e *ECHClientConfig) SetNextProtos(nextProto []string) {
e.config.NextProtos = nextProto
}
func (e *ECHClientConfig) Config() (*STDConfig, error) {
return nil, E.New("unsupported usage for ECH")
}
func (e *ECHClientConfig) Client(conn net.Conn) (Conn, error) {
return &echConnWrapper{cftls.Client(conn, e.config)}, nil
}
func (e *ECHClientConfig) Clone() Config {
return &ECHClientConfig{
config: e.config.Clone(),
}
}
type echConnWrapper struct {
*cftls.Conn
}
func (c *echConnWrapper) ConnectionState() tls.ConnectionState {
state := c.Conn.ConnectionState()
return tls.ConnectionState{
Version: state.Version,
HandshakeComplete: state.HandshakeComplete,
DidResume: state.DidResume,
CipherSuite: state.CipherSuite,
NegotiatedProtocol: state.NegotiatedProtocol,
NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
ServerName: state.ServerName,
PeerCertificates: state.PeerCertificates,
VerifiedChains: state.VerifiedChains,
SignedCertificateTimestamps: state.SignedCertificateTimestamps,
OCSPResponse: state.OCSPResponse,
TLSUnique: state.TLSUnique,
}
}
func (c *echConnWrapper) Upstream() any {
return c.Conn
}
func NewECHClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
var serverName string
if options.ServerName != "" {
serverName = options.ServerName
} else if serverAddress != "" {
if _, err := netip.ParseAddr(serverName); err != nil {
serverName = serverAddress
}
}
if serverName == "" && !options.Insecure {
return nil, E.New("missing server_name or insecure=true")
}
var tlsConfig cftls.Config
tlsConfig.Time = router.TimeFunc()
if options.DisableSNI {
tlsConfig.ServerName = "127.0.0.1"
} else {
tlsConfig.ServerName = serverName
}
if options.Insecure {
tlsConfig.InsecureSkipVerify = options.Insecure
} else if options.DisableSNI {
tlsConfig.InsecureSkipVerify = true
tlsConfig.VerifyConnection = func(state cftls.ConnectionState) error {
verifyOptions := x509.VerifyOptions{
DNSName: serverName,
Intermediates: x509.NewCertPool(),
}
for _, cert := range state.PeerCertificates[1:] {
verifyOptions.Intermediates.AddCert(cert)
}
_, err := state.PeerCertificates[0].Verify(verifyOptions)
return err
}
}
if len(options.ALPN) > 0 {
tlsConfig.NextProtos = options.ALPN
}
if options.MinVersion != "" {
minVersion, err := ParseTLSVersion(options.MinVersion)
if err != nil {
return nil, E.Cause(err, "parse min_version")
}
tlsConfig.MinVersion = minVersion
}
if options.MaxVersion != "" {
maxVersion, err := ParseTLSVersion(options.MaxVersion)
if err != nil {
return nil, E.Cause(err, "parse max_version")
}
tlsConfig.MaxVersion = maxVersion
}
if options.CipherSuites != nil {
find:
for _, cipherSuite := range options.CipherSuites {
for _, tlsCipherSuite := range cftls.CipherSuites() {
if cipherSuite == tlsCipherSuite.Name {
tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
continue find
}
}
return nil, E.New("unknown cipher_suite: ", cipherSuite)
}
}
var certificate []byte
if options.Certificate != "" {
certificate = []byte(options.Certificate)
} else if options.CertificatePath != "" {
content, err := os.ReadFile(options.CertificatePath)
if err != nil {
return nil, E.Cause(err, "read certificate")
}
certificate = content
}
if len(certificate) > 0 {
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(certificate) {
return nil, E.New("failed to parse certificate:\n\n", certificate)
}
tlsConfig.RootCAs = certPool
}
// ECH Config
tlsConfig.ECHEnabled = true
tlsConfig.PQSignatureSchemesEnabled = options.ECH.PQSignatureSchemesEnabled
tlsConfig.DynamicRecordSizingDisabled = options.ECH.DynamicRecordSizingDisabled
if options.ECH.Config != "" {
clientConfigContent, err := base64.StdEncoding.DecodeString(options.ECH.Config)
if err != nil {
return nil, err
}
clientConfig, err := cftls.UnmarshalECHConfigs(clientConfigContent)
if err != nil {
return nil, err
}
tlsConfig.ClientECHConfigs = clientConfig
} else {
tlsConfig.GetClientECHConfigs = fetchECHClientConfig(router)
}
return &ECHClientConfig{&tlsConfig}, nil
}
func fetchECHClientConfig(router adapter.Router) func(ctx context.Context, serverName string) ([]cftls.ECHConfig, error) {
return func(ctx context.Context, serverName string) ([]cftls.ECHConfig, error) {
message := &mDNS.Msg{
MsgHdr: mDNS.MsgHdr{
RecursionDesired: true,
},
Question: []mDNS.Question{
{
Name: serverName + ".",
Qtype: mDNS.TypeHTTPS,
Qclass: mDNS.ClassINET,
},
},
}
response, err := router.Exchange(ctx, message)
if err != nil {
return nil, err
}
if response.Rcode != mDNS.RcodeSuccess {
return nil, dns.RCodeError(response.Rcode)
}
for _, rr := range response.Answer {
switch resource := rr.(type) {
case *mDNS.HTTPS:
for _, value := range resource.Value {
if value.Key().String() == "ech" {
echConfig, err := base64.StdEncoding.DecodeString(value.String())
if err != nil {
return nil, E.Cause(err, "decode ECH config")
}
return cftls.UnmarshalECHConfigs(echConfig)
}
}
default:
return nil, E.New("unknown resource record type: ", resource.Header().Rrtype)
}
}
return nil, E.New("no ECH config found")
}
}
-13
View File
@@ -1,13 +0,0 @@
//go:build !with_ech
package tls
import (
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
)
func NewECHClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
return nil, E.New(`ECH is not included in this build, rebuild with -tags with_ech`)
}
-53
View File
@@ -1,53 +0,0 @@
package tls
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"time"
)
func GenerateKeyPair(timeFunc func() time.Time, serverName string) (*tls.Certificate, error) {
if timeFunc == nil {
timeFunc = time.Now
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return nil, err
}
template := &x509.Certificate{
SerialNumber: serialNumber,
NotBefore: timeFunc().Add(time.Hour * -1),
NotAfter: timeFunc().Add(time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
Subject: pkix.Name{
CommonName: serverName,
},
DNSNames: []string{serverName},
}
publicDer, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key)
if err != nil {
return nil, err
}
privateDer, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return nil, err
}
publicPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: publicDer})
privPem := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privateDer})
keyPair, err := tls.X509KeyPair(publicPem, privPem)
if err != nil {
return nil, err
}
return &keyPair, err
}
-230
View File
@@ -1,230 +0,0 @@
//go:build with_utls
package tls
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/ed25519"
"crypto/hmac"
"crypto/sha256"
"crypto/sha512"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
mRand "math/rand"
"net"
"net/http"
"reflect"
"strings"
"time"
"unsafe"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common/debug"
E "github.com/sagernet/sing/common/exceptions"
aTLS "github.com/sagernet/sing/common/tls"
utls "github.com/sagernet/utls"
"golang.org/x/crypto/hkdf"
"golang.org/x/net/http2"
)
var _ ConfigCompat = (*RealityClientConfig)(nil)
type RealityClientConfig struct {
uClient *UTLSClientConfig
publicKey []byte
shortID []byte
}
func NewRealityClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (*RealityClientConfig, error) {
if options.UTLS == nil || !options.UTLS.Enabled {
return nil, E.New("uTLS is required by reality client")
}
uClient, err := NewUTLSClient(router, serverAddress, options)
if err != nil {
return nil, err
}
publicKey, err := base64.RawURLEncoding.DecodeString(options.Reality.PublicKey)
if err != nil {
return nil, E.Cause(err, "decode public_key")
}
if len(publicKey) != 32 {
return nil, E.New("invalid public_key")
}
shortID, err := hex.DecodeString(options.Reality.ShortID)
if err != nil {
return nil, E.Cause(err, "decode short_id")
}
if len(shortID) != 8 {
return nil, E.New("invalid short_id")
}
return &RealityClientConfig{uClient, publicKey, shortID}, nil
}
func (e *RealityClientConfig) ServerName() string {
return e.uClient.ServerName()
}
func (e *RealityClientConfig) SetServerName(serverName string) {
e.uClient.SetServerName(serverName)
}
func (e *RealityClientConfig) NextProtos() []string {
return e.uClient.NextProtos()
}
func (e *RealityClientConfig) SetNextProtos(nextProto []string) {
e.uClient.SetNextProtos(nextProto)
}
func (e *RealityClientConfig) Config() (*STDConfig, error) {
return nil, E.New("unsupported usage for reality")
}
func (e *RealityClientConfig) Client(conn net.Conn) (Conn, error) {
return ClientHandshake(context.Background(), conn, e)
}
func (e *RealityClientConfig) ClientHandshake(ctx context.Context, conn net.Conn) (aTLS.Conn, error) {
verifier := &realityVerifier{
serverName: e.uClient.ServerName(),
}
uConfig := e.uClient.config.Clone()
uConfig.InsecureSkipVerify = true
uConfig.SessionTicketsDisabled = true
uConfig.VerifyPeerCertificate = verifier.VerifyPeerCertificate
uConn := utls.UClient(conn, uConfig, e.uClient.id)
verifier.UConn = uConn
err := uConn.BuildHandshakeState()
if err != nil {
return nil, err
}
hello := uConn.HandshakeState.Hello
hello.SessionId = make([]byte, 32)
copy(hello.Raw[39:], hello.SessionId)
var nowTime time.Time
if uConfig.Time != nil {
nowTime = uConfig.Time()
} else {
nowTime = time.Now()
}
binary.BigEndian.PutUint64(hello.SessionId, uint64(nowTime.Unix()))
hello.SessionId[0] = 1
hello.SessionId[1] = 7
hello.SessionId[2] = 5
copy(hello.SessionId[8:], e.shortID)
if debug.Enabled {
fmt.Printf("REALITY hello.sessionId[:16]: %v\n", hello.SessionId[:16])
}
authKey := uConn.HandshakeState.State13.EcdheParams.SharedKey(e.publicKey)
if authKey == nil {
return nil, E.New("nil auth_key")
}
verifier.authKey = authKey
_, err = hkdf.New(sha256.New, authKey, hello.Random[:20], []byte("REALITY")).Read(authKey)
if err != nil {
return nil, err
}
aesBlock, _ := aes.NewCipher(authKey)
aesGcmCipher, _ := cipher.NewGCM(aesBlock)
aesGcmCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
copy(hello.Raw[39:], hello.SessionId)
if debug.Enabled {
fmt.Printf("REALITY hello.sessionId: %v\n", hello.SessionId)
fmt.Printf("REALITY uConn.AuthKey: %v\n", authKey)
}
err = uConn.HandshakeContext(ctx)
if err != nil {
return nil, err
}
if debug.Enabled {
fmt.Printf("REALITY Conn.Verified: %v\n", verifier.verified)
}
if !verifier.verified {
go realityClientFallback(uConn, e.uClient.ServerName(), e.uClient.id)
return nil, E.New("reality verification failed")
}
return &utlsConnWrapper{uConn}, nil
}
func realityClientFallback(uConn net.Conn, serverName string, fingerprint utls.ClientHelloID) {
defer uConn.Close()
client := &http.Client{
Transport: &http2.Transport{
DialTLSContext: func(ctx context.Context, network, addr string, config *tls.Config) (net.Conn, error) {
return uConn, nil
},
},
}
request, _ := http.NewRequest("GET", "https://"+serverName, nil)
request.Header.Set("User-Agent", fingerprint.Client)
request.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", mRand.Intn(32)+30)})
response, err := client.Do(request)
if err != nil {
return
}
_, _ = io.Copy(io.Discard, response.Body)
response.Body.Close()
}
func (e *RealityClientConfig) SetSessionIDGenerator(generator func(clientHello []byte, sessionID []byte) error) {
e.uClient.config.SessionIDGenerator = generator
}
func (e *RealityClientConfig) Clone() Config {
return &RealityClientConfig{
e.uClient.Clone().(*UTLSClientConfig),
e.publicKey,
e.shortID,
}
}
type realityVerifier struct {
*utls.UConn
serverName string
authKey []byte
verified bool
}
func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates")
certs := *(*([]*x509.Certificate))(unsafe.Pointer(uintptr(unsafe.Pointer(c.Conn)) + p.Offset))
if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok {
h := hmac.New(sha512.New, c.authKey)
h.Write(pub)
if bytes.Equal(h.Sum(nil), certs[0].Signature) {
c.verified = true
return nil
}
}
opts := x509.VerifyOptions{
DNSName: c.serverName,
Intermediates: x509.NewCertPool(),
}
for _, cert := range certs[1:] {
opts.Intermediates.AddCert(cert)
}
if _, err := certs[0].Verify(opts); err != nil {
return err
}
return nil
}
-192
View File
@@ -1,192 +0,0 @@
//go:build with_reality_server
package tls
import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"net"
"time"
"github.com/sagernet/reality"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/dialer"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common/debug"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
var _ ServerConfigCompat = (*RealityServerConfig)(nil)
type RealityServerConfig struct {
config *reality.Config
}
func NewRealityServer(ctx context.Context, router adapter.Router, logger log.Logger, options option.InboundTLSOptions) (*RealityServerConfig, error) {
var tlsConfig reality.Config
if options.ACME != nil && len(options.ACME.Domain) > 0 {
return nil, E.New("acme is unavailable in reality")
}
tlsConfig.Time = router.TimeFunc()
if options.ServerName != "" {
tlsConfig.ServerName = options.ServerName
}
if len(options.ALPN) > 0 {
tlsConfig.NextProtos = append(tlsConfig.NextProtos, options.ALPN...)
}
if options.MinVersion != "" {
minVersion, err := ParseTLSVersion(options.MinVersion)
if err != nil {
return nil, E.Cause(err, "parse min_version")
}
tlsConfig.MinVersion = minVersion
}
if options.MaxVersion != "" {
maxVersion, err := ParseTLSVersion(options.MaxVersion)
if err != nil {
return nil, E.Cause(err, "parse max_version")
}
tlsConfig.MaxVersion = maxVersion
}
if options.CipherSuites != nil {
find:
for _, cipherSuite := range options.CipherSuites {
for _, tlsCipherSuite := range tls.CipherSuites() {
if cipherSuite == tlsCipherSuite.Name {
tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
continue find
}
}
return nil, E.New("unknown cipher_suite: ", cipherSuite)
}
}
if options.Certificate != "" || options.CertificatePath != "" {
return nil, E.New("certificate is unavailable in reality")
}
if options.Key != "" || options.KeyPath != "" {
return nil, E.New("key is unavailable in reality")
}
tlsConfig.SessionTicketsDisabled = true
tlsConfig.Type = N.NetworkTCP
tlsConfig.Dest = options.Reality.Handshake.ServerOptions.Build().String()
tlsConfig.ServerNames = map[string]bool{options.ServerName: true}
privateKey, err := base64.RawURLEncoding.DecodeString(options.Reality.PrivateKey)
if err != nil {
return nil, E.Cause(err, "decode private key")
}
if len(privateKey) != 32 {
return nil, E.New("invalid private key")
}
tlsConfig.PrivateKey = privateKey
tlsConfig.MaxTimeDiff = time.Duration(options.Reality.MaxTimeDifference)
tlsConfig.ShortIds = make(map[[8]byte]bool)
for i, shortID := range options.Reality.ShortID {
var shortIDBytesArray [8]byte
decodedLen, err := hex.Decode(shortIDBytesArray[:], []byte(shortID))
if err != nil {
return nil, E.Cause(err, "decode short_id[", i, "]: ", shortID)
}
if decodedLen != 8 {
return nil, E.New("invalid short_id[", i, "]: ", shortID)
}
tlsConfig.ShortIds[shortIDBytesArray] = true
}
handshakeDialer := dialer.New(router, options.Reality.Handshake.DialerOptions)
tlsConfig.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return handshakeDialer.DialContext(ctx, network, M.ParseSocksaddr(addr))
}
if debug.Enabled {
tlsConfig.Show = true
}
return &RealityServerConfig{&tlsConfig}, nil
}
func (c *RealityServerConfig) ServerName() string {
return c.config.ServerName
}
func (c *RealityServerConfig) SetServerName(serverName string) {
c.config.ServerName = serverName
}
func (c *RealityServerConfig) NextProtos() []string {
return c.config.NextProtos
}
func (c *RealityServerConfig) SetNextProtos(nextProto []string) {
c.config.NextProtos = nextProto
}
func (c *RealityServerConfig) Config() (*tls.Config, error) {
return nil, E.New("unsupported usage for reality")
}
func (c *RealityServerConfig) Client(conn net.Conn) (Conn, error) {
return ClientHandshake(context.Background(), conn, c)
}
func (c *RealityServerConfig) Start() error {
return nil
}
func (c *RealityServerConfig) Close() error {
return nil
}
func (c *RealityServerConfig) Server(conn net.Conn) (Conn, error) {
return ServerHandshake(context.Background(), conn, c)
}
func (c *RealityServerConfig) ServerHandshake(ctx context.Context, conn net.Conn) (Conn, error) {
tlsConn, err := reality.Server(ctx, conn, c.config)
if err != nil {
return nil, err
}
return &realityConnWrapper{Conn: tlsConn}, nil
}
func (c *RealityServerConfig) Clone() Config {
return &RealityServerConfig{
config: c.config.Clone(),
}
}
var _ Conn = (*realityConnWrapper)(nil)
type realityConnWrapper struct {
*reality.Conn
}
func (c *realityConnWrapper) ConnectionState() ConnectionState {
state := c.Conn.ConnectionState()
return tls.ConnectionState{
Version: state.Version,
HandshakeComplete: state.HandshakeComplete,
DidResume: state.DidResume,
CipherSuite: state.CipherSuite,
NegotiatedProtocol: state.NegotiatedProtocol,
NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
ServerName: state.ServerName,
PeerCertificates: state.PeerCertificates,
VerifiedChains: state.VerifiedChains,
SignedCertificateTimestamps: state.SignedCertificateTimestamps,
OCSPResponse: state.OCSPResponse,
TLSUnique: state.TLSUnique,
}
}
func (c *realityConnWrapper) Upstream() any {
return c.Conn
}
-16
View File
@@ -1,16 +0,0 @@
//go:build !with_reality_server
package tls
import (
"context"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
)
func NewRealityServer(ctx context.Context, router adapter.Router, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
return nil, E.New(`reality server is not included in this build, rebuild with -tags with_reality_server`)
}
-29
View File
@@ -1,29 +0,0 @@
package tls
import (
"context"
"net"
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
aTLS "github.com/sagernet/sing/common/tls"
)
func NewServer(ctx context.Context, router adapter.Router, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) {
if !options.Enabled {
return nil, nil
}
if options.Reality != nil && options.Reality.Enabled {
return NewRealityServer(ctx, router, logger, options)
} else {
return NewSTDServer(ctx, router, logger, options)
}
}
func ServerHandshake(ctx context.Context, conn net.Conn, config ServerConfig) (Conn, error) {
ctx, cancel := context.WithTimeout(ctx, C.TCPTimeout)
defer cancel()
return aTLS.ServerHandshake(ctx, conn, config)
}
-216
View File
@@ -1,216 +0,0 @@
//go:build with_utls
package tls
import (
"crypto/tls"
"crypto/x509"
"math/rand"
"net"
"net/netip"
"os"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
utls "github.com/sagernet/utls"
"golang.org/x/net/http2"
)
type UTLSClientConfig struct {
config *utls.Config
id utls.ClientHelloID
}
func (e *UTLSClientConfig) ServerName() string {
return e.config.ServerName
}
func (e *UTLSClientConfig) SetServerName(serverName string) {
e.config.ServerName = serverName
}
func (e *UTLSClientConfig) NextProtos() []string {
return e.config.NextProtos
}
func (e *UTLSClientConfig) SetNextProtos(nextProto []string) {
if len(nextProto) == 1 && nextProto[0] == http2.NextProtoTLS {
nextProto = append(nextProto, "http/1.1")
}
e.config.NextProtos = nextProto
}
func (e *UTLSClientConfig) Config() (*STDConfig, error) {
return nil, E.New("unsupported usage for uTLS")
}
func (e *UTLSClientConfig) Client(conn net.Conn) (Conn, error) {
return &utlsConnWrapper{utls.UClient(conn, e.config.Clone(), e.id)}, nil
}
func (e *UTLSClientConfig) SetSessionIDGenerator(generator func(clientHello []byte, sessionID []byte) error) {
e.config.SessionIDGenerator = generator
}
func (e *UTLSClientConfig) Clone() Config {
return &UTLSClientConfig{
config: e.config.Clone(),
id: e.id,
}
}
type utlsConnWrapper struct {
*utls.UConn
}
func (c *utlsConnWrapper) ConnectionState() tls.ConnectionState {
state := c.Conn.ConnectionState()
return tls.ConnectionState{
Version: state.Version,
HandshakeComplete: state.HandshakeComplete,
DidResume: state.DidResume,
CipherSuite: state.CipherSuite,
NegotiatedProtocol: state.NegotiatedProtocol,
NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
ServerName: state.ServerName,
PeerCertificates: state.PeerCertificates,
VerifiedChains: state.VerifiedChains,
SignedCertificateTimestamps: state.SignedCertificateTimestamps,
OCSPResponse: state.OCSPResponse,
TLSUnique: state.TLSUnique,
}
}
func (c *utlsConnWrapper) Upstream() any {
return c.UConn
}
func NewUTLSClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (*UTLSClientConfig, error) {
var serverName string
if options.ServerName != "" {
serverName = options.ServerName
} else if serverAddress != "" {
if _, err := netip.ParseAddr(serverName); err != nil {
serverName = serverAddress
}
}
if serverName == "" && !options.Insecure {
return nil, E.New("missing server_name or insecure=true")
}
var tlsConfig utls.Config
tlsConfig.Time = router.TimeFunc()
if options.DisableSNI {
tlsConfig.ServerName = "127.0.0.1"
} else {
tlsConfig.ServerName = serverName
}
if options.Insecure {
tlsConfig.InsecureSkipVerify = options.Insecure
} else if options.DisableSNI {
return nil, E.New("disable_sni is unsupported in uTLS")
}
if len(options.ALPN) > 0 {
tlsConfig.NextProtos = options.ALPN
}
if options.MinVersion != "" {
minVersion, err := ParseTLSVersion(options.MinVersion)
if err != nil {
return nil, E.Cause(err, "parse min_version")
}
tlsConfig.MinVersion = minVersion
}
if options.MaxVersion != "" {
maxVersion, err := ParseTLSVersion(options.MaxVersion)
if err != nil {
return nil, E.Cause(err, "parse max_version")
}
tlsConfig.MaxVersion = maxVersion
}
if options.CipherSuites != nil {
find:
for _, cipherSuite := range options.CipherSuites {
for _, tlsCipherSuite := range tls.CipherSuites() {
if cipherSuite == tlsCipherSuite.Name {
tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
continue find
}
}
return nil, E.New("unknown cipher_suite: ", cipherSuite)
}
}
var certificate []byte
if options.Certificate != "" {
certificate = []byte(options.Certificate)
} else if options.CertificatePath != "" {
content, err := os.ReadFile(options.CertificatePath)
if err != nil {
return nil, E.Cause(err, "read certificate")
}
certificate = content
}
if len(certificate) > 0 {
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(certificate) {
return nil, E.New("failed to parse certificate:\n\n", certificate)
}
tlsConfig.RootCAs = certPool
}
id, err := uTLSClientHelloID(options.UTLS.Fingerprint)
if err != nil {
return nil, err
}
return &UTLSClientConfig{&tlsConfig, id}, nil
}
var (
randomFingerprint utls.ClientHelloID
randomizedFingerprint utls.ClientHelloID
)
func init() {
modernFingerprints := []utls.ClientHelloID{
utls.HelloChrome_Auto,
utls.HelloFirefox_Auto,
utls.HelloEdge_Auto,
utls.HelloSafari_Auto,
utls.HelloIOS_Auto,
}
randomFingerprint = modernFingerprints[rand.Intn(len(modernFingerprints))]
weights := utls.DefaultWeights
weights.TLSVersMax_Set_VersionTLS13 = 1
weights.FirstKeyShare_Set_CurveP256 = 0
randomizedFingerprint = utls.HelloRandomized
randomizedFingerprint.Seed, _ = utls.NewPRNGSeed()
randomizedFingerprint.Weights = &weights
}
func uTLSClientHelloID(name string) (utls.ClientHelloID, error) {
switch name {
case "chrome", "":
return utls.HelloChrome_Auto, nil
case "firefox":
return utls.HelloFirefox_Auto, nil
case "edge":
return utls.HelloEdge_Auto, nil
case "safari":
return utls.HelloSafari_Auto, nil
case "360":
return utls.Hello360_Auto, nil
case "qq":
return utls.HelloQQ_Auto, nil
case "ios":
return utls.HelloIOS_Auto, nil
case "android":
return utls.HelloAndroid_11_OkHttp, nil
case "random":
return randomFingerprint, nil
case "randomized":
return randomizedFingerprint, nil
default:
return utls.ClientHelloID{}, E.New("unknown uTLS fingerprint: ", name)
}
}
-17
View File
@@ -1,17 +0,0 @@
//go:build !with_utls
package tls
import (
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
)
func NewUTLSClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
return nil, E.New(`uTLS is not included in this build, rebuild with -tags with_utls`)
}
func NewRealityClient(router adapter.Router, serverAddress string, options option.OutboundTLSOptions) (Config, error) {
return nil, E.New(`uTLS, which is required by reality client is not included in this build, rebuild with -tags with_utls`)
}
+145
View File
@@ -0,0 +1,145 @@
package trafficcontrol
import (
"io"
"net"
"sync"
"sync/atomic"
"github.com/sagernet/sing/common/buf"
"github.com/sagernet/sing/common/bufio"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
)
type Manager[U comparable] struct {
access sync.Mutex
users map[U]*Traffic
}
type Traffic struct {
Upload uint64
Download uint64
}
func NewManager[U comparable]() *Manager[U] {
return &Manager[U]{
users: make(map[U]*Traffic),
}
}
func (m *Manager[U]) Reset() {
m.users = make(map[U]*Traffic)
}
func (m *Manager[U]) TrackConnection(user U, conn net.Conn) net.Conn {
m.access.Lock()
defer m.access.Unlock()
var traffic *Traffic
if t, loaded := m.users[user]; loaded {
traffic = t
} else {
traffic = new(Traffic)
m.users[user] = traffic
}
return &TrackConn{conn, traffic}
}
func (m *Manager[U]) TrackPacketConnection(user U, conn N.PacketConn) N.PacketConn {
m.access.Lock()
defer m.access.Unlock()
var traffic *Traffic
if t, loaded := m.users[user]; loaded {
traffic = t
} else {
traffic = new(Traffic)
m.users[user] = traffic
}
return &TrackPacketConn{conn, traffic}
}
func (m *Manager[U]) ReadTraffics() map[U]Traffic {
m.access.Lock()
defer m.access.Unlock()
trafficMap := make(map[U]Traffic)
for user, traffic := range m.users {
upload := atomic.SwapUint64(&traffic.Upload, 0)
download := atomic.SwapUint64(&traffic.Download, 0)
if upload == 0 && download == 0 {
continue
}
trafficMap[user] = Traffic{
Upload: upload,
Download: download,
}
}
return trafficMap
}
type TrackConn struct {
net.Conn
*Traffic
}
func (c *TrackConn) Read(p []byte) (n int, err error) {
n, err = c.Conn.Read(p)
if n > 0 {
atomic.AddUint64(&c.Upload, uint64(n))
}
return
}
func (c *TrackConn) Write(p []byte) (n int, err error) {
n, err = c.Conn.Write(p)
if n > 0 {
atomic.AddUint64(&c.Download, uint64(n))
}
return
}
func (c *TrackConn) WriteTo(w io.Writer) (n int64, err error) {
n, err = bufio.Copy(w, c.Conn)
if n > 0 {
atomic.AddUint64(&c.Upload, uint64(n))
}
return
}
func (c *TrackConn) ReadFrom(r io.Reader) (n int64, err error) {
n, err = bufio.Copy(c.Conn, r)
if n > 0 {
atomic.AddUint64(&c.Download, uint64(n))
}
return
}
func (c *TrackConn) Upstream() any {
return c.Conn
}
type TrackPacketConn struct {
N.PacketConn
*Traffic
}
func (c *TrackPacketConn) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) {
destination, err := c.PacketConn.ReadPacket(buffer)
if err == nil {
atomic.AddUint64(&c.Upload, uint64(buffer.Len()))
}
return destination, err
}
func (c *TrackPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
n := buffer.Len()
err := c.PacketConn.WritePacket(buffer, destination)
if err == nil {
atomic.AddUint64(&c.Download, uint64(n))
}
return err
}
func (c *TrackPacketConn) Upstream() any {
return c.PacketConn
}
-8
View File
@@ -1,8 +0,0 @@
package constant
import "time"
const (
DHCPTTL = time.Hour
DHCPTimeout = time.Minute
)
-2
View File
@@ -3,5 +3,3 @@ package constant
import E "github.com/sagernet/sing/common/exceptions" import E "github.com/sagernet/sing/common/exceptions"
var ErrTLSRequired = E.New("TLS required") var ErrTLSRequired = E.New("TLS required")
var ErrQUICNotIncluded = E.New(`QUIC is not included in this build, rebuild with -tags with_quic`)
+1 -16
View File
@@ -3,28 +3,13 @@ package constant
import ( import (
"os" "os"
"path/filepath" "path/filepath"
"strings"
"github.com/sagernet/sing/common/rw" "github.com/sagernet/sing/common/rw"
) )
const dirName = "sing-box" const dirName = "sing-box"
var ( var resourcePaths []string
basePath string
resourcePaths []string
)
func BasePath(name string) string {
if basePath == "" || strings.HasPrefix(name, "/") {
return name
}
return filepath.Join(basePath, name)
}
func SetBasePath(path string) {
basePath = path
}
func FindPath(name string) (string, bool) { func FindPath(name string) (string, bool) {
name = os.ExpandEnv(name) name = os.ExpandEnv(name)
+18 -21
View File
@@ -1,29 +1,26 @@
package constant package constant
const ( const (
TypeTun = "tun" TypeTun = "tun"
TypeRedirect = "redirect" TypeRedirect = "redirect"
TypeTProxy = "tproxy" TypeTProxy = "tproxy"
TypeDirect = "direct" TypeDirect = "direct"
TypeBlock = "block" TypeBlock = "block"
TypeDNS = "dns" TypeDNS = "dns"
TypeSocks = "socks" TypeSocks = "socks"
TypeHTTP = "http" TypeHTTP = "http"
TypeMixed = "mixed" TypeMixed = "mixed"
TypeShadowsocks = "shadowsocks" TypeShadowsocks = "shadowsocks"
TypeVMess = "vmess" TypeVMess = "vmess"
TypeTrojan = "trojan" TypeTrojan = "trojan"
TypeNaive = "naive" TypeNaive = "naive"
TypeWireGuard = "wireguard" TypeWireGuard = "wireguard"
TypeHysteria = "hysteria" TypeHysteria = "hysteria"
TypeTor = "tor" TypeTor = "tor"
TypeSSH = "ssh" TypeSSH = "ssh"
TypeShadowTLS = "shadowtls" TypeShadowTLS = "shadowtls"
TypeShadowsocksR = "shadowsocksr"
TypeVLESS = "vless"
) )
const ( const (
TypeSelector = "selector" TypeSelector = "selector"
TypeURLTest = "urltest"
) )
+5
View File
@@ -0,0 +1,5 @@
//go:build with_quic
package constant
const QUIC_AVAILABLE = true
+9
View File
@@ -0,0 +1,9 @@
//go:build !with_quic
package constant
import E "github.com/sagernet/sing/common/exceptions"
const QUIC_AVAILABLE = false
var ErrQUICNotIncluded = E.New(`QUIC is not included in this build, rebuild with -tags with_quic`)
+6 -7
View File
@@ -3,11 +3,10 @@ package constant
import "time" import "time"
const ( const (
TCPTimeout = 5 * time.Second TCPTimeout = 5 * time.Second
ReadPayloadTimeout = 300 * time.Millisecond ReadPayloadTimeout = 300 * time.Millisecond
DNSTimeout = 10 * time.Second DNSTimeout = 10 * time.Second
QUICTimeout = 30 * time.Second QUICTimeout = 30 * time.Second
STUNTimeout = 15 * time.Second STUNTimeout = 15 * time.Second
UDPTimeout = 5 * time.Minute UDPTimeout = 5 * time.Minute
DefaultURLTestInterval = 1 * time.Minute
) )
+4 -1
View File
@@ -1,3 +1,6 @@
package constant package constant
var Version = "unknown" var (
Version = "1.0.1"
Commit = ""
)
-37
View File
@@ -1,37 +0,0 @@
<svg width="1027" height="1109" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" overflow="hidden">
<defs>
<filter id="fx0" x="-10%" y="-10%" width="120%" height="120%" filterUnits="userSpaceOnUse" primitiveUnits="userSpaceOnUse">
<feComponentTransfer color-interpolation-filters="sRGB">
<feFuncR type="discrete" tableValues="0 0" />
<feFuncG type="discrete" tableValues="0 0" />
<feFuncB type="discrete" tableValues="0 0" />
<feFuncA type="linear" slope="0.4" intercept="0" />
</feComponentTransfer>
<feGaussianBlur stdDeviation="4.58333 4.58333" />
</filter>
<clipPath id="clip1">
<rect x="692" y="855" width="1027" height="1109" />
</clipPath>
<clipPath id="clip2">
<rect x="-2" y="-2" width="541" height="786" />
</clipPath>
<clipPath id="clip3">
<rect x="0" y="0" width="535" height="782" />
</clipPath>
</defs>
<g clip-path="url(#clip1)" transform="translate(-692 -855)">
<path d="M692 1191 692 1575.69C692 1640.41 731.499 1651.19 731.499 1651.19L1148.03 1931.62C1212.66 1974.77 1194.71 1881.29 1194.71 1881.29L1194.71 1528.96 692 1191Z" fill="#37474F" fill-rule="evenodd" />
<g clip-path="url(#clip2)" filter="url(#fx0)" transform="translate(1184 1182)">
<g clip-path="url(#clip3)">
<path d="M520.482 15.4819 520.482 400.176C520.482 464.89 480.983 475.676 480.983 475.676 480.983 475.676 129.086 712.963 64.4523 756.106-0.181814 799.25 17.7721 705.773 17.7721 705.773L17.7721 353.437 520.482 15.4819Z" fill="#455A64" fill-rule="evenodd" />
</g>
</g>
<path d="M1698 1191 1698 1575.69C1698 1640.41 1658.5 1651.19 1658.5 1651.19 1658.5 1651.19 1306.6 1888.48 1241.97 1931.62 1177.34 1974.77 1195.29 1881.29 1195.29 1881.29L1195.29 1528.96 1698 1191Z" fill="#455A64" fill-rule="evenodd" />
<path d="M1241.71 868.473C1212.96 850.509 1169.85 850.509 1144.7 868.473L713.557 1163.07C684.814 1181.04 684.814 1213.37 713.557 1231.33L1144.7 1529.53C1173.44 1547.49 1216.56 1547.49 1241.71 1529.53L1676.44 1227.74C1705.19 1209.78 1705.19 1177.44 1676.44 1159.48L1241.71 868.473Z" fill="#546E7A" fill-rule="evenodd" />
<path d="M1195 1949C1173.4 1949 1159 1935.19 1159 1917.92L1159 1531.08C1159 1513.82 1173.4 1500 1195 1500 1216.6 1500 1231 1513.82 1231 1531.08L1231 1914.46C1231 1935.19 1216.6 1949 1195 1949Z" fill="#546E7A" fill-rule="evenodd" />
<path d="M1553.92 1435.92C1553.92 1471.89 1557.5 1486.27 1518.03 1511.45L1428.32 1568.99C1388.85 1594.17 1374.5 1572.59 1374.5 1540.22L1374.5 1446.71C1374.5 1439.52 1374.5 1435.92 1363.73 1428.73 1270.43 1363.99 911.591 1115.84 847 1069.09L1012.07 954C1058.72 982.772 1399.61 1209.35 1539.56 1306.45 1546.74 1310.05 1550.33 1317.24 1550.33 1320.84L1550.33 1435.92Z" fill="#99AAB5" fill-rule="evenodd" />
<path d="M1543.41 1310.21C1399.82 1213.17 1058.79 986.752 1015.72 958L951.103 997.534 847 1069.41C911.615 1116.14 1270.59 1360.53 1363.92 1425.22 1371.1 1428.81 1371.1 1432.41 1371.1 1436L1547 1313.8C1547 1313.8 1547 1310.21 1543.41 1310.21Z" fill="#CCD6DD" fill-rule="evenodd" />
<path d="M1554.9 1435.48 1554.9 1324.19C1554.9 1317.01 1551.3 1313.42 1544.11 1309.83 1400.28 1212.89 1058.67 986.721 1015.51 958L940 1008.26C1062.26 1090.83 1389.49 1306.24 1475.79 1367.27 1486.58 1374.45 1486.58 1381.63 1486.58 1385.22L1486.58 1536 1522.54 1510.87C1558.5 1485.74 1554.9 1467.79 1554.9 1435.48Z" fill="#CCD6DD" fill-rule="evenodd" />
<path d="M1543.23 1309.95C1399.6 1212.98 1058.49 986.731 1015.4 958L940 1008.28C1062.08 1090.88 1388.83 1306.36 1475.01 1367.41 1475.01 1367.41 1478.6 1371 1478.6 1371L1554 1317.13C1546.82 1313.54 1546.82 1309.95 1543.23 1309.95Z" fill="#E1E8ED" fill-rule="evenodd" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.7 KiB

-410
View File
@@ -1,413 +1,3 @@
#### 1.2-beta8
* Update reality and uTLS libraries
* Fix `auto_detect_interface` incorrectly identifying the default interface on Windows
#### 1.2-beta7
* Fix the compatibility issue between VLESS's vision sub-protocol and the Xray-core client
* Improve the stability of the VMESS server
#### 1.2-beta6
* Introducing our [new iOS client application](/installation/clients/sfi)
* Add [platform options](/configuration/inbound/tun#platform) for tun inbound
* Add custom TLS server support for http based v2ray transports
* Add generate commands
* Enable XUDP by default in VLESS
* Update reality server
* Update vision protocol
* Fixed [user flow in vless server](/configuration/inbound/vless#usersflow)
* Bug fixes
* Update dependencies
#### 1.2-beta5
* Add [VLESS server](/configuration/inbound/vless) and [vision](/configuration/outbound/vless#flow) support
* Add [reality TLS](/configuration/shared/tls) support
* Fix match private address
#### 1.1.6
* Improve vmess request
* Fix ipv6 redirect on Linux
* Fix match geoip private
* Fix parse hysteria UDP message
* Fix socks connect response
* Disable vmess header protection if transport enabled
* Update QUIC v2 version number and initial salt
#### 1.2-beta4
* Add [NTP service](/configuration/ntp)
* Add Add multiple server names and multi-user support for shadowtls
* Add strict mode support for shadowtls v3
* Add uTLS support for shadowtls v3
#### 1.2-beta3
* Update QUIC v2 version number and initial salt
* Fix shadowtls v3 implementation
#### 1.2-beta2
* Add [ShadowTLS protocol v3](https://github.com/ihciah/shadow-tls/blob/master/docs/protocol-v3-en.md)
* Add fallback support for v2ray transport
* Fix parse hysteria UDP message
* Fix socks connect response
* Disable vmess header protection if transport enabled
#### 1.2-beta1
* Add [DHCP DNS server](/configuration/dns/server) support
* Add SSH [host key validation](/configuration/outbound/ssh) support
* Add [query_type](/configuration/dns/rule) DNS rule item
* Add v2ray [user stats](/configuration/experimental#statsusers) api
* Add new clash DNS query api
* Improve vmess request
* Fix ipv6 redirect on Linux
* Fix match geoip private
#### 1.1.5
* Add Go 1.20 support
* Fix inbound default DF value
* Fix auth_user route for naive inbound
* Fix gRPC lite header
* Ignore domain case in route rules
#### 1.1.4
* Fix DNS log
* Fix write to h2 conn after closed
* Fix create UDP DNS transport from plain IPv6 address
#### 1.1.2
* Fix http proxy auth
* Fix user from stream packet conn
* Fix DNS response TTL
* Fix override packet conn
* Skip override system proxy bypass list
* Improve DNS log
#### 1.1.1
* Fix acme config
* Fix vmess packet conn
* Suppress quic-go set DF error
#### 1.1
* Fix close clash cache
Important changes since 1.0:
* Add support for use with android VPNService
* Add tun support for WireGuard outbound
* Add system tun stack
* Add comment filter for config
* Add option for allow optional proxy protocol header
* Add Clash mode and persistence support
* Add TLS ECH and uTLS support for outbound TLS options
* Add internal simple-obfs and v2ray-plugin
* Add ShadowsocksR outbound
* Add VLESS outbound and XUDP
* Skip wait for hysteria tcp handshake response
* Add v2ray mux support for all inbound
* Add XUDP support for VMess
* Improve websocket writer
* Refine tproxy write back
* Fix DNS leak caused by
Windows' ordinary multihomed DNS resolution behavior
* Add sniff_timeout listen option
* Add custom route support for tun
* Add option for custom wireguard reserved bytes
* Split bind_address into ipv4 and ipv6
* Add ShadowTLS v1 and v2 support
#### 1.1-rc1
* Fix TLS config for h2 server
* Fix crash when input bad method in shadowsocks multi-user inbound
* Fix listen UDP
* Fix check invalid packet on macOS
#### 1.1-beta18
* Enhance defense against active probe for shadowtls server **1**
**1**:
The `fallback_after` option has been removed.
#### 1.1-beta17
* Fix shadowtls server **1**
*1*:
Added [fallback_after](/configuration/inbound/shadowtls#fallback_after) option.
#### 1.0.7
* Add support for new x/h2 deadline
* Fix copy pipe
* Fix decrypt xplus packet
* Fix macOS Ventura process name match
* Fix smux keepalive
* Fix vmess request buffer
* Fix h2c transport
* Fix tor geoip
* Fix udp connect for mux client
* Fix default dns transport strategy
#### 1.1-beta16
* Improve shadowtls server
* Fix default dns transport strategy
* Update uTLS to v1.2.0
#### 1.1-beta15
* Add support for new x/h2 deadline
* Fix udp connect for mux client
* Fix dns buffer
* Fix quic dns retry
* Fix create TLS config
* Fix websocket alpn
* Fix tor geoip
#### 1.1-beta14
* Add multi-user support for hysteria inbound **1**
* Add custom tls client support for std grpc
* Fix smux keep alive
* Fix vmess request buffer
* Fix default local DNS server behavior
* Fix h2c transport
*1*:
The `auth` and `auth_str` fields have been replaced by the `users` field.
#### 1.1-beta13
* Add custom worker count option for WireGuard outbound
* Split bind_address into ipv4 and ipv6
* Move WFP manipulation to strict route
* Fix WireGuard outbound panic when close
* Fix macOS Ventura process name match
* Fix QUIC connection migration by @HyNetwork
* Fix handling QUIC client SNI by @HyNetwork
#### 1.1-beta12
* Fix uTLS config
* Update quic-go to v0.30.0
* Update cloudflare-tls to go1.18.7
#### 1.1-beta11
* Add option for custom wireguard reserved bytes
* Fix shadowtls v2
* Fix h3 dns transport
* Fix copy pipe
* Fix decrypt xplus packet
* Fix v2ray api
* Suppress no network error
* Improve local dns transport
#### 1.1-beta10
* Add [sniff_timeout](/configuration/shared/listen#sniff_timeout) listen option
* Add [custom route](/configuration/inbound/tun#inet4_route_address) support for tun **1**
* Fix interface monitor
* Fix websocket headroom
* Fix uTLS handshake
* Fix ssh outbound
* Fix sniff fragmented quic client hello
* Fix DF for hysteria
* Fix naive overflow
* Check destination before udp connect
* Update uTLS to v1.1.5
* Update tfo-go to v2.0.2
* Update fsnotify to v1.6.0
* Update grpc to v1.50.1
*1*:
The `strict_route` on windows is removed.
#### 1.0.6
* Fix ssh outbound
* Fix sniff fragmented quic client hello
* Fix naive overflow
* Check destination before udp connect
#### 1.1-beta9
* Fix windows route **1**
* Add [v2ray statistics api](/configuration/experimental#v2ray-api-fields)
* Add ShadowTLS v2 support **2**
* Fixes and improvements
**1**:
* Fix DNS leak caused by
Windows' [ordinary multihomed DNS resolution behavior](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/dd197552%28v%3Dws.10%29)
* Flush Windows DNS cache when start/close
**2**:
See [ShadowTLS inbound](/configuration/inbound/shadowtls#version)
and [ShadowTLS outbound](/configuration/outbound/shadowtls#version)
#### 1.1-beta8
* Fix leaks on close
* Improve websocket writer
* Refine tproxy write back
* Refine 4in6 processing
* Fix shadowsocks plugins
* Fix missing source address from transport connection
* Fix fqdn socks5 outbound connection
* Fix read source address from grpc-go
#### 1.0.5
* Fix missing source address from transport connection
* Fix fqdn socks5 outbound connection
* Fix read source address from grpc-go
#### 1.1-beta7
* Add v2ray mux and XUDP support for VMess inbound
* Add XUDP support for VMess outbound
* Disable DF on direct outbound by default
* Fix bugs in 1.1-beta6
#### 1.1-beta6
* Add [URLTest outbound](/configuration/outbound/urltest)
* Fix bugs in 1.1-beta5
#### 1.1-beta5
* Print tags in version command
* Redirect clash hello to external ui
* Move shadowsocksr implementation to clash
* Make gVisor optional **1**
* Refactor to miekg/dns
* Refactor bind control
* Fix build on go1.18
* Fix clash store-selected
* Fix close grpc conn
* Fix port rule match logic
* Fix clash api proxy type
*1*:
The build tag `no_gvisor` is replaced by `with_gvisor`.
The default tun stack is changed to system.
#### 1.0.4
* Fix close grpc conn
* Fix port rule match logic
* Fix clash api proxy type
#### 1.1-beta4
* Add internal simple-obfs and v2ray-plugin [Shadowsocks plugins](/configuration/outbound/shadowsocks#plugin)
* Add [ShadowsocksR outbound](/configuration/outbound/shadowsocksr)
* Add [VLESS outbound and XUDP](/configuration/outbound/vless)
* Skip wait for hysteria tcp handshake response
* Fix socks4 client
* Fix hysteria inbound
* Fix concurrent write
#### 1.0.3
* Fix socks4 client
* Fix hysteria inbound
* Fix concurrent write
#### 1.1-beta3
* Fix using custom TLS client in http2 client
* Fix bugs in 1.1-beta2
#### 1.1-beta2
* Add Clash mode and persistence support **1**
* Add TLS ECH and uTLS support for outbound TLS options **2**
* Fix socks4 request
* Fix processing empty dns result
*1*:
Switching modes using the Clash API, and `store-selected` are now supported,
see [Experimental](/configuration/experimental).
*2*:
ECH (Encrypted Client Hello) is a TLS extension that allows a client to encrypt the first part of its ClientHello
message, see [TLS#ECH](/configuration/shared/tls#ech).
uTLS is a fork of "crypto/tls", which provides ClientHello fingerprinting resistance,
see [TLS#uTLS](/configuration/shared/tls#utls).
#### 1.0.2
* Fix socks4 request
* Fix processing empty dns result
#### 1.1-beta1
* Add support for use with android VPNService **1**
* Add tun support for WireGuard outbound **2**
* Add system tun stack **3**
* Add comment filter for config **4**
* Add option for allow optional proxy protocol header
* Add half close for smux
* Set UDP DF by default **5**
* Set default tun mtu to 9000
* Update gVisor to 20220905.0
*1*:
In previous versions, Android VPN would not work with tun enabled.
The usage of tun over VPN and VPN over tun is now supported, see [Tun Inbound](/configuration/inbound/tun#auto_route).
*2*:
In previous releases, WireGuard outbound support was backed by the lower performance gVisor virtual interface.
It achieves the same performance as wireguard-go by providing automatic system interface support.
*3*:
It does not depend on gVisor and has better performance in some cases.
It is less compatible and may not be available in some environments.
*4*:
Annotated json configuration files are now supported.
*5*:
UDP fragmentation is now blocked by default.
Including shadowsocks-libev, shadowsocks-rust and quic-go all disable segmentation by default.
See [Dial Fields](/configuration/shared/dial#udp_fragment)
and [Listen Fields](/configuration/shared/listen#udp_fragment).
#### 1.0.1 #### 1.0.1
* Fix match 4in6 address in ip_cidr * Fix match 4in6 address in ip_cidr
+1 -17
View File
@@ -9,11 +9,6 @@
"mixed-in" "mixed-in"
], ],
"ip_version": 6, "ip_version": 6,
"query_type": [
"A",
"HTTPS",
32768
],
"network": "tcp", "network": "tcp",
"auth_user": [ "auth_user": [
"usera", "usera",
@@ -78,7 +73,6 @@
"user_id": [ "user_id": [
1000 1000
], ],
"clash_mode": "direct",
"invert": false, "invert": false,
"outbound": [ "outbound": [
"direct" "direct"
@@ -109,10 +103,8 @@
The default rule uses the following matching logic: The default rule uses the following matching logic:
(`domain` || `domain_suffix` || `domain_keyword` || `domain_regex` || `geosite`) && (`domain` || `domain_suffix` || `domain_keyword` || `domain_regex` || `geosite`) &&
(`port` || `port_range`) &&
(`source_geoip` || `source_ip_cidr`) && (`source_geoip` || `source_ip_cidr`) &&
(`source_port` || `source_port_range`) && `other fields`
`other fields`
#### inbound #### inbound
@@ -124,10 +116,6 @@ Tags of [Inbound](/configuration/inbound).
Not limited if empty. Not limited if empty.
#### query_type
DNS query type. Values can be integers or type name strings.
#### network #### network
`tcp` or `udp`. `tcp` or `udp`.
@@ -220,10 +208,6 @@ Match user name.
Match user id. Match user id.
#### clash_mode
Match Clash mode.
#### invert #### invert
Invert match result. Invert match result.
+1 -17
View File
@@ -9,11 +9,6 @@
"mixed-in" "mixed-in"
], ],
"ip_version": 6, "ip_version": 6,
"query_type": [
"A",
"HTTPS",
32768
],
"network": "tcp", "network": "tcp",
"auth_user": [ "auth_user": [
"usera", "usera",
@@ -77,7 +72,6 @@
"user_id": [ "user_id": [
1000 1000
], ],
"clash_mode": "direct",
"invert": false, "invert": false,
"outbound": [ "outbound": [
"direct" "direct"
@@ -108,10 +102,8 @@
默认规则使用以下匹配逻辑: 默认规则使用以下匹配逻辑:
(`domain` || `domain_suffix` || `domain_keyword` || `domain_regex` || `geosite`) && (`domain` || `domain_suffix` || `domain_keyword` || `domain_regex` || `geosite`) &&
(`port` || `port_range`) &&
(`source_geoip` || `source_ip_cidr`) && (`source_geoip` || `source_ip_cidr`) &&
(`source_port` || `source_port_range`) && `other fields`
`other fields`
#### inbound #### inbound
@@ -123,10 +115,6 @@
默认不限制。 默认不限制。
#### query_type
DNS 查询类型。值可以为整数或者类型名称字符串。
#### network #### network
`tcp` 或 `udp`。 `tcp` 或 `udp`。
@@ -219,10 +207,6 @@ DNS 查询类型。值可以为整数或者类型名称字符串。
匹配用户 ID。 匹配用户 ID。
#### clash_mode
匹配 Clash 模式。
#### invert #### invert
反选匹配结果。 反选匹配结果。
+10 -15
View File
@@ -30,17 +30,16 @@ The tag of the dns server.
The address of the dns server. The address of the dns server.
| Protocol | Format | | Protocol | Format |
|----------|-------------------------------| |----------|-----------------------------|
| `System` | `local` | | `System` | `local` |
| `TCP` | `tcp://1.0.0.1` | | `TCP` | `tcp://1.0.0.1` |
| `UDP` | `8.8.8.8` `udp://8.8.4.4` | | `UDP` | `8.8.8.8` `udp://8.8.4.4` |
| `TLS` | `tls://dns.google` | | `TLS` | `tls://dns.google` |
| `HTTPS` | `https://1.1.1.1/dns-query` | | `HTTPS` | `https://1.1.1.1/dns-query` |
| `QUIC` | `quic://dns.adguard.com` | | `QUIC` | `quic://dns.adguard.com` |
| `HTTP3` | `h3://8.8.8.8/dns-query` | | `HTTP3` | `h3://8.8.8.8/dns-query` |
| `RCode` | `rcode://refused` | | `RCode` | `rcode://refused` |
| `DHCP` | `dhcp://auto` or `dhcp://en0` |
!!! warning "" !!! warning ""
@@ -54,10 +53,6 @@ The address of the dns server.
the RCode transport is often used to block queries. Use with rules and the `disable_cache` rule option. the RCode transport is often used to block queries. Use with rules and the `disable_cache` rule option.
!!! warning ""
DHCP transport is not included by default, see [Installation](/#installation).
| RCode | Description | | RCode | Description |
|-------------------|-----------------------| |-------------------|-----------------------|
| `success` | `No error` | | `success` | `No error` |
+10 -15
View File
@@ -30,17 +30,16 @@ DNS 服务器的标签。
DNS 服务器的地址。 DNS 服务器的地址。
| 协议 | 格式 | | 协议 | 格式 |
|----------|------------------------------| |----------|-----------------------------|
| `System` | `local` | | `System` | `local` |
| `TCP` | `tcp://1.0.0.1` | | `TCP` | `tcp://1.0.0.1` |
| `UDP` | `8.8.8.8` `udp://8.8.4.4` | | `UDP` | `8.8.8.8` `udp://8.8.4.4` |
| `TLS` | `tls://dns.google` | | `TLS` | `tls://dns.google` |
| `HTTPS` | `https://1.1.1.1/dns-query` | | `HTTPS` | `https://1.1.1.1/dns-query` |
| `QUIC` | `quic://dns.adguard.com` | | `QUIC` | `quic://dns.adguard.com` |
| `HTTP3` | `h3://8.8.8.8/dns-query` | | `HTTP3` | `h3://8.8.8.8/dns-query` |
| `RCode` | `rcode://refused` | | `RCode` | `rcode://refused` |
| `DHCP` | `dhcp://auto` 或 `dhcp://en0` |
!!! warning "" !!! warning ""
@@ -54,10 +53,6 @@ DNS 服务器的地址。
RCode 传输层传输层常用于屏蔽请求. 与 DNS 规则和 `disable_cache` 规则选项一起使用。 RCode 传输层传输层常用于屏蔽请求. 与 DNS 规则和 `disable_cache` 规则选项一起使用。
!!! warning ""
默认安装不包含 DHCP 传输层,请参阅 [安装](/zh/#_2)。
| RCode | 描述 | | RCode | 描述 |
|-------------------|----------| |-------------------|----------|
| `success` | `无错误` | | `success` | `无错误` |
+7 -74
View File
@@ -8,44 +8,25 @@
"clash_api": { "clash_api": {
"external_controller": "127.0.0.1:9090", "external_controller": "127.0.0.1:9090",
"external_ui": "folder", "external_ui": "folder",
"secret": "", "secret": ""
"default_mode": "rule",
"store_selected": false,
"cache_file": "cache.db"
},
"v2ray_api": {
"listen": "127.0.0.1:8080",
"stats": {
"enabled": true,
"inbounds": [
"socks-in"
],
"outbounds": [
"proxy",
"direct"
],
"users": [
"sekai"
]
}
} }
} }
} }
``` ```
!!! note ""
Traffic statistics and connection management can degrade performance.
### Clash API Fields ### Clash API Fields
!!! error "" !!! error ""
Clash API is not included by default, see [Installation](/#installation). Clash API is not included by default, see [Installation](/#installation).
!!! note ""
Traffic statistics and connection management will disable TCP splice in linux and reduce performance, use at your own risk.
#### external_controller #### external_controller
RESTful web API listening address. Clash API will be disabled if empty. RESTful web API listening address. Disabled if empty.
#### external_ui #### external_ui
@@ -57,52 +38,4 @@ serve it at `http://{{external-controller}}/ui`.
Secret for the RESTful API (optional) Secret for the RESTful API (optional)
Authenticate by spedifying HTTP header `Authorization: Bearer ${secret}` Authenticate by spedifying HTTP header `Authorization: Bearer ${secret}`
ALWAYS set a secret if RESTful API is listening on 0.0.0.0 ALWAYS set a secret if RESTful API is listening on 0.0.0.0
#### default_mode
Default mode in clash, `rule` will be used if empty.
This setting has no direct effect, but can be used in routing and DNS rules via the `clash_mode` rule item.
#### store_selected
!!! note ""
The tag must be set for target outbounds.
Store selected outbound for the `Selector` outbound in cache file.
#### cache_file
Cache file path, `cache.db` will be used if empty.
### V2Ray API Fields
!!! error ""
V2Ray API is not included by default, see [Installation](/#installation).
#### listen
gRPC API listening address. V2Ray API will be disabled if empty.
#### stats
Traffic statistics service settings.
#### stats.enabled
Enable statistics service.
#### stats.inbounds
Inbound list to count traffic.
#### stats.outbounds
Outbound list to count traffic.
#### stats.users
User list to count traffic.
+7 -74
View File
@@ -8,44 +8,25 @@
"clash_api": { "clash_api": {
"external_controller": "127.0.0.1:9090", "external_controller": "127.0.0.1:9090",
"external_ui": "folder", "external_ui": "folder",
"secret": "", "secret": ""
"default_mode": "rule",
"store_selected": false,
"cache_file": "cache.db"
},
"v2ray_api": {
"listen": "127.0.0.1:8080",
"stats": {
"enabled": true,
"inbounds": [
"socks-in"
],
"outbounds": [
"proxy",
"direct"
],
"users": [
"sekai"
]
}
} }
} }
} }
``` ```
!!! note ""
流量统计和连接管理会降低性能。
### Clash API 字段 ### Clash API 字段
!!! error "" !!! error ""
默认安装不包含 Clash API,参阅 [安装](/zh/#_2)。 默认安装不包含 Clash API,参阅 [安装](/zh/#_2)。
!!! note ""
流量统计和连接管理将禁用 Linux 中的 TCP splice 并降低性能,使用风险自负。
#### external_controller #### external_controller
RESTful web API 监听地址。如果为空,则禁用 Clash API。 RESTful web API 监听地址。
#### external_ui #### external_ui
@@ -55,52 +36,4 @@ RESTful web API 监听地址。如果为空,则禁用 Clash API。
RESTful API 的密钥(可选) RESTful API 的密钥(可选)
通过指定 HTTP 标头 `Authorization: Bearer ${secret}` 进行身份验证 通过指定 HTTP 标头 `Authorization: Bearer ${secret}` 进行身份验证
如果 RESTful API 正在监听 0.0.0.0,请始终设置一个密钥。 如果 RESTful API 正在监听 0.0.0.0,请始终设置一个密钥。
#### default_mode
Clash 中的默认模式,默认使用 `rule`。
此设置没有直接影响,但可以通过 `clash_mode` 规则项在路由和 DNS 规则中使用。
#### store_selected
!!! note ""
必须为目标出站设置标签。
将 `Selector` 中出站的选定的目标出站存储在缓存文件中。
#### cache_file
缓存文件路径,默认使用`cache.db`。
### V2Ray API 字段
!!! error ""
默认安装不包含 V2Ray API,参阅 [安装](/zh/#_2)。
#### listen
gRPC API 监听地址。如果为空,则禁用 V2Ray API。
#### stats
流量统计服务设置。
#### stats.enabled
启用统计服务。
#### stats.inbounds
统计流量的入站列表。
#### stats.outbounds
统计流量的出站列表。
#### stats.users
统计流量的用户列表。
+4 -19
View File
@@ -12,15 +12,8 @@
"down": "100 Mbps", "down": "100 Mbps",
"down_mbps": 100, "down_mbps": 100,
"obfs": "fuck me till the daylight", "obfs": "fuck me till the daylight",
"auth": "",
"users": [ "auth_str": "password",
{
"name": "sekai",
"auth": "",
"auth_str": "password"
}
],
"recv_window_conn": 0, "recv_window_conn": 0,
"recv_window_client": 0, "recv_window_client": 0,
"max_conn_client": 0, "max_conn_client": 0,
@@ -68,19 +61,11 @@ Supported units (case sensitive, b = bits, B = bytes, 8b=1B):
Obfuscated password. Obfuscated password.
#### users #### auth
Hysteria users
#### users.auth
==Required if `auth_str` is empty==
Authentication password, in base64. Authentication password, in base64.
#### users.auth_str #### auth_str
==Required if `auth` is empty==
Authentication password. Authentication password.
+4 -19
View File
@@ -12,15 +12,8 @@
"down": "100 Mbps", "down": "100 Mbps",
"down_mbps": 100, "down_mbps": 100,
"obfs": "fuck me till the daylight", "obfs": "fuck me till the daylight",
"auth": "",
"users": [ "auth_str": "password",
{
"name": "sekai",
"auth": "",
"auth_str": "password"
}
],
"recv_window_conn": 0, "recv_window_conn": 0,
"recv_window_client": 0, "recv_window_client": 0,
"max_conn_client": 0, "max_conn_client": 0,
@@ -68,19 +61,11 @@
混淆密码。 混淆密码。
#### users #### auth
Hysteria 用户
#### users.auth
==与 auth_str 必填一个==
base64 编码的认证密码。 base64 编码的认证密码。
#### users.auth_str #### auth_str
==与 auth 必填一个==
认证密码。 认证密码。
-2
View File
@@ -26,8 +26,6 @@
| `trojan` | [Trojan](./trojan) | TCP | | `trojan` | [Trojan](./trojan) | TCP |
| `naive` | [Naive](./naive) | X | | `naive` | [Naive](./naive) | X |
| `hysteria` | [Hysteria](./hysteria) | X | | `hysteria` | [Hysteria](./hysteria) | X |
| `shadowtls` | [ShadowTLS](./shadowtls) | TCP |
| `vless` | [VLESS](./vless) | TCP |
| `tun` | [Tun](./tun) | X | | `tun` | [Tun](./tun) | X |
| `redirect` | [Redirect](./redirect) | X | | `redirect` | [Redirect](./redirect) | X |
| `tproxy` | [TProxy](./tproxy) | X | | `tproxy` | [TProxy](./tproxy) | X |
+5 -5
View File
@@ -77,11 +77,11 @@ Both if empty.
==Required== ==Required==
| Method | Password Format | | Method | Password Format |
|---------------|------------------------------------------------| |---------------|-------------------------------------|
| none | / | | none | / |
| 2022 methods | `sing-box generate rand --base64 <Key Length>` | | 2022 methods | `openssl rand -base64 <Key Length>` |
| other methods | any string | | other methods | any string |
### Listen Fields ### Listen Fields
+5 -5
View File
@@ -77,8 +77,8 @@ See [Listen Fields](/configuration/shared/listen) for details.
==必填== ==必填==
| 方法 | 密码格式 | | 方法 | 密码格式 |
|---------------|------------------------------------------| |---------------|-------------------------------|
| none | / | | none | / |
| 2022 methods | `sing-box generate rand --base64 <密钥长度>` | | 2022 methods | `openssl rand -base64 <密钥长度>` |
| other methods | 任意字符串 | | other methods | 任意字符串 |
+3 -53
View File
@@ -7,29 +7,12 @@
... // Listen Fields ... // Listen Fields
"version": 3,
"password": "fuck me till the daylight",
"users": [
{
"name": "sekai",
"password": "8JCsPssfgS8tiRwiMlhARg=="
}
],
"handshake": { "handshake": {
"server": "google.com", "server": "google.com",
"server_port": 443, "server_port": 443,
... // Dial Fields ... // Dial Fields
}, }
"handshake_for_server_name": {
"example.com": {
"server": "example.com",
"server_port": 443,
... // Dial Fields
}
},
"strict_mode": false
} }
``` ```
@@ -37,45 +20,12 @@
See [Listen Fields](/configuration/shared/listen) for details. See [Listen Fields](/configuration/shared/listen) for details.
### Fields ### Fields
#### version
ShadowTLS protocol version.
| Value | Protocol Version |
|---------------|-----------------------------------------------------------------------------------------|
| `1` (default) | [ShadowTLS v1](https://github.com/ihciah/shadow-tls/blob/master/docs/protocol-en.md#v1) |
| `2` | [ShadowTLS v2](https://github.com/ihciah/shadow-tls/blob/master/docs/protocol-en.md#v2) |
| `3` | [ShadowTLS v3](https://github.com/ihciah/shadow-tls/blob/master/docs/protocol-v3-en.md) |
#### password
ShadowTLS password.
Only available in the ShadowTLS protocol 2.
#### users
ShadowTLS users.
Only available in the ShadowTLS protocol 3.
#### handshake #### handshake
==Required== ==Required==
Handshake server address and [Dial options](/configuration/shared/dial). Handshake server address and [dial options](/configuration/shared/dial).
#### handshake_for_server_name
Handshake server address and [Dial options](/configuration/shared/dial) for specific server name.
Only available in the ShadowTLS protocol 2/3.
#### strict_mode
ShadowTLS strict mode.
Only available in the ShadowTLS protocol 3.
+1 -54
View File
@@ -7,29 +7,12 @@
... // 监听字段 ... // 监听字段
"version": 3,
"password": "fuck me till the daylight",
"users": [
{
"name": "sekai",
"password": "8JCsPssfgS8tiRwiMlhARg=="
}
],
"handshake": { "handshake": {
"server": "google.com", "server": "google.com",
"server_port": 443, "server_port": 443,
... // 拨号字段 ... // 拨号字段
}, }
"handshake_for_server_name": {
"example.com": {
"server": "example.com",
"server_port": 443,
... // 拨号字段
}
},
"strict_mode": false
} }
``` ```
@@ -39,44 +22,8 @@
### 字段 ### 字段
#### version
ShadowTLS 协议版本。
| 值 | 协议版本 |
|---------------|-----------------------------------------------------------------------------------------|
| `1` (default) | [ShadowTLS v1](https://github.com/ihciah/shadow-tls/blob/master/docs/protocol-en.md#v1) |
| `2` | [ShadowTLS v2](https://github.com/ihciah/shadow-tls/blob/master/docs/protocol-en.md#v2) |
| `3` | [ShadowTLS v3](https://github.com/ihciah/shadow-tls/blob/master/docs/protocol-v3-en.md) |
#### password
ShadowTLS 密码。
仅在 ShadowTLS 协议版本 2 中可用。
#### users
ShadowTLS 用户。
仅在 ShadowTLS 协议版本 3 中可用。
#### handshake #### handshake
==必填== ==必填==
握手服务器地址和 [拨号参数](/zh/configuration/shared/dial/)。 握手服务器地址和 [拨号参数](/zh/configuration/shared/dial/)。
#### handshake_for_server_name
==必填==
对于特定服务器名称的握手服务器地址和 [拨号参数](/zh/configuration/shared/dial/)。
仅在 ShadowTLS 协议版本 2/3 中可用。
#### strict_mode
ShadowTLS 严格模式。
仅在 ShadowTLS 协议版本 3 中可用。
+11 -59
View File
@@ -8,22 +8,15 @@
{ {
"type": "tun", "type": "tun",
"tag": "tun-in", "tag": "tun-in",
"interface_name": "tun0", "interface_name": "tun0",
"inet4_address": "172.19.0.1/30", "inet4_address": "172.19.0.1/30",
"inet6_address": "fdfe:dcba:9876::1/126", "inet6_address": "fdfe:dcba:9876::1/128",
"mtu": 9000, "mtu": 1500,
"auto_route": true, "auto_route": true,
"strict_route": true, "strict_route": true,
"inet4_route_address": [
"0.0.0.0/1",
"128.0.0.0/1"
],
"inet6_route_address": [
"::/1",
"8000::/1"
],
"endpoint_independent_nat": false, "endpoint_independent_nat": false,
"stack": "system", "stack": "gvisor",
"include_uid": [ "include_uid": [
0 0
], ],
@@ -46,14 +39,7 @@
"exclude_package": [ "exclude_package": [
"com.android.captiveportallogin" "com.android.captiveportallogin"
], ],
"platform": {
"http_proxy": {
"enabled": false,
"server": "127.0.0.1",
"server_port": 8080
}
},
... // Listen Fields ... // Listen Fields
} }
``` ```
@@ -94,15 +80,9 @@ Set the default route to the Tun.
To avoid traffic loopback, set `route.auto_detect_interface` or `route.default_interface` or `outbound.bind_interface` To avoid traffic loopback, set `route.auto_detect_interface` or `route.default_interface` or `outbound.bind_interface`
!!! note "Use with Android VPN"
By default, VPN takes precedence over tun. To make tun go through VPN, enable `route.override_android_vpn`.
#### strict_route #### strict_route
Enforce strict routing rules when `auto_route` is enabled: Enforce strict routing rules in Linux when `auto_route` is enabled:
*In Linux*:
* Let unsupported network unreachable * Let unsupported network unreachable
* Route all connections to tun * Route all connections to tun
@@ -110,27 +90,8 @@ Enforce strict routing rules when `auto_route` is enabled:
It prevents address leaks and makes DNS hijacking work on Android and Linux with systemd-resolved, but your device will It prevents address leaks and makes DNS hijacking work on Android and Linux with systemd-resolved, but your device will
not be accessible by others. not be accessible by others.
*In Windows*:
* Add firewall rules to prevent DNS leak caused by
Windows' [ordinary multihomed DNS resolution behavior](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/dd197552%28v%3Dws.10%29)
It may prevent some applications (such as VirtualBox) from working properly in certain situations.
#### inet4_route_address
Use custom routes instead of default when `auto_route` is enabled.
#### inet6_route_address
Use custom routes instead of default when `auto_route` is enabled.
#### endpoint_independent_nat #### endpoint_independent_nat
!!! info ""
This item is only available on the gvisor stack, other stacks are endpoint-independent NAT by default.
Enable endpoint-independent NAT. Enable endpoint-independent NAT.
Performance may degrade slightly, so it is not recommended to enable on when it is not needed. Performance may degrade slightly, so it is not recommended to enable on when it is not needed.
@@ -143,15 +104,14 @@ UDP NAT expiration time in seconds, default is 300 (5 minutes).
TCP/IP stack. TCP/IP stack.
| Stack | Description | Status | | Stack | Upstream | Status |
|------------------|----------------------------------------------------------------------------------|-------------------| |------------------|-----------------------------------------------------------------------|-------------------|
| system (default) | Sometimes better performance | recommended | | gVisor (default) | [google/gvisor](https://github.com/google/gvisor) | recommended |
| gVisor | Better compatibility, based on [google/gvisor](https://github.com/google/gvisor) | recommended | | LWIP | [eycorsican/go-tun2socks](https://github.com/eycorsican/go-tun2socks) | upstream archived |
| LWIP | Based on [eycorsican/go-tun2socks](https://github.com/eycorsican/go-tun2socks) | upstream archived |
!!! warning "" !!! warning ""
gVisor and LWIP stacks is not included by default, see [Installation](/#installation). The LWIP stack is not included by default, see [Installation](/#installation).
#### include_uid #### include_uid
@@ -194,14 +154,6 @@ Limit android packages in route.
Exclude android packages in route. Exclude android packages in route.
#### platform
Platform-specific settings, provided by client applications.
#### platform.http_proxy
System HTTP proxy settings.
### Listen Fields ### Listen Fields
See [Listen Fields](/configuration/shared/listen) for details. See [Listen Fields](/configuration/shared/listen) for details.
+19 -64
View File
@@ -8,22 +8,15 @@
{ {
"type": "tun", "type": "tun",
"tag": "tun-in", "tag": "tun-in",
"interface_name": "tun0", "interface_name": "tun0",
"inet4_address": "172.19.0.1/30", "inet4_address": "172.19.0.1/30",
"inet6_address": "fdfe:dcba:9876::1/126", "inet6_address": "fdfe:dcba:9876::1/128",
"mtu": 9000, "mtu": 1500,
"auto_route": true, "auto_route": true,
"strict_route": true, "strict_route": true,
"inet4_route_address": [
"0.0.0.0/1",
"128.0.0.0/1"
],
"inet6_route_address": [
"::/1",
"8000::/1"
],
"endpoint_independent_nat": false, "endpoint_independent_nat": false,
"stack": "system", "stack": "gvisor",
"include_uid": [ "include_uid": [
0 0
], ],
@@ -46,14 +39,7 @@
"exclude_package": [ "exclude_package": [
"com.android.captiveportallogin" "com.android.captiveportallogin"
], ],
"platform": {
"http_proxy": {
"enabled": false,
"server": "127.0.0.1",
"server_port": 8080
}
},
... // 监听字段 ... // 监听字段
} }
``` ```
@@ -94,37 +80,15 @@ tun 接口的 IPv6 前缀。
为避免流量环回,请设置 `route.auto_detect_interface` 或 `route.default_interface` 或 `outbound.bind_interface`。 为避免流量环回,请设置 `route.auto_detect_interface` 或 `route.default_interface` 或 `outbound.bind_interface`。
!!! note "与 Android VPN 一起使用"
VPN 默认优先于 tun。要使 tun 经过 VPN,启用 `route.override_android_vpn`。
#### strict_route #### strict_route
启用 `auto_route` 时执行严格的路由规则。 在 Linux 中启用 `auto_route` 时执行严格的路由规则。
*在 Linux 中*:
* 让不支持的网络无法到达 * 让不支持的网络无法到达
* 将所有连接路由到 tun * 将所有连接路由到 tun
它可以防止地址泄漏,并使 DNS 劫持在 Android 和使用 systemd-resolved 的 Linux 上工作,但你的设备将无法其他设备被访问。 它可以防止地址泄漏,并使 DNS 劫持在 Android 和使用 systemd-resolved 的 Linux 上工作,但你的设备将无法其他设备被访问。
*在 Windows 中*:
* 添加防火墙规则以阻止 Windows
的 [普通多宿主 DNS 解析行为](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/dd197552%28v%3Dws.10%29)
造成的 DNS 泄露
它可能会使某些应用程序(如 VirtualBox)在某些情况下无法正常工作。
#### inet4_route_address
启用 `auto_route` 时使用自定义路由而不是默认路由。
#### inet6_route_address
启用 `auto_route` 时使用自定义路由而不是默认路由。
#### endpoint_independent_nat #### endpoint_independent_nat
启用独立于端点的 NAT。 启用独立于端点的 NAT。
@@ -139,15 +103,14 @@ UDP NAT 过期时间,以秒为单位,默认为 300(5 分钟)。
TCP/IP 栈。 TCP/IP 栈。
| 栈 | 描述 | 状态 | | 栈 | 上游 | 状态 |
|-------------|--------------------------------------------------------------------------|-------| |------------------|-----------------------------------------------------------------------|-------|
| system (默认) | 有时性能更好 | 推荐 | | gVisor (default) | [google/gvisor](https://github.com/google/gvisor) | 推荐 |
| gVisor | 兼容性较好,基于 [google/gvisor](https://github.com/google/gvisor) | 推荐 | | LWIP | [eycorsican/go-tun2socks](https://github.com/eycorsican/go-tun2socks) | 上游已存档 |
| LWIP | 基于 [eycorsican/go-tun2socks](https://github.com/eycorsican/go-tun2socks) | 上游已存档 |
!!! warning "" !!! warning ""
默认安装不包含 gVisor 和 LWIP 栈,请参阅 [安装](/zh/#_2)。 默认安装不包含 LWIP 栈,请参阅 [安装](/zh/#_2)。
#### include_uid #### include_uid
@@ -155,19 +118,19 @@ TCP/IP 栈。
UID 规则仅在 Linux 下被支持,并且需要 `auto_route`。 UID 规则仅在 Linux 下被支持,并且需要 `auto_route`。
限制被路由的用户。默认不限制。 限制被路由的的用户。默认不限制。
#### include_uid_range #### include_uid_range
限制被路由的用户范围。 限制被路由的的用户范围。
#### exclude_uid #### exclude_uid
排除路由的用户。 排除路由的的用户。
#### exclude_uid_range #### exclude_uid_range
排除路由的用户范围。 排除路由的的用户范围。
#### include_android_user #### include_android_user
@@ -177,10 +140,10 @@ TCP/IP 栈。
限制被路由的 Android 用户。 限制被路由的 Android 用户。
| 常用用户 | ID | | 常用用户 | ID |
|--|-----| |--|-----|
| 您 | 0 | | 您 | 0 |
| 工作资料 | 10 | | 工作资料 | 10 |
#### include_package #### include_package
@@ -190,14 +153,6 @@ TCP/IP 栈。
排除路由的 Android 应用包名。 排除路由的 Android 应用包名。
#### platform
平台特定的设置,由客户端应用提供。
#### platform.http_proxy
系统 HTTP 代理设置。
### 监听字段 ### 监听字段
参阅 [监听字段](/zh/configuration/shared/listen/)。 参阅 [监听字段](/zh/configuration/shared/listen/)。
-54
View File
@@ -1,54 +0,0 @@
### Structure
```json
{
"type": "vless",
"tag": "vless-in",
... // Listen Fields
"users": [
{
"name": "sekai",
"uuid": "bf000d23-0752-40b4-affe-68f7707a9661",
"flow": ""
}
],
"tls": {},
"transport": {}
}
```
### Listen Fields
See [Listen Fields](/configuration/shared/listen) for details.
### Fields
#### users
==Required==
VLESS users.
#### users.uuid
==Required==
VLESS user id.
#### users.flow
VLESS Sub-protocol.
Available values:
* `xtls-rprx-vision`
#### tls
TLS configuration, see [TLS](/configuration/shared/tls/#inbound).
#### transport
V2Ray Transport configuration, see [V2Ray Transport](/configuration/shared/v2ray-transport).

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