From 1520d0c0fdcd17f7de35a2054499179900df7569 Mon Sep 17 00:00:00 2001 From: iHsin Date: Wed, 2 Dec 2026 10:06:30 +0800 Subject: [PATCH 1/2] docs: migrate the bilingual manual to Zensical Assisted-by: Codex:GPT-6 --- .github/workflows/deploy.yml | 9 +- .gitignore | 3 +- README.md | 32 ++- build.py | 22 ++ docs/config/full.zh.md | 231 ------------------ docs/config/inbounds/http.md | 0 docs/config/inbounds/index.md | 50 ---- docs/config/inbounds/socks.md | 0 docs/config/inbounds/tunnel.md | 0 docs/config/index.md | 0 docs/config/index.zh.md | 0 docs/config/outbounds/tuic.md | 0 docs/config/tun.md | 0 docs/config/types.md | 1 - docs/en/config/full.md | 3 + docs/en/config/inbounds.md | 35 +++ docs/en/index.md | 11 + docs/en/quick-start.md | 24 ++ docs/index.md | 23 -- docs/index.zh.md | 24 -- docs/quick-start/cli.md | 1 - docs/quick-start/cli.zh.md | 0 docs/quick-start/gui.md | 0 docs/quick-start/gui.zh.md | 0 docs/quick-start/index.md | 1 - docs/quick-start/index.zh.md | 0 docs/zh/config/full.md | 3 + docs/zh/config/inbounds.md | 35 +++ docs/zh/index.md | 11 + docs/zh/quick-start.md | 24 ++ landing/index.html | 23 ++ mkdocs.yml | 126 ---------- .../assets/images/clashrs.png | Bin overrides/main.html | 7 + requirements.txt | 5 +- docs/config/full.md => shared/full-example.md | 0 tests/check_site.py | 64 +++++ zensical.toml | 66 +++++ zensical.zh.toml | 66 +++++ 39 files changed, 423 insertions(+), 477 deletions(-) create mode 100644 build.py delete mode 100644 docs/config/full.zh.md delete mode 100644 docs/config/inbounds/http.md delete mode 100644 docs/config/inbounds/index.md delete mode 100644 docs/config/inbounds/socks.md delete mode 100644 docs/config/inbounds/tunnel.md delete mode 100644 docs/config/index.md delete mode 100644 docs/config/index.zh.md delete mode 100644 docs/config/outbounds/tuic.md delete mode 100644 docs/config/tun.md delete mode 100644 docs/config/types.md create mode 100644 docs/en/config/full.md create mode 100644 docs/en/config/inbounds.md create mode 100644 docs/en/index.md create mode 100644 docs/en/quick-start.md delete mode 100644 docs/index.md delete mode 100644 docs/index.zh.md delete mode 100644 docs/quick-start/cli.md delete mode 100644 docs/quick-start/cli.zh.md delete mode 100644 docs/quick-start/gui.md delete mode 100644 docs/quick-start/gui.zh.md delete mode 100644 docs/quick-start/index.md delete mode 100644 docs/quick-start/index.zh.md create mode 100644 docs/zh/config/full.md create mode 100644 docs/zh/config/inbounds.md create mode 100644 docs/zh/index.md create mode 100644 docs/zh/quick-start.md create mode 100644 landing/index.html delete mode 100644 mkdocs.yml rename docs/artwork/logo.png => overrides/assets/images/clashrs.png (100%) create mode 100644 overrides/main.html rename docs/config/full.md => shared/full-example.md (100%) create mode 100644 tests/check_site.py create mode 100644 zensical.toml create mode 100644 zensical.zh.toml diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 0aefcda..1f0f976 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -17,20 +17,19 @@ jobs: - uses: actions/setup-python@v4 with: - python-version: 3.x + python-version: '3.13' cache: 'pip' - run: | pip install -r requirements.txt - mkdocs build - mkdir sites - mv site sites/clash + python build.py + python tests/check_site.py - name: Deploy uses: peaceiris/actions-gh-pages@v3 with: github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: sites + publish_dir: site cname: docs.watfaq.com force_orphan: true user_name: github-actions[bot] diff --git a/.gitignore b/.gitignore index 244a97c..d129029 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ site/ -.venv/ \ No newline at end of file +.cache/ +.venv/ diff --git a/README.md b/README.md index 1ff72ee..d5c94d0 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,24 @@ -# docs.watfaq.com/clash +# ClashRS 用户手册 -## Development +本站用 Zensical 分别构建英文和简体中文手册。发布入口为 [docs.watfaq.com/clash/](https://docs.watfaq.com/clash/)。 -```bash -# Install dependencies -python3 -m venv .venv -source .venv/bin/activate -pip install -r requirements.txt -pip install mkdocs +## 本地构建和预览 -# Run development server -mkdocs serve -``` \ No newline at end of file +在本文档仓库根目录使用 Python 3.13 运行: + +```sh +python -m pip install -r requirements.txt +python build.py +python tests/check_site.py +python -m http.server 8000 --bind 127.0.0.1 --directory site +``` + +打开 选择语言。两套站点分别位于 `/clash/en/` 和 `/clash/zh/`。CI 使用相同的构建脚本,将 `site/` 发布到 GitHub Pages。 + +只预览一种语言并在编辑时自动刷新,可以使用 `zensical serve -f zensical.toml`(英文)或 `zensical serve -f zensical.zh.toml`(简体中文)。跨语言切换请使用上述双语预览。 + +## 维护文档 + +- 在 `docs/en/` 和 `docs/zh/` 使用相同的相对路径,语言菜单通过该路径切换到对应文章。 +- 在 `zensical.toml` 和 `zensical.zh.toml` 中分别维护导航标题。尚未翻译的页面可以先在对应路径放入带有英文原文链接的简短说明。 +- 两种语言的完整配置示例都引用 `shared/full-example.md`,修改示例只需编辑这一份文件。站点图标位于 `overrides/assets/images/`。 diff --git a/build.py b/build.py new file mode 100644 index 0000000..3b27b58 --- /dev/null +++ b/build.py @@ -0,0 +1,22 @@ +"""Build the two manuals and their shared language selection page.""" + +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent + + +def main(): + for config in ("zensical.toml", "zensical.zh.toml"): + subprocess.run( + [sys.executable, "-m", "zensical", "build", "--clean", "--strict", "-f", config], + cwd=ROOT, + check=True, + ) + shutil.copyfile(ROOT / "landing/index.html", ROOT / "site/clash/index.html") + + +if __name__ == "__main__": + main() diff --git a/docs/config/full.zh.md b/docs/config/full.zh.md deleted file mode 100644 index 4703a6f..0000000 --- a/docs/config/full.zh.md +++ /dev/null @@ -1,231 +0,0 @@ -```yaml ---- -port: 8888 -socks-port: 8889 -mixed-port: 8899 - -tun: - enable: false - device-id: "dev://utun1989" - -dns: - enable: true - listen: 127.0.0.1:53553 - # udp: 127.0.0.1:53553 - # tcp: 127.0.0.1:53553 - # dot: 127.0.0.1:53554 - # doh: 127.0.0.1:53555 - - # ipv6: false # when the false, response to AAAA questions will be empty - - # These nameservers are used to resolve the DNS nameserver hostnames below. - # Specify IP addresses only - default-nameserver: - - 114.114.114.114 - - 8.8.8.8 - enhanced-mode: fake-ip - fake-ip-range: 198.18.0.2/16 # Fake IP addresses pool CIDR - # use-hosts: true # lookup hosts and return IP record - - # Hostnames in this list will not be resolved with fake IPs - # i.e. questions to these domain names will always be answered with their - # real IP addresses - # fake-ip-filter: - # - '*.lan' - # - localhost.ptlogin2.qq.com - - # Supports UDP, TCP, DoT, DoH. You can specify the port to connect to. - # All DNS questions are sent directly to the nameserver, without proxies - # involved. Clash answers the DNS question with the first result gathered. - nameserver: - - 114.114.114.114 # default value - - 1.1.1.1 # default value - - tls://1.1.1.1:853 # DNS over TLS - - https://1.1.1.1/dns-query # DNS over HTTPS -# - dhcp://en0 # dns from dhcp - -allow-lan: true -mode: rule -log-level: debug -external-controller: 127.0.0.1:9090 -external-ui: "public" -# secret: "clash-rs" -experimental: - ignore-resolve-fail: true - -profile: - store-selected: true - store-fake-ip: false - - -proxy-groups: - - name: "relay" - type: relay - proxies: - - "plain-vmess" - - "ws-vmess" - - "auto" - - "fallback-auto" - - "load-balance" - - "select" - - DIRECT - - - name: "relay-one" - type: relay - use: - - "file-provider" - - - name: "auto" - type: url-test - use: - - "file-provider" - proxies: - - DIRECT - url: "http://www.gstatic.com/generate_204" - interval: 300 - - - name: "fallback-auto" - type: fallback - use: - - "file-provider" - proxies: - - DIRECT - url: "http://www.gstatic.com/generate_204" - interval: 300 - - - name: "load-balance" - type: load-balance - use: - - "file-provider" - proxies: - - DIRECT - strategy: round-robin - url: "http://www.gstatic.com/generate_204" - interval: 300 - - - name: select - type: select - use: - - "file-provider" - - - name: test 🌏 - type: select - use: - - "file-provider" - proxies: - - DIRECT - -proxies: - - name: plain-vmess - type: vmess - server: 10.0.0.13 - port: 16823 - uuid: b831381d-6324-4d53-ad4f-8cda48b30811 - alterId: 0 - cipher: auto - udp: true - skip-cert-verify: true - - name: ws-vmess - type: vmess - server: 10.0.0.13 - port: 16824 - uuid: b831381d-6324-4d53-ad4f-8cda48b30811 - alterId: 0 - cipher: auto - udp: true - skip-cert-verify: true - network: ws - ws-opts: - path: /api/v3/download.getFile - headers: - Host: www.amazon.com - - - name: tls-vmess - type: vmess - server: 10.0.0.13 - port: 8443 - uuid: 23ad6b10-8d1a-40f7-8ad0-e3e35cd38297 - alterId: 0 - cipher: auto - udp: true - skip-cert-verify: true - tls: true - - - name: h2-vmess - type: vmess - server: 10.0.0.13 - port: 8444 - uuid: b831381d-6324-4d53-ad4f-8cda48b30811 - alterId: 0 - cipher: auto - udp: true - skip-cert-verify: true - tls: true - network: h2 - h2-opts: - path: /ray - - - name: vmess-altid - type: vmess - server: tw-1.ac.laowanxiang.com - port: 153 - uuid: 46dd0dd3-2cc0-3f55-907c-d94e54877687 - alterId: 64 - cipher: auto - udp: true - network: ws - ws-opts: - path: /api/v3/download.getFile - headers: - Host: 5607b9d187e655736f563fee87d7283994721.laowanxiang.com - - name: "ss-simple" - type: ss - server: 10.0.0.13 - port: 8388 - cipher: aes-256-gcm - password: "password" - udp: true - - name: "trojan" - type: trojan - server: 10.0.0.13 - port: 9443 - password: password1 - udp: true - # sni: example.com # aka server name - alpn: - - h2 - - http/1.1 - skip-cert-verify: true - -proxy-providers: - file-provider: - type: file - path: ./ss.yaml - interval: 300 - health-check: - enable: true - url: http://www.gstatic.com/generate_204 - interval: 300 - -rule-providers: - file-provider: - type: file - path: ./rule-set.yaml - interval: 300 - behavior: domain - -rules: - - DOMAIN,ipinfo.io,relay - - RULE-SET,file-provider,trojan - - GEOIP,CN,relay - - DOMAIN-SUFFIX,facebook.com,REJECT - - DOMAIN-KEYWORD,google,select - - DOMAIN,google.com,select - - SRC-IP-CIDR,192.168.1.1/24,DIRECT - - GEOIP,CN,DIRECT - - DST-PORT,53,trojan - - SRC-PORT,7777,DIRECT - - MATCH, DIRECT -... - -``` \ No newline at end of file diff --git a/docs/config/inbounds/http.md b/docs/config/inbounds/http.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/config/inbounds/index.md b/docs/config/inbounds/index.md deleted file mode 100644 index a5db8b4..0000000 --- a/docs/config/inbounds/index.md +++ /dev/null @@ -1,50 +0,0 @@ -## Simplified usage - -- HTTP Proxy - -```yaml -# port of HTTP proxy server -port: 7890 -``` - -- SOCKS Proxy - -```yaml -socks-port: 7891 -``` - -!!! Tip - Top-level HTTP/SOCKS/Mixed/Tproxy will be converted into inbounds add included in `listeners` - - | Type | Mapped inbound name | - | ---------- | -------------------- | - | `HTTP` | `HTTP-IN` | - | `SOCKS` | `SOCKS-IN` | - | `Mixed` | `MIXED-IN` | - | `Tproxy` | `TPROXY-IN` | - -## Supported Inbound Types - -- http -- socks -- mixed -- tproxy -- tunnel - - -## Common Options - -``` yaml -listeners: - - name: in-http - type: http #(3) - port: 15201 - listen: 127.0.0.1 #(4) - proxy: out-tuic #(1) - ...... #(2) -``` - -1. Optional, outbound name. Any traffic through this inbound will directly go to `proxy` -2. There could be more fields in real inbound -3. [Allowed Values](./#supported-inbound-types) -4. [Type: BindAddress](../../config/types/#bindaddress)
Address of inbound server diff --git a/docs/config/inbounds/socks.md b/docs/config/inbounds/socks.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/config/inbounds/tunnel.md b/docs/config/inbounds/tunnel.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/config/index.md b/docs/config/index.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/config/index.zh.md b/docs/config/index.zh.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/config/outbounds/tuic.md b/docs/config/outbounds/tuic.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/config/tun.md b/docs/config/tun.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/config/types.md b/docs/config/types.md deleted file mode 100644 index 09fb7c8..0000000 --- a/docs/config/types.md +++ /dev/null @@ -1 +0,0 @@ -## BindAddress \ No newline at end of file diff --git a/docs/en/config/full.md b/docs/en/config/full.md new file mode 100644 index 0000000..e08bb88 --- /dev/null +++ b/docs/en/config/full.md @@ -0,0 +1,3 @@ +# Full configuration example + +--8<-- "full-example.md" diff --git a/docs/en/config/inbounds.md b/docs/en/config/inbounds.md new file mode 100644 index 0000000..76dd185 --- /dev/null +++ b/docs/en/config/inbounds.md @@ -0,0 +1,35 @@ +# Inbounds + +## Listen on a port + +Top-level port options create named listeners. This example enables separate ports for HTTP and SOCKS: + +```yaml +port: 7890 +socks-port: 7891 +``` + +| Option | Listener name | +| --- | --- | +| `port` | `HTTP-IN` | +| `socks-port` | `SOCKS-IN` | +| `mixed-port` | `MIXED-IN` | +| `tproxy-port` | `TPROXY-IN` (requires TPROXY support) | + +## Define a listener + +Use `listeners` to choose a name, protocol, port and bind address: + +```yaml +listeners: + - name: in-http + type: http + listen: 127.0.0.1 + port: 15201 +``` + +Common listener types include `http`, `socks`, `mixed`, `tproxy` and `tunnel`. Available types depend on the build. A `tunnel` listener can set `proxy` to forward its traffic through a named outbound. + +### Bind address + +`listen` accepts an IPv4 or IPv6 address. Use `127.0.0.1` or `localhost` for IPv4 loopback, `"*"` for all IPv4 interfaces, or `"::"` for all IPv6 interfaces. diff --git a/docs/en/index.md b/docs/en/index.md new file mode 100644 index 0000000..39edbb4 --- /dev/null +++ b/docs/en/index.md @@ -0,0 +1,11 @@ +# ClashRS User Manual + +ClashRS is a rule-based network proxy written in Rust. It can serve HTTP and SOCKS clients or act as a network gateway through a TUN device. + +- [Quick start](quick-start.md) walks through starting a local proxy or choosing a graphical interface. +- [Inbounds](config/inbounds.md) explains how to accept connections. +- [Full configuration example](config/full.md) shows how DNS, outbounds and routing rules fit together. + +## Features + +ClashRS can route traffic by source, destination, domain or GeoIP and load remote proxy and rule providers. Its DNS resolver supports UDP, TCP, DNS over HTTPS and DNS over TLS. Outbound protocols include Shadowsocks, Trojan and VMess. ClashRS also supports distributed tracing. See the [ClashRS feature list](https://github.com/Watfaq/clash-rs#-features). diff --git a/docs/en/quick-start.md b/docs/en/quick-start.md new file mode 100644 index 0000000..94e07b1 --- /dev/null +++ b/docs/en/quick-start.md @@ -0,0 +1,24 @@ +# Quick start + +Download the binary for your platform from the [ClashRS releases](https://github.com/Watfaq/clash-rs/releases) and make it available as `clash-rs` on your PATH. + +## Start an HTTP proxy + +Save the following as `config.yaml`: + +```yaml +port: 7890 +``` + +Check the configuration, then start ClashRS: + +```sh +clash-rs -t -c config.yaml +clash-rs -c config.yaml +``` + +Set your application's HTTP proxy to `127.0.0.1:7890`. See [Inbounds](config/inbounds.md) for SOCKS and named listeners, or the [full configuration example](config/full.md) for routing and outbound settings. + +## Use a GUI + +[Clash Nyanpasu](https://github.com/LibNyanpasu/clash-nyanpasu) provides a graphical interface for ClashRS. diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index a684020..0000000 --- a/docs/index.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -hide: - - toc - - navigation ---- -# 👋Welcome to ClashRS User Manual - - - -This software is still under it's prerelease. Please report any missing/broken features if you'd like to 👍 - -## Overview - -ClashRS is a network proxy software that you can use to control how you want to divert your internet traffic through different proxy servers with flexible rules and multiple different supported outbound protocols. - -### [✨ Features](https://github.com/Watfaq/clash-rs#-features) - -- 🌈 Flexible traffic routing rules based off source/destination IP/Domain/GeoIP etc. -- 📦 Local anti spoofing DNS with support of UDP/TCP/DoH/DoT remote. -- 🛡 Run as a HTTP/Socks5 proxy, or utun device as a home network gateway. -- ⚙️ Shadowsocks/Trojan/Vmess outbound support with different underlying trasports. -- 🌍 Dynamic remote rule/proxy loader. -- 🎵 Tracing with Jaeger diff --git a/docs/index.zh.md b/docs/index.zh.md deleted file mode 100644 index 1ce4c90..0000000 --- a/docs/index.zh.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -hide: - - toc - - navigation ---- - -# 👋Welcome to ClashRS User Manual - - - -This software is still under it's prerelease. Please report any missing/broken features if you'd like to 👍 - -## Overview - -ClashRS is a network proxy software that you can use to control how you want to divert your internet traffic through different proxy servers with flexible rules and multiple different supported outbound protocols. - -### [✨ Features](https://github.com/Watfaq/clash-rs#-features) - -- 🌈 Flexible traffic routing rules based off source/destination IP/Domain/GeoIP etc. -- 📦 Local anti spoofing DNS with support of UDP/TCP/DoH/DoT remote. -- 🛡 Run as a HTTP/Socks5 proxy, or utun device as a home network gateway. -- ⚙️ Shadowsocks/Trojan/Vmess outbound support with different underlying trasports. -- 🌍 Dynamic remote rule/proxy loader. -- 🎵 Tracing with Jaeger diff --git a/docs/quick-start/cli.md b/docs/quick-start/cli.md deleted file mode 100644 index 9720664..0000000 --- a/docs/quick-start/cli.md +++ /dev/null @@ -1 +0,0 @@ -ffff \ No newline at end of file diff --git a/docs/quick-start/cli.zh.md b/docs/quick-start/cli.zh.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/quick-start/gui.md b/docs/quick-start/gui.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/quick-start/gui.zh.md b/docs/quick-start/gui.zh.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/quick-start/index.md b/docs/quick-start/index.md deleted file mode 100644 index cd82083..0000000 --- a/docs/quick-start/index.md +++ /dev/null @@ -1 +0,0 @@ -quick-start Index page \ No newline at end of file diff --git a/docs/quick-start/index.zh.md b/docs/quick-start/index.zh.md deleted file mode 100644 index e69de29..0000000 diff --git a/docs/zh/config/full.md b/docs/zh/config/full.md new file mode 100644 index 0000000..5495049 --- /dev/null +++ b/docs/zh/config/full.md @@ -0,0 +1,3 @@ +# 完整配置示例 + +--8<-- "full-example.md" diff --git a/docs/zh/config/inbounds.md b/docs/zh/config/inbounds.md new file mode 100644 index 0000000..ae6f861 --- /dev/null +++ b/docs/zh/config/inbounds.md @@ -0,0 +1,35 @@ +# 入站监听 + +## 配置端口 + +顶层端口字段会创建带有预设名称的监听器。以下配置分别开启 HTTP 和 SOCKS 端口: + +```yaml +port: 7890 +socks-port: 7891 +``` + +| 字段 | 监听器名称 | +| --- | --- | +| `port` | `HTTP-IN` | +| `socks-port` | `SOCKS-IN` | +| `mixed-port` | `MIXED-IN` | +| `tproxy-port` | `TPROXY-IN`(需要 TPROXY 支持) | + +## 自定义监听器 + +通过 `listeners` 可以指定监听器名称、协议、端口和绑定地址: + +```yaml +listeners: + - name: in-http + type: http + listen: 127.0.0.1 + port: 15201 +``` + +常见类型包括 `http`、`socks`、`mixed`、`tproxy` 和 `tunnel`,可用类型取决于构建时启用的功能。`tunnel` 监听器可以通过 `proxy` 指定转发流量的出站名称。 + +### 绑定地址 + +`listen` 接受 IPv4 或 IPv6 地址。`127.0.0.1` 和 `localhost` 表示 IPv4 回环地址,`"*"` 表示所有 IPv4 接口,`"::"` 表示所有 IPv6 接口。 diff --git a/docs/zh/index.md b/docs/zh/index.md new file mode 100644 index 0000000..7e4b841 --- /dev/null +++ b/docs/zh/index.md @@ -0,0 +1,11 @@ +# ClashRS 用户手册 + +ClashRS 是用 Rust 编写的规则代理。它可以为应用程序提供 HTTP 和 SOCKS 代理,也可以通过 TUN 设备接管网络流量。 + +- [快速开始](quick-start.md)介绍如何启动本地代理或使用图形界面。 +- [入站监听](config/inbounds.md)介绍如何配置接收连接的端口和地址。 +- [完整配置示例](config/full.md)展示 DNS、出站代理和路由规则如何配合使用。 + +## 功能 + +ClashRS 可以按来源、目的地址、域名或 GeoIP 分流,也可以加载远程代理和规则。DNS 解析支持 UDP、TCP、DoH 和 DoT。出站协议包括 Shadowsocks、Trojan 和 VMess,并支持分布式追踪。详见[项目功能列表](https://github.com/Watfaq/clash-rs#-features)。 diff --git a/docs/zh/quick-start.md b/docs/zh/quick-start.md new file mode 100644 index 0000000..c8a254a --- /dev/null +++ b/docs/zh/quick-start.md @@ -0,0 +1,24 @@ +# 快速开始 + +从 [ClashRS 发布页](https://github.com/Watfaq/clash-rs/releases)下载适合当前平台的可执行文件,放到 PATH 中,确保可以运行 `clash-rs`。 + +## 启动 HTTP 代理 + +将以下内容保存为 `config.yaml`: + +```yaml +port: 7890 +``` + +先检查配置,再启动 ClashRS: + +```sh +clash-rs -t -c config.yaml +clash-rs -c config.yaml +``` + +将应用程序的 HTTP 代理设为 `127.0.0.1:7890`。要使用 SOCKS 或自定义监听器,请参阅[入站监听](config/inbounds.md)。路由和出站配置可参考[完整配置示例](config/full.md)。 + +## 使用图形界面 + +[Clash Nyanpasu](https://github.com/LibNyanpasu/clash-nyanpasu) 提供支持 ClashRS 的图形界面。 diff --git a/landing/index.html b/landing/index.html new file mode 100644 index 0000000..e01e734 --- /dev/null +++ b/landing/index.html @@ -0,0 +1,23 @@ + + + + + +ClashRS · Documentation + + + +
+

ClashRS

+ +
+ + diff --git a/mkdocs.yml b/mkdocs.yml deleted file mode 100644 index 9bf4c41..0000000 --- a/mkdocs.yml +++ /dev/null @@ -1,126 +0,0 @@ -site_name: ClashRS User Mannual -docs_dir: docs -site_url: https://docs.watfaq.com/clash/ -repo_url: https://github.com/Watfaq/clash-rs -edit_uri: https://github.com/Watfaq/docs/blob/master/docs/ -repo_name: clash-rs - -theme: - logo: artwork/logo.png - favicon: artwork/logo.png - name: material - features: - - search.highlight - - navigation.tracking - # - navigation.instant - # - navigation.expand - - navigation.path - - navigation.indexes - - navigation.tracking - - navigation.top - - navigation.tabs - - navigation.sections - - content.action.edit - # markdown_extensions Code blocks - - content.code.copy - - content.code.annotate - - # markdown_extensions.pymdownx.tabbed - - content.tabs.link - palette: - - media: "(prefers-color-scheme)" - toggle: - icon: material/link - name: Switch to light mode - - media: "(prefers-color-scheme: light)" - scheme: default - primary: indigo - accent: indigo - toggle: - icon: material/toggle-switch - name: Switch to dark mode - - media: "(prefers-color-scheme: dark)" - scheme: slate - primary: black - accent: indigo - toggle: - icon: material/toggle-switch-off - name: Switch to system preference -# https://squidfunk.github.io/mkdocs-material/reference/ -markdown_extensions: - # Admonitions - - admonition - - pymdownx.details - - pymdownx.superfences - # Code blocks - - pymdownx.highlight: - anchor_linenums: true - line_spans: __span - pygments_lang_class: true - - pymdownx.inlinehilite - - pymdownx.snippets - # Content tabs - - pymdownx.tabbed: - alternate_style: true - # Foramtting - - pymdownx.critic - - pymdownx.keys - - pymdownx.keys - - pymdownx.mark - - pymdownx.tilde - # Lists - - def_list - - pymdownx.tasklist: - custom_checkbox: true - -nav: - - Welcome: index.md - - Quick start: - - quick-start/index.md - - CLI: quick-start/cli.md - - GUI: quick-start/gui.md - - Configuration: - - config/index.md - - Full Example: config/full.md - - Inbounds: - - config/inbounds/index.md - - HTTP: config/inbounds/http.md - - SOCKS: config/inbounds/socks.md - - Tunnel: config/inbounds/tunnel.md - -plugins: - # - search - # - awesome-pages - - i18n: - docs_structure: suffix - fallback_to_default: true - reconfigure_material: true - reconfigure_search: true - languages: - - build: true - default: true - locale: en - name: English - site_name: "ClashRS User Mannual" - - build: true - default: false - locale: zh - name: 简体中文 - site_name: "ClashRS 用户文档" - nav_translations: - Welcome: 欢迎 - Quick start: 快速开始 - CLI: 命令行界面 - GUI: 图形用户界面 - Configuration: 配置 - Full Example: 完整示例 - -extra: - analytics: - provider: google - property: G-YQC14KYW3F - social: - - icon: fontawesome/brands/github - link: https://github.com/Watfaq/clash-rs - - icon: material/file-document - link: https://github.com/Watfaq/docs diff --git a/docs/artwork/logo.png b/overrides/assets/images/clashrs.png similarity index 100% rename from docs/artwork/logo.png rename to overrides/assets/images/clashrs.png diff --git a/overrides/main.html b/overrides/main.html new file mode 100644 index 0000000..ad4ece3 --- /dev/null +++ b/overrides/main.html @@ -0,0 +1,7 @@ +{% extends "base.html" %} +{# Keep the language menu and hreflang metadata on the current article. #} +{% set localized = namespace(links=[]) %} +{% for alt in config.extra.alternate %} + {% set localized.links = localized.links + [dict(alt, link=alt.link ~ (page.url | default("", true)))] %} +{% endfor %} +{% set config = dict(config, extra=dict(config.extra, alternate=localized.links)) %} diff --git a/requirements.txt b/requirements.txt index 1f5aa50..d5e46a5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,2 @@ -mkdocs-material -mkdocs-minify-plugin -mkdocs-static-i18n \ No newline at end of file +zensical==0.1.4 +tzdata; sys_platform == "win32" diff --git a/docs/config/full.md b/shared/full-example.md similarity index 100% rename from docs/config/full.md rename to shared/full-example.md diff --git a/tests/check_site.py b/tests/check_site.py new file mode 100644 index 0000000..68d9188 --- /dev/null +++ b/tests/check_site.py @@ -0,0 +1,64 @@ +"""Check the bilingual contract in the generated GitHub Pages artifact.""" + +import json +from html.parser import HTMLParser +from pathlib import Path +from urllib.parse import urljoin, urlsplit + + +ROOT = Path(__file__).resolve().parents[1] +SITE = ROOT / "site" +ORIGIN = "https://docs.watfaq.com" + + +class Page(HTMLParser): + def __init__(self, path): + super().__init__() + self.elements = [] + self.feed(path.read_text(encoding="utf-8")) + + def handle_starttag(self, tag, attrs): + self.elements.append((tag, dict(attrs))) + + +def check(): + pages = {path: Page(path) for path in SITE.rglob("*.html")} + for path, page in pages.items(): + url = f"{ORIGIN}/{path.relative_to(SITE).as_posix()}" + for tag, attrs in page.elements: + link = attrs.get("href") or attrs.get("src") + if not link: + continue + target = urlsplit(urljoin(url, link)) + if target.netloc != "docs.watfaq.com" or target.scheme != "https": + continue + dest = SITE / target.path.lstrip("/") + if dest.is_dir(): + dest /= "index.html" + assert dest.is_file(), (path, link) + + for lang in ("en", "zh"): + root = SITE / "clash" / lang + index = json.loads((root / "search.json").read_text(encoding="utf-8")) + assert index["config"]["lang"] == [lang], lang + locations = {item["location"] for item in index["items"]} + for source in (ROOT / "docs" / lang).rglob("*.md"): + stem = source.relative_to(ROOT / "docs" / lang).with_suffix("") + route = stem.parent if stem.name == "index" else stem + suffix = route.as_posix() + "/" if route.parts else "" + assert suffix in locations, (lang, suffix) + elements = pages[root / route / "index.html"].elements + assert any(tag == "html" and attrs.get("lang") == lang for tag, attrs in elements) + expected = {code: f"/clash/{code}/{suffix}" for code in ("en", "zh")} + for tag in ("a", "link"): + alternate = { + attrs["hreflang"]: attrs["href"] + for t, attrs in elements + if t == tag and "hreflang" in attrs + } + assert alternate == expected, (lang, suffix, tag) + + +if __name__ == "__main__": + check() + print("Bilingual site checks passed") diff --git a/zensical.toml b/zensical.toml new file mode 100644 index 0000000..e0cd84b --- /dev/null +++ b/zensical.toml @@ -0,0 +1,66 @@ +[project] +site_name = "ClashRS User Manual" +site_url = "https://docs.watfaq.com/clash/en/" +docs_dir = "docs/en" +site_dir = "site/clash/en" +repo_name = "clash-rs" +repo_url = "https://github.com/Watfaq/clash-rs" +edit_uri = "https://github.com/Watfaq-legacy/docs/edit/master/docs/en/" +nav = [ + { "Overview" = "index.md" }, + { "Quick start" = "quick-start.md" }, + { "Configuration" = [ + { "Inbounds" = "config/inbounds.md" }, + { "Full example" = "config/full.md" }, + ] }, +] + +[project.theme] +language = "en" +custom_dir = "overrides" +logo = "assets/images/clashrs.png" +favicon = "assets/images/clashrs.png" +features = [ + "navigation.tracking", "navigation.path", "navigation.top", "navigation.tabs", + "navigation.sections", "search.highlight", "content.action.edit", + "content.code.copy", "content.code.annotate", "content.tabs.link", +] + +[[project.theme.palette]] +media = "(prefers-color-scheme: light)" +scheme = "default" +primary = "indigo" +toggle = { icon = "lucide/moon", name = "Switch to dark mode" } + +[[project.theme.palette]] +media = "(prefers-color-scheme: dark)" +scheme = "slate" +primary = "black" +toggle = { icon = "lucide/sun", name = "Switch to light mode" } + +[project.markdown_extensions.tables] +[project.markdown_extensions.admonition] +[project.markdown_extensions."pymdownx.details"] +[project.markdown_extensions."pymdownx.superfences"] +[project.markdown_extensions."pymdownx.highlight"] +anchor_linenums = true +line_spans = "__span" +pygments_lang_class = true + +[project.markdown_extensions."pymdownx.snippets"] +base_path = ["shared"] +check_paths = true + +[project.extra] +alternate = [ + { name = "English", link = "/clash/en/", lang = "en" }, + { name = "简体中文", link = "/clash/zh/", lang = "zh" }, +] +social = [ + { icon = "fontawesome/brands/github", link = "https://github.com/Watfaq/clash-rs" }, + { icon = "material/file-document", link = "https://github.com/Watfaq-legacy/docs" }, +] + +[project.extra.analytics] +provider = "google" +property = "G-YQC14KYW3F" diff --git a/zensical.zh.toml b/zensical.zh.toml new file mode 100644 index 0000000..3991870 --- /dev/null +++ b/zensical.zh.toml @@ -0,0 +1,66 @@ +[project] +site_name = "ClashRS 用户手册" +site_url = "https://docs.watfaq.com/clash/zh/" +docs_dir = "docs/zh" +site_dir = "site/clash/zh" +repo_name = "clash-rs" +repo_url = "https://github.com/Watfaq/clash-rs" +edit_uri = "https://github.com/Watfaq-legacy/docs/edit/master/docs/zh/" +nav = [ + { "概览" = "index.md" }, + { "快速开始" = "quick-start.md" }, + { "配置" = [ + { "入站监听" = "config/inbounds.md" }, + { "完整示例" = "config/full.md" }, + ] }, +] + +[project.theme] +language = "zh" +custom_dir = "overrides" +logo = "assets/images/clashrs.png" +favicon = "assets/images/clashrs.png" +features = [ + "navigation.tracking", "navigation.path", "navigation.top", "navigation.tabs", + "navigation.sections", "search.highlight", "content.action.edit", + "content.code.copy", "content.code.annotate", "content.tabs.link", +] + +[[project.theme.palette]] +media = "(prefers-color-scheme: light)" +scheme = "default" +primary = "indigo" +toggle = { icon = "lucide/moon", name = "切换到深色模式" } + +[[project.theme.palette]] +media = "(prefers-color-scheme: dark)" +scheme = "slate" +primary = "black" +toggle = { icon = "lucide/sun", name = "切换到浅色模式" } + +[project.markdown_extensions.tables] +[project.markdown_extensions.admonition] +[project.markdown_extensions."pymdownx.details"] +[project.markdown_extensions."pymdownx.superfences"] +[project.markdown_extensions."pymdownx.highlight"] +anchor_linenums = true +line_spans = "__span" +pygments_lang_class = true + +[project.markdown_extensions."pymdownx.snippets"] +base_path = ["shared"] +check_paths = true + +[project.extra] +alternate = [ + { name = "English", link = "/clash/en/", lang = "en" }, + { name = "简体中文", link = "/clash/zh/", lang = "zh" }, +] +social = [ + { icon = "fontawesome/brands/github", link = "https://github.com/Watfaq/clash-rs" }, + { icon = "material/file-document", link = "https://github.com/Watfaq-legacy/docs" }, +] + +[project.extra.analytics] +provider = "google" +property = "G-YQC14KYW3F" From b47fe215d6ce69839a7c81900497ab7887a9d981 Mon Sep 17 00:00:00 2001 From: iHsin Date: Wed, 2 Dec 2026 10:57:48 +0800 Subject: [PATCH 2/2] docs: rewrite and expand the bilingual ClashRS manual Expand the English and Simplified Chinese Zensical documentation to match clash-rs, covering installation, CLI/environment options, DNS, TUN, all inbound and outbound protocols, proxy groups, routing rules, providers, Mihomo compatibility, safe paths, the REST API, and a refreshed shared full example. Assisted-by: Antigravity --- docs/en/config/dns.md | 152 ++++++++ docs/en/config/full.md | 4 +- docs/en/config/inbounds.md | 35 -- docs/en/config/inbounds/http.md | 61 +++ docs/en/config/inbounds/index.md | 65 ++++ docs/en/config/inbounds/protocols.md | 110 ++++++ docs/en/config/inbounds/socks.md | 45 +++ docs/en/config/inbounds/transparent.md | 68 ++++ docs/en/config/inbounds/tunnel.md | 65 ++++ docs/en/config/index.md | 113 ++++++ docs/en/config/outbounds/index.md | 57 +++ docs/en/config/outbounds/quic.md | 87 +++++ docs/en/config/outbounds/shadowsocks.md | 108 ++++++ docs/en/config/outbounds/tls-socks.md | 111 ++++++ docs/en/config/outbounds/tuic.md | 51 +++ docs/en/config/outbounds/v2ray.md | 132 +++++++ docs/en/config/outbounds/vpn.md | 135 +++++++ docs/en/config/providers.md | 145 ++++++++ docs/en/config/proxy-groups.md | 164 +++++++++ docs/en/config/rules.md | 85 +++++ docs/en/config/tun.md | 136 +++++++ docs/en/config/types.md | 106 ++++++ docs/en/guides/api.md | 119 ++++++ docs/en/guides/compatibility.md | 110 ++++++ docs/en/index.md | 48 ++- docs/en/quick-start.md | 24 -- docs/en/quick-start/cli.md | 87 +++++ docs/en/quick-start/gui.md | 60 +++ docs/en/quick-start/index.md | 144 ++++++++ docs/zh/config/dns.md | 152 ++++++++ docs/zh/config/full.md | 2 + docs/zh/config/inbounds.md | 35 -- docs/zh/config/inbounds/http.md | 61 +++ docs/zh/config/inbounds/index.md | 65 ++++ docs/zh/config/inbounds/protocols.md | 110 ++++++ docs/zh/config/inbounds/socks.md | 45 +++ docs/zh/config/inbounds/transparent.md | 68 ++++ docs/zh/config/inbounds/tunnel.md | 65 ++++ docs/zh/config/index.md | 113 ++++++ docs/zh/config/outbounds/index.md | 57 +++ docs/zh/config/outbounds/quic.md | 87 +++++ docs/zh/config/outbounds/shadowsocks.md | 108 ++++++ docs/zh/config/outbounds/tls-socks.md | 111 ++++++ docs/zh/config/outbounds/tuic.md | 51 +++ docs/zh/config/outbounds/v2ray.md | 132 +++++++ docs/zh/config/outbounds/vpn.md | 135 +++++++ docs/zh/config/providers.md | 145 ++++++++ docs/zh/config/proxy-groups.md | 164 +++++++++ docs/zh/config/rules.md | 85 +++++ docs/zh/config/tun.md | 136 +++++++ docs/zh/config/types.md | 106 ++++++ docs/zh/guides/api.md | 119 ++++++ docs/zh/guides/compatibility.md | 110 ++++++ docs/zh/index.md | 48 ++- docs/zh/quick-start.md | 24 -- docs/zh/quick-start/cli.md | 87 +++++ docs/zh/quick-start/gui.md | 60 +++ docs/zh/quick-start/index.md | 144 ++++++++ shared/full-example.md | 469 ++++++++++++------------ zensical.toml | 47 ++- zensical.zh.toml | 47 ++- 61 files changed, 5443 insertions(+), 372 deletions(-) create mode 100644 docs/en/config/dns.md delete mode 100644 docs/en/config/inbounds.md create mode 100644 docs/en/config/inbounds/http.md create mode 100644 docs/en/config/inbounds/index.md create mode 100644 docs/en/config/inbounds/protocols.md create mode 100644 docs/en/config/inbounds/socks.md create mode 100644 docs/en/config/inbounds/transparent.md create mode 100644 docs/en/config/inbounds/tunnel.md create mode 100644 docs/en/config/index.md create mode 100644 docs/en/config/outbounds/index.md create mode 100644 docs/en/config/outbounds/quic.md create mode 100644 docs/en/config/outbounds/shadowsocks.md create mode 100644 docs/en/config/outbounds/tls-socks.md create mode 100644 docs/en/config/outbounds/tuic.md create mode 100644 docs/en/config/outbounds/v2ray.md create mode 100644 docs/en/config/outbounds/vpn.md create mode 100644 docs/en/config/providers.md create mode 100644 docs/en/config/proxy-groups.md create mode 100644 docs/en/config/rules.md create mode 100644 docs/en/config/tun.md create mode 100644 docs/en/config/types.md create mode 100644 docs/en/guides/api.md create mode 100644 docs/en/guides/compatibility.md delete mode 100644 docs/en/quick-start.md create mode 100644 docs/en/quick-start/cli.md create mode 100644 docs/en/quick-start/gui.md create mode 100644 docs/en/quick-start/index.md create mode 100644 docs/zh/config/dns.md delete mode 100644 docs/zh/config/inbounds.md create mode 100644 docs/zh/config/inbounds/http.md create mode 100644 docs/zh/config/inbounds/index.md create mode 100644 docs/zh/config/inbounds/protocols.md create mode 100644 docs/zh/config/inbounds/socks.md create mode 100644 docs/zh/config/inbounds/transparent.md create mode 100644 docs/zh/config/inbounds/tunnel.md create mode 100644 docs/zh/config/index.md create mode 100644 docs/zh/config/outbounds/index.md create mode 100644 docs/zh/config/outbounds/quic.md create mode 100644 docs/zh/config/outbounds/shadowsocks.md create mode 100644 docs/zh/config/outbounds/tls-socks.md create mode 100644 docs/zh/config/outbounds/tuic.md create mode 100644 docs/zh/config/outbounds/v2ray.md create mode 100644 docs/zh/config/outbounds/vpn.md create mode 100644 docs/zh/config/providers.md create mode 100644 docs/zh/config/proxy-groups.md create mode 100644 docs/zh/config/rules.md create mode 100644 docs/zh/config/tun.md create mode 100644 docs/zh/config/types.md create mode 100644 docs/zh/guides/api.md create mode 100644 docs/zh/guides/compatibility.md delete mode 100644 docs/zh/quick-start.md create mode 100644 docs/zh/quick-start/cli.md create mode 100644 docs/zh/quick-start/gui.md create mode 100644 docs/zh/quick-start/index.md diff --git a/docs/en/config/dns.md b/docs/en/config/dns.md new file mode 100644 index 0000000..82ffd9f --- /dev/null +++ b/docs/en/config/dns.md @@ -0,0 +1,152 @@ +# DNS Configuration + +ClashRS includes an anti-spoofing DNS resolver and a multi-protocol local DNS server supporting UDP, TCP, DoT, DoH, and DoH3. + +When `dns.enable` is `false` (default), ClashRS delegates name resolution to the operating system (`SystemResolver`) and starts no local DNS server. + +## All `dns` Fields + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `enable` | `bool` | `false` | Enable the built-in DNS resolver and optional local DNS server. | +| `ipv6` | `bool` | `false` | Resolve `AAAA` records. **Effective value is `config.ipv6 && dns.ipv6`** (both must be `true`). | +| `use-hosts` | `bool` | `true` | Look up top-level `hosts` entries before querying upstreams (`localhost -> 127.0.0.1` is always present). | +| `listen` | `string` or object | `None` | Local DNS server bind address(es). Omit to disable the local DNS listener. See [DNS Listeners](#dns-listeners). | +| `enhanced-mode` | `normal` \| `fake-ip` \| `redir-host` | `normal` | `fake-ip` allocates synthetic IPs from `fake-ip-range`. **`redir-host` is accepted for parsing only and is a no-op** (logs a warning). | +| `fake-ip-range` | CIDR string | `"198.18.0.1/16"` | Address pool used in `fake-ip` mode. Validated even when `dns.enable: false`. | +| `fake-ip-filter` | `list[string]` | `[]` | Domains that bypass Fake-IP and return real IPs (supports `StringTrie` patterns such as `*.lan`, `+.example.com`). Outbound proxy server hostnames are automatically excluded to prevent loops. | +| `default-nameserver` | `list[string]` | `["114.114.114.114", "8.8.8.8"]` | Bootstrap DNS servers used to resolve hostnames of DoH/DoT upstreams and `proxy-server-nameserver`. **Must be non-empty and contain IP addresses only** (no hostnames). Unaffected by `respect-rules`. | +| `nameserver` | `list[string]` | `[]` | Primary upstream DNS servers. Must be non-empty when `dns.enable: true`, except when Mihomo-style TUN is active (in which case empty `nameserver` falls back to `default-nameserver`). | +| `fallback` | `list[string]` | `[]` | Secondary upstream DNS servers used according to `fallback-filter`. | +| `fallback-filter` | object | See below | Rules deciding when to prefer `fallback` results over `nameserver`. | +| `proxy-server-nameserver` | `list[string]` | `[]` | Dedicated upstreams for resolving outbound proxy server hostnames (domain-based DoH/DoT URLs are allowed and bootstrapped via `default-nameserver`). Unaffected by `respect-rules`. | +| `nameserver-policy` | `map[domain -> string]` | `{}` | Per-domain upstream override. **Each value is a single upstream string** (not a list). | +| `edns-client-subnet` | object | `None` | Attach ECS to upstream queries (`ipv4` and/or `ipv6` CIDR; at least one must be set). Does not overwrite an existing ECS option on incoming requests. | +| `respect-rules` | `bool` | `false` | Route `nameserver`, `fallback`, and `nameserver-policy` upstream traffic through the rule engine instead of `DIRECT`. | + +!!! note "Unsupported Mihomo DNS Keys" + `use-system-hosts`, `cache-algorithm`, `fake-ip-filter-mode`, and `direct-nameserver` are not implemented in ClashRS. Response caching uses a fixed 1,024-entry LRU cache (and a 1,024-entry, 3-second reverse IP→domain cache). + +## Local DNS Listeners (`dns.listen`) { #dns-listeners } + +`dns.listen` supports two forms: + +=== "Single UDP String" + + ```yaml + dns: + enable: true + listen: 127.0.0.1:5353 + ``` + + A leading colon such as `:5353` expands to `0.0.0.0:5353`. + +=== "Multi-Protocol Map" + + Expose UDP, TCP, DoT, DoH, and DoH3 simultaneously: + + ```yaml + dns: + enable: true + listen: + udp: 127.0.0.1:5353 + tcp: 127.0.0.1:5353 + dot: + addr: 127.0.0.1:853 + ca-cert: certs/dns.crt + ca-key: certs/dns.key + doh: + addr: 127.0.0.1:8443 + ca-cert: certs/dns.crt + ca-key: certs/dns.key + hostname: dns.example.com + doh3: + addr: 127.0.0.1:8443 + ca-cert: certs/dns.crt + ca-key: certs/dns.key + hostname: dns.example.com + ``` + + - `dot`: `addr` (required), optional `ca-cert`, `ca-key`. + - `doh` & `doh3`: `addr` (required), optional `ca-cert`, `ca-key`, `hostname` (TLS / QUIC SNI). + +## Upstream URL Syntax + +| Scheme | Default Port | Example | +| --- | --- | --- | +| `udp://` (or omitted) | `53` | `1.1.1.1`, `udp://8.8.8.8:53`, `2400:3200::1` | +| `tcp://` | `53` | `tcp://8.8.8.8:53` | +| `tls://` (DoT) | `853` | `tls://dns.quad9.net:853` | +| `https://` (DoH) | `443` | `https://cloudflare-dns.com/dns-query` | +| `dhcp://` | — | `dhcp://eth0` (queries DNS from the interface's DHCP lease) | + +Important details verified from source: + +- `"system"` is **not** supported as an upstream entry (logged and skipped). +- **DoH path is fixed to `/dns-query`**; custom URL paths on `https://` upstreams are ignored. Connecting to an IP-literal DoH server disables hostname certificate verification. +- **URL fragment routing modifiers** (separated by `&` after `#`): + - `#` or `#proxy=` — send DNS queries through a specific outbound proxy or group. + - `#interface=` — bind upstream queries to a specific interface (`auto` detects the default physical interface; inherited automatically when TUN is active). + +```yaml +nameserver: + - https://1.1.1.1/dns-query#PROXY + - 223.5.5.5#interface=eth0 +``` + +## `fallback-filter` + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `geoip` | `bool` | `true` | If `nameserver` returns an IP outside `geoip-code`, prefer `fallback`. If no `mmdb` is configured/loaded, the filter evaluates to `true` (uses `fallback`). | +| `geoip-code` | `string` | `"CN"` | ISO country code (normalized to uppercase). | +| `ipcidr` | `list[CIDR]` | `[]` | Results matching any of these CIDRs trigger `fallback`. | +| `domain` | `list[string]` | `[]` | Queries matching these domains always use `fallback`. | + +## Complete DNS Example + +```yaml +ipv6: true +mmdb: Country.mmdb + +hosts: + router.lan: 192.168.1.1 + +dns: + enable: true + ipv6: true + use-hosts: true + listen: + udp: 127.0.0.1:5353 + tcp: 127.0.0.1:5353 + enhanced-mode: fake-ip + fake-ip-range: 198.18.0.1/16 + fake-ip-filter: + - "*.lan" + - "+.local" + - "time.windows.com" + default-nameserver: + - 223.5.5.5 + - 8.8.8.8 + proxy-server-nameserver: + - https://dns.alidns.com/dns-query + nameserver: + - 223.5.5.5 + - 119.29.29.29 + fallback: + - tls://1.1.1.1:853 + - https://dns.google/dns-query + fallback-filter: + geoip: true + geoip-code: CN + ipcidr: + - 240.0.0.0/4 + domain: + - "+.google.com" + - "+.github.com" + nameserver-policy: + "+.internal.example.com": 192.168.1.1 + edns-client-subnet: + ipv4: 198.51.100.0/24 + respect-rules: false +``` diff --git a/docs/en/config/full.md b/docs/en/config/full.md index e08bb88..8b5a127 100644 --- a/docs/en/config/full.md +++ b/docs/en/config/full.md @@ -1,3 +1,5 @@ -# Full configuration example +# Full Configuration Example + +This annotated reference combines general settings, DNS, TUN, listeners, tunnels, modern outbound protocols, proxy groups, inline rule providers, and routing rules. Replace all placeholder hostnames, UUIDs, keys, and passwords before use, and validate with `clash-rs -c config.yaml -t --strict-config`. --8<-- "full-example.md" diff --git a/docs/en/config/inbounds.md b/docs/en/config/inbounds.md deleted file mode 100644 index 76dd185..0000000 --- a/docs/en/config/inbounds.md +++ /dev/null @@ -1,35 +0,0 @@ -# Inbounds - -## Listen on a port - -Top-level port options create named listeners. This example enables separate ports for HTTP and SOCKS: - -```yaml -port: 7890 -socks-port: 7891 -``` - -| Option | Listener name | -| --- | --- | -| `port` | `HTTP-IN` | -| `socks-port` | `SOCKS-IN` | -| `mixed-port` | `MIXED-IN` | -| `tproxy-port` | `TPROXY-IN` (requires TPROXY support) | - -## Define a listener - -Use `listeners` to choose a name, protocol, port and bind address: - -```yaml -listeners: - - name: in-http - type: http - listen: 127.0.0.1 - port: 15201 -``` - -Common listener types include `http`, `socks`, `mixed`, `tproxy` and `tunnel`. Available types depend on the build. A `tunnel` listener can set `proxy` to forward its traffic through a named outbound. - -### Bind address - -`listen` accepts an IPv4 or IPv6 address. Use `127.0.0.1` or `localhost` for IPv4 loopback, `"*"` for all IPv4 interfaces, or `"::"` for all IPv6 interfaces. diff --git a/docs/en/config/inbounds/http.md b/docs/en/config/inbounds/http.md new file mode 100644 index 0000000..0ed602b --- /dev/null +++ b/docs/en/config/inbounds/http.md @@ -0,0 +1,61 @@ +# HTTP & Mixed Inbounds + +ClashRS supports standalone HTTP proxies (`http`) and combined HTTP + SOCKS5 proxies (`mixed`) on a single TCP port. + +## HTTP Inbound (`type: http`) + +- **Transport**: TCP only (supports both plain HTTP proxy requests and `CONNECT` tunneling for HTTPS). +- **Authentication**: Uses top-level `authentication` via HTTP Basic `Proxy-Authorization`. +- **Type-specific fields**: None beyond [common listener fields](index.md#common-listeners-fields). + +=== "Top-Level Shorthand" + + ```yaml + port: 7890 + bind-address: 127.0.0.1 + allow-lan: false + authentication: + - "alice:secret123" + ``` + +=== "Named Listener" + + ```yaml + listeners: + - name: http-in + type: http + listen: 127.0.0.1 + port: 7890 + allow-lan: false + ``` + +## Mixed Inbound (`type: mixed`) + +The `mixed` listener peeks at the first byte of each incoming TCP connection: + +- If the first byte is `0x05`, the connection is handled as **SOCKS5** (including `UDP_ASSOCIATE`). +- Otherwise, the connection is handled as an **HTTP** proxy request. + +- **Authentication**: Uses top-level `authentication` for both HTTP and SOCKS5 clients. +- **Type-specific fields**: + - `udp` (`bool`, optional, default `true`): Accepted for schema compatibility. At runtime, SOCKS5 `UDP_ASSOCIATE` is always available over the SOCKS5 handshake. + +=== "Top-Level Shorthand" + + ```yaml + mixed-port: 7890 + bind-address: 127.0.0.1 + allow-lan: false + ``` + +=== "Named Listener" + + ```yaml + listeners: + - name: mixed-in + type: mixed + listen: 0.0.0.0 + port: 7890 + allow-lan: true + udp: true + ``` diff --git a/docs/en/config/inbounds/index.md b/docs/en/config/inbounds/index.md new file mode 100644 index 0000000..c319150 --- /dev/null +++ b/docs/en/config/inbounds/index.md @@ -0,0 +1,65 @@ +# Inbounds Overview + +Inbounds accept local or remote client traffic and hand connections to the ClashRS routing dispatcher. You can configure them via: + +1. **Top-level port shorthands** (`port`, `socks-port`, `mixed-port`, `redir-port`, `tproxy-port`) +2. **Named `listeners`** for full multi-protocol, multi-port control +3. **Top-level `tunnels`** for fixed-target TCP/UDP forwarding +4. **`inbound-providers`** for dynamic file or HTTP listener lists +5. **[`tun`](../tun.md)** for L3 transparent proxying + +## Top-Level Port Shorthands + +Each top-level port field (type [`Port`](../types.md#port)) is converted into a named listener that inherits top-level `bind-address`, `allow-lan`, and `routing-mark`: + +| Top-Level Key | Alias | Generated Listener Name | Inbound Type | Implicit Defaults | Required Feature | +| --- | --- | --- | --- | --- | --- | +| `port` | `http_port` | `HTTP-IN` | `http` | — | Built-in | +| `socks-port` | — | `SOCKS-IN` | `socks` | `udp: true` | Built-in | +| `mixed-port` | — | `MIXED-IN` | `mixed` | `udp: true` | Built-in | +| `redir-port` | — | `REDIR-IN` | `redir` | — | `redir` (`standard`) | +| `tproxy-port` | — | `TPROXY-IN` | `tproxy` | `udp: true`, `dns-hijack: true` | `tproxy` (`standard`) | + +If `bind-address` is left at its default (`0.0.0.0`) and top-level `ipv6: true`, shorthand listeners automatically upgrade to dual-stack `::`. + +## Supported `listeners` Types + +| Type | Transport | Platform / Feature | Reference | +| --- | --- | --- | --- | +| `http` | TCP | All / built-in | [HTTP & Mixed](http.md) | +| `mixed` | TCP + SOCKS5 UDP | All / built-in | [HTTP & Mixed](http.md) | +| `socks` | TCP + UDP (`UDP_ASSOCIATE`) | All / built-in | [SOCKS5](socks.md) | +| `tproxy` (or `t-proxy`) | TCP + UDP | Linux, Android / `tproxy` | [Transparent Proxy](transparent.md) | +| `redir` | TCP | Linux / `redir` | [Transparent Proxy](transparent.md) | +| `tunnel` | TCP / UDP | All / built-in | [Tunnel](tunnel.md) | +| `shadowsocks` | TCP + UDP | All / `shadowsocks` | [Proxy Protocols](protocols.md) | +| `anytls` | TCP + UoT v2 | All / built-in | [Proxy Protocols](protocols.md) | +| `hysteria2` | QUIC (UDP) | All / built-in | [Proxy Protocols](protocols.md) | + +## Common `listeners` Fields + +Every entry in `listeners` shares these base fields: + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name` | `string` | Yes | — | Listener name. | +| `type` | `string` | Yes | — | Inbound type from the table above. | +| `listen` | [`BindAddress`](../types.md#bindaddress) | Yes | — | Listen IP (`*`, `localhost`, `::`, `[::]`, or IP literal). | +| `port` | `u16` | Yes | — | Listen port (integer). | +| `allow-lan` | `bool` | No | `false` | Allow connections from non-local addresses (currently not enforced on `tunnel` and `tproxy`). | +| `fw-mark` | [`SocketMark`](../types.md#socketmark) | No | `None` | Linux/Android `SO_MARK` propagated to `Session.so_mark`. | + +```yaml +listeners: + - name: local-mixed + type: mixed + listen: 127.0.0.1 + port: 7890 + allow-lan: false +``` + +### Deduplication & Authentication + +- **Precedence**: `listeners` entries are registered first, followed by `tunnels`, and finally top-level port shorthands. Identical entries are deduplicated with a warning (note that `name` is part of equality, so listeners with different names on the same port will conflict at bind time). +- **Global `authentication`**: Top-level `authentication: ["user:pass"]` applies to `http`, `socks`, and `mixed` listeners (both shorthand and `listeners[]`). Protocol inbounds (`shadowsocks`, `anytls`, `hysteria2`) use their own `password` / `users` credentials instead. +- **Hot user updates**: For `shadowsocks`, `anytls`, and `hysteria2`, updating `users` via `inbound-providers` reloads credentials in place without restarting the listening socket. See [Providers](../providers.md#inbound-providers). diff --git a/docs/en/config/inbounds/protocols.md b/docs/en/config/inbounds/protocols.md new file mode 100644 index 0000000..6726de1 --- /dev/null +++ b/docs/en/config/inbounds/protocols.md @@ -0,0 +1,110 @@ +# Proxy Protocol Inbounds (Shadowsocks, AnyTLS, Hysteria2) + +ClashRS can act as an authenticated proxy server using `shadowsocks`, `anytls`, and `hysteria2` listeners. All three support multi-user credentials (`users`) that populate `IN-USER` routing rules and `/user-stats` traffic accounting, and support in-place user hot reloads via [`inbound-providers`](../providers.md#inbound-providers). + +## Multi-User Entry Format (`InboundUser`) + +```yaml +users: + - name: alice + password: "user-specific-password" + - name: bob + password: "another-password" +``` + +The `name` field is recorded as `inbound_user` on the session for `IN-USER` rules and `GET /user-stats`. + +--- + +## Shadowsocks Inbound (`type: shadowsocks`) + +- **Feature**: `shadowsocks` (enabled in `standard` / default builds). +- **Transport**: TCP + optional UDP (`udp` defaults to `true`). + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `cipher` | `string` | Yes | — | Any cipher supported by ClashRS Shadowsocks (see [Shadowsocks Outbound](../outbounds/shadowsocks.md#supported-ciphers)). | +| `password` | `string` | Yes | — | Single-user password, or the server PSK for Shadowsocks 2022 multi-user EIH. | +| `udp` | `bool` | No | `true` | Enable UDP relay on the listener. | +| `users` | `list[InboundUser]` | No | `[]` | SS2022 multi-user EIH entries (`password` must be Base64 user key). | + +```yaml +listeners: + - name: ss2022-server + type: shadowsocks + listen: 0.0.0.0 + port: 8388 + allow-lan: true + cipher: 2022-blake3-aes-128-gcm + password: "BASE64_SERVER_PSK" + udp: true + users: + - name: alice + password: "BASE64_ALICE_KEY" +``` + +--- + +## AnyTLS Inbound (`type: anytls`) + +- **Feature**: Built-in (all platforms). +- **Transport**: TCP with TLS; UDP is multiplexed over the same connection via UoT v2. + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `password` | `string` | Yes | — | Single-user plaintext password (active when `users` is empty). | +| `users` | `list[InboundUser]` | No | `[]` | Multi-user plaintext passwords; when non-empty, replaces `password`. Duplicate passwords are rejected during validation. | +| `certificate` | `string` | No | Self-signed `localhost` cert | PEM certificate chain file path or inline PEM. Must be paired with `private-key`. | +| `private-key` | `string` | No | Self-signed `localhost` key | PEM private key file path or inline PEM. Must be paired with `certificate`. | +| `fallback` | `string` | No | `None` | `host:port` fallback address for TLS connections that fail password authentication (e.g. a local web server for active-probe camouflage). Unauthenticated connections are dropped when unset. | + +```yaml +listeners: + - name: anytls-server + type: anytls + listen: 0.0.0.0 + port: 8443 + allow-lan: true + password: "default-password" + certificate: certs/fullchain.pem + private-key: certs/privkey.pem + fallback: 127.0.0.1:80 + users: + - name: alice + password: "alice-password" +``` + +--- + +## Hysteria2 Inbound (`type: hysteria2`) + +- **Feature**: Built-in (all platforms). +- **Transport**: QUIC (UDP) with ALPN `h3` and HTTP/3 authentication (`POST https://hysteria/auth`). TCP uses QUIC bidirectional streams; UDP uses QUIC datagrams. + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `password` | `string` | Yes | — | Single-user plaintext password (active when `users` is empty). | +| `users` | `list[InboundUser]` | No | `[]` | Multi-user list (replaces `password` when non-empty). | +| `certificate` | `string` | No | Self-signed `localhost` cert | PEM certificate chain path or inline PEM. Must be paired with `private-key`. | +| `private-key` | `string` | No | Self-signed `localhost` key | PEM private key path or inline PEM. Must be paired with `certificate`. | + +```yaml +listeners: + - name: hy2-server + type: hysteria2 + listen: 0.0.0.0 + port: 8443 + allow-lan: true + password: "default-password" + certificate: certs/fullchain.pem + private-key: certs/privkey.pem + users: + - name: alice + password: "alice-hy2-password" +``` diff --git a/docs/en/config/inbounds/socks.md b/docs/en/config/inbounds/socks.md new file mode 100644 index 0000000..8bcdf73 --- /dev/null +++ b/docs/en/config/inbounds/socks.md @@ -0,0 +1,45 @@ +# SOCKS5 Inbound + +The `socks` inbound implements SOCKS5 (`RFC 1928`) with TCP `CONNECT`, UDP `UDP_ASSOCIATE`, and optional username/password authentication (`RFC 1929`). + +- **Platform / Feature**: All platforms, built-in. +- **Authentication**: Uses top-level `authentication` (`username:password` entries). +- **Type-specific fields**: + - `udp` (`bool`, optional, default `true`): Accepted in config; at runtime `UDP_ASSOCIATE` is always enabled on the SOCKS5 TCP handshake (no static UDP bind port is opened separately). + +=== "Top-Level Shorthand" + + ```yaml + socks-port: 7891 + bind-address: 127.0.0.1 + allow-lan: false + authentication: + - "alice:secret123" + ``` + +=== "Named Listener" + + ```yaml + listeners: + - name: socks-in + type: socks + listen: 127.0.0.1 + port: 7891 + allow-lan: false + udp: true + ``` + +## Routing & Testing + +Match SOCKS5 traffic in rules using `IN-TYPE,SOCKS,` (or `SOCKS5`): + +```yaml +rules: + - IN-TYPE,SOCKS,PROXY +``` + +Verify with `curl`: + +```bash +curl --socks5-hostname 127.0.0.1:7891 https://example.com +``` diff --git a/docs/en/config/inbounds/transparent.md b/docs/en/config/inbounds/transparent.md new file mode 100644 index 0000000..0109451 --- /dev/null +++ b/docs/en/config/inbounds/transparent.md @@ -0,0 +1,68 @@ +# Transparent Proxy Inbounds (TProxy & Redir) + +In addition to [TUN](../tun.md), ClashRS supports kernel-level transparent proxying via **TProxy** (TCP + UDP) and **Redir** (TCP). + +## TProxy Inbound (`type: tproxy`) + +- **Platforms**: **Linux and Android only** (logs a warning and skips on other platforms). +- **Feature**: `tproxy` (enabled in `standard` / default builds). +- **Transport**: TCP and UDP (`IP_TRANSPARENT`). +- **Aliases**: Both `type: tproxy` and `type: t-proxy` are accepted. + +### Fields + +In addition to common listener fields (`name`, `listen`, `port`, `allow-lan`, `fw-mark`): + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `udp` | `bool` | `true` | Accepted in config; at runtime `TproxyInbound` always handles UDP. | +| `dns-hijack` | `bool` | `true` | Hijack TProxy UDP DNS traffic to the built-in DNS resolver. | + +=== "Top-Level Shorthand" + + ```yaml + tproxy-port: 7893 + routing-mark: 6666 + ``` + +=== "Named Listener" + + ```yaml + listeners: + - name: tproxy-in + type: tproxy + listen: 0.0.0.0 + port: 7893 + udp: true + dns-hijack: true + fw-mark: 6666 + ``` + +!!! tip "Loop Avoidance on Linux" + Always set top-level `routing-mark` (or `fw-mark`) and exclude that mark in your `iptables` / `nftables` `TPROXY` rules so outbound connections generated by ClashRS are not redirected back into `tproxy-port`. + +## Redir Inbound (`type: redir`) + +- **Platforms**: **Linux only** (uses `SO_ORIGINAL_DST` / `IP6T_SO_ORIGINAL_DST`). +- **Feature**: `redir` (enabled in `standard` / default builds). +- **Transport**: TCP only. +- **Type-specific fields**: None beyond common listener fields. + +=== "Top-Level Shorthand" + + ```yaml + redir-port: 7892 + routing-mark: 6666 + ``` + +=== "Named Listener" + + ```yaml + listeners: + - name: redir-in + type: redir + listen: 0.0.0.0 + port: 7892 + allow-lan: true + fw-mark: 6666 + ``` diff --git a/docs/en/config/inbounds/tunnel.md b/docs/en/config/inbounds/tunnel.md new file mode 100644 index 0000000..49144d1 --- /dev/null +++ b/docs/en/config/inbounds/tunnel.md @@ -0,0 +1,65 @@ +# Tunnel Inbound (Port Forwarding) + +Tunnel inbounds forward incoming TCP and/or UDP connections on a local port to a fixed `target` address. + +- **Platform / Feature**: All platforms, built-in. +- **Routing behavior**: + - When `proxy` is set to an outbound proxy or proxy group name (including `DIRECT`, `REJECT`, `GLOBAL`, or a provider node looked up at traffic time), all traffic through the tunnel uses that outbound regardless of `mode`. If the named outbound is unavailable, traffic is dropped. + - When `proxy` is omitted (or empty), traffic goes through normal routing rules. + +## Top-Level `tunnels` Shorthand + +`tunnels` accepts either structured YAML mappings or comma-separated strings: + +```yaml +tunnels: + - network: [tcp, udp] + address: 127.0.0.1:1053 + target: 192.0.2.53:53 + proxy: DIRECT + - "tcp,127.0.0.1:8443,example.org:443" + - "tcp/udp,127.0.0.1:5353,1.1.1.1:53,PROXY" +``` + +### Mapping Fields + +| Key | Type | Required | Description | +| --- | --- | --- | --- | +| `network` | `list["tcp" \| "udp"]` | Yes | Non-empty list of protocols (`tcp`, `udp`). | +| `address` | `string` | Yes | Local bind `host:port` (empty host or `*` → `0.0.0.0`; `localhost` → `127.0.0.1`). | +| `target` | [`SocksAddr`](../types.md#socksaddr) | Yes | Fixed destination `host:port` (port must be non-zero). | +| `proxy` | `string` | No | Fixed outbound or proxy group name. Omit for normal rule routing. | + +### String Format + +```text +network,address,target[,proxy] +``` + +- `network` separates protocols with `/` (e.g. `tcp`, `udp`, `tcp/udp`). +- Duplicate `(listen, port, transport)` entries return a configuration error. +- Generated listener names follow `tunnel--` with `allow-lan` derived from `!listen.ip().is_loopback()` and `fw-mark` inherited from top-level `routing-mark`. + +## Named Listener (`listeners` with `type: tunnel`) + +You can configure the exact same tunnel as an explicit listener by splitting `address` into `listen` and `port`: + +```yaml +listeners: + - name: dns-tunnel + type: tunnel + listen: 127.0.0.1 + port: 1053 + network: + - tcp + - udp + target: 192.0.2.53:53 + proxy: DIRECT +``` + +| Key | Type | Required | Description | +| --- | --- | --- | --- | +| `name`, `type`, `listen`, `port`, `fw-mark` | Common fields | Yes (except `fw-mark`) | Standard listener fields (`type: tunnel`). | +| `network` | `list["tcp" \| "udp"]` | Yes | Protocols to listen on (case-insensitive). | +| `target` | [`SocksAddr`](../types.md#socksaddr) | Yes | Destination `host:port`. | +| `proxy` | `string` | No | Fixed outbound name; omit to route normally. | diff --git a/docs/en/config/index.md b/docs/en/config/index.md new file mode 100644 index 0000000..8140ef1 --- /dev/null +++ b/docs/en/config/index.md @@ -0,0 +1,113 @@ +# Configuration Overview + +ClashRS uses a single YAML configuration file (default `config.yaml` inside the working directory `-d`). Before deserialization, ClashRS expands standard YAML anchors and merge keys (`<<: *anchor`). + +By default, unknown YAML keys are silently ignored so profiles authored for Mihomo or Clash can load without modification. Pass `--strict-config` on the CLI to reject unknown keys at any nesting depth. + +## Top-Level Sections + +| Section | Description | Reference | +| --- | --- | --- | +| General & Controller | Ports, binding, mode, logging, IPv6, GeoData, `hosts`, `profile`, `experimental`, controller/UI | This page | +| `dns` | Built-in DNS resolver, Fake-IP, fallback filters, local DNS listeners | [DNS](dns.md) | +| `tun` | Cross-platform TUN transparent proxy | [TUN](tun.md) | +| `listeners` / `tunnels` / `inbound-providers` | Multi-protocol inbound listeners & fixed port forwarding | [Inbounds](inbounds/index.md) | +| `proxies` | Outbound proxy definitions | [Outbounds](outbounds/index.md) | +| `proxy-groups` | Selection, URL-test, fallback, load-balance, relay, and smart groups | [Proxy Groups](proxy-groups.md) | +| `rules` | Traffic routing rules | [Routing Rules](rules.md) | +| `proxy-providers` / `rule-providers` | Remote, file, and inline providers | [Providers](providers.md) | + +## General Options + +### Inbound Shorthand & Network + +| Key | Alias | Type | Default | Description | +| --- | --- | --- | --- | --- | +| `port` | `http_port` | [`Port`](types.md#port) | `None` | HTTP proxy port (mapped to listener `HTTP-IN`). | +| `socks-port` | — | [`Port`](types.md#port) | `None` | SOCKS5 proxy port with UDP enabled (mapped to `SOCKS-IN`). | +| `mixed-port` | — | [`Port`](types.md#port) | `None` | Combined HTTP + SOCKS5 port with UDP enabled (mapped to `MIXED-IN`). | +| `redir-port` | — | [`Port`](types.md#port) | `None` | Linux TCP Redirect port (`redir` feature; mapped to `REDIR-IN`). | +| `tproxy-port` | — | [`Port`](types.md#port) | `None` | Linux/Android TProxy port (`tproxy` feature; mapped to `TPROXY-IN`). | +| `authentication` | — | `list[string]` | `[]` | Credentials for `http`, `socks`, and `mixed` inbounds in `"username:password"` format (split on the first `:`; missing `:` yields an empty password). | +| `allow-lan` | — | `bool` | `false` | Allow connections from non-local addresses. When `false`, inbound listeners require `peer_addr.ip() == local_addr.ip()`. | +| `bind-address` | — | [`BindAddress`](types.md#bindaddress) | `0.0.0.0` (`::` when left default and `ipv6: true`) | Bind IP for top-level shorthand ports. Accepts `*`, `localhost`, `::`, `[::]`, or any IP literal. | +| `mode` | — | `rule` \| `global` \| `direct` | `rule` | Routing mode (also accepts capitalized `Rule`, `Global`, `Direct`). | +| `log-level` | — | `trace` \| `debug` \| `info` \| `warning` (`warn`) \| `error` \| `silent` (`off`) | `info` | Runtime log verbosity. Overridden if `RUST_LOG` is set. | +| `unified-delay` | — | `bool` | `false` | Measure latency on an already established HTTP connection to exclude handshake overhead. | +| `ipv6` | — | `bool` | `false` | Global IPv6 switch. Upgrades default `bind-address` to `::`, gates DNS IPv6 (`config.ipv6 && dns.ipv6`), and enables default IPv6 `gateway-v6` in Mihomo TUN mode. | +| `interface` | `interface-name` | `string` | `None` | Default physical outbound interface name or IP address (used when TUN is enabled). | +| `routing-mark` | — | [`SocketMark`](types.md#socketmark) | `None` | Outbound socket `SO_MARK` on Linux (and Android with `tproxy` feature). Inherited by `tun.so-mark` (when unset) and DNS clients. | + +### External Controller & Dashboard + +| Key | Alias | Type | Default | Description | +| --- | --- | --- | --- | --- | +| `external-controller` | — | `string` | `None` | REST API TCP listen address (e.g. `127.0.0.1:9090`; `:9090` expands to `127.0.0.1:9090`). Non-loopback bindings require both non-empty `secret` and CORS origins. | +| `external-controller-ipc` | `external-controller-unix` (Unix), `external-controller-pipe` (Windows) | `string` | `None` | Unix Domain Socket path or Windows Named Pipe (`\\.\pipe\clash-rs`). Can run alongside TCP. Overridden by `--controller-ipc`. | +| `external-ui` | — | `string` | `None` | Local directory (relative to `-d`) served at `/ui/`. Falls back to the embedded dashboard if empty/missing. | +| `external-ui-url` | — | `string` | `None` | Archive URL (`.zip`/`.tgz`) downloaded into `external-ui` when empty. Supports `#force=true` and `#_clash_outbound=`. | +| `secret` | — | `string` | `None` | Bearer token for TCP API authentication (`Authorization: Bearer ` or `?token=` for WebSockets). Not applied to IPC. | +| `external-controller-cors` | — | object | `None` | CORS configuration with `allow-origins: list[string]` and `allow-private-network: bool` (default `true`). | +| `cors-allow-origins` | — | `list[string]` | `None` | Legacy fallback for `external-controller-cors.allow-origins`. | + +```yaml +external-controller: 0.0.0.0:9090 +secret: "strong-random-secret" +external-controller-cors: + allow-origins: + - "https://metacubex.github.io" + - "http://127.0.0.1:9090" + allow-private-network: true +``` + +### GeoData & Static Hosts + +GeoData files are resolved relative to `-d` (subject to [Safe Paths](../guides/compatibility.md#safe-paths)) and are **only loaded/downloaded when their path is configured** (or automatically defaulted in `--compatibility` mode). + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `mmdb` | `string` | `None` (`Country.mmdb` in `--compatibility`) | Country GeoIP MMDB path. Required by `GEOIP` rules and `dns.fallback-filter.geoip`. | +| `mmdb-download-url` | `string` | `https://github.com/Loyalsoldier/geoip/releases/latest/download/Country.mmdb` | Download URL used when `mmdb` is missing or refreshed via `POST /configs/geo`. | +| `asn-mmdb` | `string` | `None` | ASN MMDB database path. | +| `asn-mmdb-download-url` | `string` | `https://git.io/GeoLite2-ASN.mmdb` | Download URL for `asn-mmdb`. | +| `geosite` | `string` | `None` (`geosite.dat` in `--compatibility`) | GeoSite database path. Required by `GEOSITE` rules. | +| `geosite-download-url` | `string` or `list[string]` | Loyalsoldier `v2ray-rules-dat` jsDelivr + GitHub mirror list | Single URL or ordered mirror list (non-empty). | +| `hosts` | `map[domain -> IP]` | `{}` | Static domain-to-IP mappings used when `dns.use-hosts: true`. `localhost -> 127.0.0.1` is always built in. | + +### `profile` + +Controls persistent local caches stored inside `-d`: + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `store-selected` | `bool` | `true` | Persist `select` proxy group choices to `cache.db` (`clash-rs-cache.db` in `--compatibility` mode). | +| `store-fake-ip` | `bool` | `false` | Persist Fake-IP mappings to disk. When `false`, uses an in-memory store (capacity 1,000). | +| `store-smart-stats` | `bool` | `true` | Persist `smart` proxy group scoring statistics every 30 seconds. | + +```yaml +profile: + store-selected: true + store-fake-ip: false + store-smart-stats: true +``` + +### `experimental` + +Optional buffer and runtime tuning knobs: + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `tcp-buffer-size` | `usize` (bytes) | `65536` (64 KiB) | Bidirectional TCP relay copy buffer size. | +| `anytls-duplex-buffer-size` | `usize` (bytes) | `16384` (16 KiB) | Internal duplex pipe buffer size for AnyTLS. | +| `anytls-relay-buffer-size` | `usize` (bytes) | `4096` (4 KiB) | Read buffer size for AnyTLS relay loops. | +| `closed-flows-cap` | `usize` | `50` | Ring-buffer capacity for closed flow records returned by `/flows`. | +| `ignore-resolve-fail` | `bool` | `false` | Accepted for config compatibility (currently unused at runtime). | + +## Unsupported Mihomo / Clash Top-Level Keys + +The following keys from other Clash forks are **not** defined in ClashRS (silently ignored normally; rejected under `--strict-config`): + +- `geodata-mode`, `geodata-loader`, `geox-url` +- `fwmark` (use `routing-mark` instead) +- `skip-auth-prefixes`, `lan-allowed-ips`, `lan-disallowed-ips` +- `sniffer`, `ntp`, `sub-rules`, `script`, `find-process-mode`, `global-client-fingerprint`, `ebpf` diff --git a/docs/en/config/outbounds/index.md b/docs/en/config/outbounds/index.md new file mode 100644 index 0000000..2b229c5 --- /dev/null +++ b/docs/en/config/outbounds/index.md @@ -0,0 +1,57 @@ +# Outbounds Overview + +Outbound proxies are defined under top-level `proxies` (or loaded dynamically via [`proxy-providers`](../providers.md#proxy-providers)). Every proxy must have a globally unique `name`. + +Two built-in proxies — **`DIRECT`** and **`REJECT`** — are registered automatically and cannot be shadowed by user-defined entries. + +## Supported Outbound Protocols (16 Types) + +| `type` | Transports / Highlights | Default UDP | `connect-via` Support | Required Feature | Page | +| --- | --- | --- | --- | --- | --- | +| `direct` | Direct egress | Always `true` | TCP | Built-in | This page | +| `reject` | Drop connection | `false` | All | Built-in | This page | +| `ss` | Plain, `obfs`, `v2ray-plugin` (WS), `shadow-tls` v3 | `true` | TCP + UDP | `shadowsocks` (`standard`) | [Shadowsocks](shadowsocks.md) | +| `trojan` | TLS, WS, gRPC, mTLS | `false` | TCP + UDP | Built-in | [Trojan, VMess & VLESS](v2ray.md) | +| `vmess` | TCP, TLS, WS, H2, gRPC, XHTTP, mTLS | `true` | TCP + UDP | Built-in | [Trojan, VMess & VLESS](v2ray.md) | +| `vless` | TCP, TLS, WS, H2, gRPC, XHTTP, REALITY, Vision, mTLS | `true` | TCP + UDP | Built-in | [Trojan, VMess & VLESS](v2ray.md) | +| `tuic` | QUIC v5 (`bbr`/`bbr3`/`cubic`/`new_reno`), mTLS | Always `true` | Not supported | `tuic` (`standard`) | [TUIC](tuic.md) | +| `hysteria2` | QUIC, port hopping, Salamander obfs, mTLS | Server-negotiated | Not in schema | Built-in | [Hysteria2 & ShadowQUIC](quic.md) | +| `shadowquic` | QUIC / over-stream, JLS, brutal/bbr/bbr3 | Always `true` | Not supported | `shadowquic` (`standard`) | [Hysteria2 & ShadowQUIC](quic.md) | +| `anytls` | TLS + UoT v2, mTLS | `false` | TCP + UDP | Built-in | [AnyTLS, Naive & SOCKS5](tls-socks.md) | +| `naive` | HTTP/2 or QUIC (Cronet) + UoT v2 | `false` | Rejected (`InvalidConfig`) | `naive` (**opt-in**) | [AnyTLS, Naive & SOCKS5](tls-socks.md) | +| `socks5` | Plain TCP or TLS + UDP | `true` | TCP + UDP | Built-in | [AnyTLS, Naive & SOCKS5](tls-socks.md) | +| `wireguard` | Userspace BoringTun (IPv4/IPv6) | `false` | Not supported | `wireguard` (`standard`) | [VPN & Tunneling](vpn.md) | +| `ssh` | SSH tunnel (password, key, host-key, TOTP) | `false` | TCP | `ssh` (`standard`) | [VPN & Tunneling](vpn.md) | +| `tailscale` | Tailnet / Headscale mesh VPN | Always `true` | Not supported | `tailscale` (`standard`) | [VPN & Tunneling](vpn.md) | +| `tor` | Tor onion routing | `false` | Not supported | `onion` (`plus` build) | [VPN & Tunneling](vpn.md) | + +!!! warning "Unsupported Outbound Types & Per-Proxy Fields" + - **Unsupported types**: `http` outbound, `snell`, and `ssr` are **not** supported and fail YAML parsing. + - **Absent per-proxy fields**: `smux`, `ip-version`, and standalone `shadow-tls-opts` do not exist (ShadowTLS is configured via `ss` `plugin: shadow-tls`). Per-proxy `interface-name` and `routing-mark` are only available on `tor`; use top-level `interface` / `routing-mark` or rule-level `interface=` for global/per-rule egress control. + +## Common Outbound Options (`CommonConfigOptions`) + +Shared by `ss`, `socks5`, `anytls`, `trojan`, `vmess`, `vless`, `wireguard`, `tuic`, `naive`, `ssh`, and `shadowquic`: + +| Key | Alias | Type | Required | Description | +| --- | --- | --- | --- | --- | +| `name` | — | `string` | Yes | Unique proxy name. | +| `server` | — | `string` | Yes | Server hostname or IP. | +| `port` | — | `u16` | Yes | Server port (integer). | +| `connect-via` | `dialer-proxy` | `string` | No | Upstream proxy or proxy group name used to dial this proxy (cannot reference a node defined only inside a `proxy-provider`). | + +## Built-in `direct` and `reject` + +While `DIRECT` and `REJECT` are always registered automatically, you may also define custom aliases: + +```yaml +proxies: + - name: my-direct + type: direct + - name: my-reject + type: reject +``` + +## Client Certificates (mTLS) + +`anytls`, `trojan`, `vmess`, `vless` (non-REALITY), `tuic`, and `hysteria2` support mutual TLS via `tls-cert` and `tls-key` (file path or inline PEM; both must be provided together). See [TLS Certificates](../types.md#tls-certificates). diff --git a/docs/en/config/outbounds/quic.md b/docs/en/config/outbounds/quic.md new file mode 100644 index 0000000..f71c4d9 --- /dev/null +++ b/docs/en/config/outbounds/quic.md @@ -0,0 +1,87 @@ +# Hysteria2 & ShadowQUIC Outbounds + +## Hysteria2 (`type: hysteria2`) + +- **Feature**: Built-in (all platforms). +- **UDP**: Negotiated from the server's `Hysteria-UDP` auth header (defaults to `true` before connection). +- **`connect-via`**: Not part of the `hysteria2` config schema. + +### Fields + +| Key | Alias | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | --- | +| `name` | — | `string` | Yes | — | Unique proxy name. | +| `server` | — | `string` | Yes | — | Server hostname or IP. | +| `port` | — | `u16` | Yes | — | Primary UDP port. | +| `password` | — | `string` | Yes | — | Hysteria2 authentication password. | +| `skip-cert-verify` | — | `bool` | **Yes** | None | **Must be explicitly set** (`true` or `false`) in YAML because the schema has no default for this field. | +| `ports` | — | `string` | No | `None` | Port hopping ranges/list (e.g. `"20000-30000,40000"`). | +| `hop-interval` | `hop_interval` | `u64` (seconds) | No | `30` | Port hopping interval. | +| `obfs` | — | `"salamander"` | No | `None` | Obfuscation type. When set, `obfs-password` is required. | +| `obfs-password` | — | `string` | When `obfs` set | `None` | Salamander obfuscation password. | +| `sni` | — | `string` | No | `server` | TLS SNI. | +| `alpn` | — | `list[string]` | No | `["h3"]` | TLS ALPN protocols. | +| `fingerprint` | — | `string` | No | `None` | Server certificate SHA-256 hex fingerprint pinning. | +| `udp-mtu` | — | `u32` | No | `None` | Custom UDP MTU. | +| `disable-mtu-discovery` | — | `bool` | No | `false` | Disable QUIC PMTU discovery. | +| `tls-cert`, `tls-key` | — | `string` | No | `None` | Paired mTLS client certificate and private key. | + +!!! note "Parsed-only Hysteria2 fields" + `ca` (logs a warning), `ca-str`, `up`, `down`, and `cwnd` are accepted in YAML for compatibility with external profiles, but are currently unused at runtime. + +```yaml +proxies: + - name: hy2-node + type: hysteria2 + server: hy2.example.com + port: 443 + ports: "20000-30000" + hop-interval: 30 + password: "your-hy2-password" + obfs: salamander + obfs-password: "your-obfs-password" + sni: hy2.example.com + skip-cert-verify: false +``` + +--- + +## ShadowQUIC (`type: shadowquic`) + +- **Feature**: `shadowquic` (enabled in `standard` / default builds). +- **UDP**: Always enabled (QUIC datagram by default, or QUIC stream when `over-stream: true`). +- **`connect-via`**: Ignored at runtime. + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `server`, `port` | Common | Yes | — | Standard outbound options. | +| `username` | `string` | Yes | — | JLS username. | +| `password` | `string` | Yes | — | JLS password. | +| `server-name` | `string` | Yes | — | JLS upstream camouflage hostname (SNI). | +| `alpn` | `list[string]` | No | `["h3"]` | TLS ALPN list. | +| `initial-mtu` | `u16` | No | `1300` | Initial QUIC MTU (minimum `1200`). | +| `min-mtu` | `u16` | No | `1290` | Minimum QUIC MTU (minimum `1200`). | +| `congestion-control` | string or map | No | `"bbr"` | `"bbr"`, `"cubic"`, `"new-reno"`, `"bbr3"`, or map `brutal: { bandwidth, min-window, cwnd-gain, min-ack-rate, min-sample-count, ack-compensate }`. | +| `zero-rtt` | `bool` | No | `true` | Enable QUIC 0-RTT. | +| `over-stream` | `bool` | No | `false` | Relay UDP over QUIC streams instead of QUIC datagrams. | +| `keep-alive-interval` | `u32` (ms) | No | `0` (disabled) | QUIC keep-alive interval. | +| `gso` | `bool` | No | `true` | Enable UDP Generic Segmentation Offload. | +| `mtu-discovery` | `bool` | No | `true` | Enable QUIC path MTU discovery. | + +```yaml +proxies: + - name: sq-node + type: shadowquic + server: sq.example.com + port: 443 + username: "jls-user" + password: "jls-password" + server-name: www.example.org + alpn: + - h3 + congestion-control: bbr3 + zero-rtt: true + over-stream: false +``` diff --git a/docs/en/config/outbounds/shadowsocks.md b/docs/en/config/outbounds/shadowsocks.md new file mode 100644 index 0000000..de883a8 --- /dev/null +++ b/docs/en/config/outbounds/shadowsocks.md @@ -0,0 +1,108 @@ +# Shadowsocks Outbound (`type: ss`) + +Supports classic AEAD ciphers, Shadowsocks 2022 BLAKE3 ciphers, and pluggable transports (`obfs`, `v2ray-plugin`, and `shadow-tls` v3). + +- **Feature**: `shadowsocks` (enabled in `standard` / default builds). +- **`connect-via` / `dialer-proxy`**: TCP + UDP supported. + +## Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `server`, `port`, `connect-via` (`dialer-proxy`) | Common | Yes (except `connect-via`) | — | Standard outbound options. | +| `cipher` | `string` | Yes | — | Encryption cipher (see list below). | +| `password` | `string` | Yes | — | Password or Base64 PSK (for SS2022). | +| `udp` | `bool` | No | `true` | Enable UDP relay. | +| `plugin` | `string` | No | `None` | One of `"obfs"`, `"v2ray-plugin"`, or `"shadow-tls"`. Requires `plugin-opts` when set. | +| `plugin-opts` | map | Required if `plugin` set | `None` | Plugin-specific options (see below). | + +## Supported Ciphers { #supported-ciphers } + +Exactly 8 ciphers are supported by ClashRS (`map_cipher`): + +- `aes-128-gcm` +- `aes-256-gcm` +- `chacha20-ietf-poly1305` +- `xchacha20-ietf-poly1305` +- `2022-blake3-aes-128-gcm` +- `2022-blake3-aes-256-gcm` +- `2022-blake3-chacha20-ietf-poly1305` +- `rc4-md5` + +## Plugins + +=== "shadow-tls (v3)" + + | `plugin-opts` Key | Type | Required | Default | Description | + | --- | --- | --- | --- | --- | + | `password` | `string` | Yes | — | ShadowTLS v3 password. | + | `host` | `string` | No | `"bing.com"` | TLS SNI handshake host. | + | `strict` | `bool` | No | `true` | Enable strict mode. | + + ```yaml + proxies: + - name: ss-shadowtls + type: ss + server: proxy.example.com + port: 443 + cipher: 2022-blake3-aes-128-gcm + password: "BASE64_PSK" + udp: true + plugin: shadow-tls + plugin-opts: + host: www.example.org + password: "shadowtls-password" + strict: true + ``` + +=== "v2ray-plugin" + + | `plugin-opts` Key | Type | Required | Default | Description | + | --- | --- | --- | --- | --- | + | `mode` | `string` | Yes | — | Must be `"websocket"`. | + | `host` | `string` | No | `"bing.com"` | WebSocket `Host` and TLS SNI. | + | `path` | `string` | No | `""` (`"/"` on wire) | WebSocket path. | + | `tls` | `bool` | No | `false` | Wrap WebSocket in TLS. | + | `port` | `u16` | No | `443` (if `tls`) / `80` | Port used in WebSocket Upgrade `Host` header. | + | `skip-cert-verify` | `bool` | No | `false` | Skip TLS certificate verification. | + | `headers` | map | No | `{}` | Extra headers (`Host` auto-filled from `host` if absent). | + | `mux` | `bool` | No | `false` | **Setting `mux: true` fails with an error** (`v2ray plugin does not support mux`). | + + ```yaml + proxies: + - name: ss-v2ray-ws + type: ss + server: proxy.example.com + port: 443 + cipher: aes-256-gcm + password: "password" + plugin: v2ray-plugin + plugin-opts: + mode: websocket + tls: true + host: ws.example.com + path: /ws + ``` + +=== "obfs (deprecated)" + + Logs a deprecation warning on startup. + + | `plugin-opts` Key | Type | Required | Default | Description | + | --- | --- | --- | --- | --- | + | `mode` | `"http"` \| `"tls"` | Yes | — | Obfuscation mode. | + | `host` | `string` | No | `"bing.com"` | Disguised HTTP/TLS host. | + + ```yaml + proxies: + - name: ss-obfs + type: ss + server: proxy.example.com + port: 8388 + cipher: aes-256-gcm + password: "password" + plugin: obfs + plugin-opts: + mode: tls + host: www.example.com + ``` diff --git a/docs/en/config/outbounds/tls-socks.md b/docs/en/config/outbounds/tls-socks.md new file mode 100644 index 0000000..aad49d1 --- /dev/null +++ b/docs/en/config/outbounds/tls-socks.md @@ -0,0 +1,111 @@ +# AnyTLS, Naive & SOCKS5 Outbounds + +## AnyTLS (`type: anytls`) + +- **Feature**: Built-in (all platforms). +- **`connect-via`**: TCP + UDP supported. + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `server`, `port`, `connect-via` | Common | Yes (except `connect-via`) | — | Standard outbound options. | +| `password` | `string` | Yes | — | AnyTLS password. | +| `sni` | `string` | No | `server` | TLS SNI. | +| `alpn` | `list[string]` | No | `["h2", "http/1.1"]` | TLS ALPN list. | +| `skip-cert-verify` | `bool` | No | `false` | Skip TLS certificate verification. | +| `udp` | `bool` | No | `false` | Enable UDP relay via UoT v2. | +| `tls-cert`, `tls-key` | `string` | No | `None` | Paired mTLS client certificate and private key. | + +!!! note "Parsed-only AnyTLS fields" + `fingerprint`, `client-fingerprint`, `idle-session-check-interval`, `idle-session-timeout`, and `min-idle-session` are accepted in YAML for profile compatibility, log a warning, and have no runtime effect. + +```yaml +proxies: + - name: anytls-node + type: anytls + server: anytls.example.com + port: 443 + password: "your-anytls-password" + sni: anytls.example.com + udp: true +``` + +--- + +## Naive (`type: naive`) + +Powered by Wind + Chromium Cronet, supporting HTTP/2 and QUIC transports with optional UDP over TCP (UoT v2). + +- **Feature**: `naive` (**not** enabled in `default` or `standard` builds). To compile with a prebuilt static Cronet binary on supported platforms: + +```bash +cargo build --locked --release -p clash-rs --features naive-static,naive-download +``` + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `server`, `port` | Common | Yes (`port > 0`) | — | Standard outbound options (bracketed IPv6 literals like `[::1]` are accepted). **Setting `connect-via` / `dialer-proxy` fails with `InvalidConfig`.** | +| `username` | `string` | Yes | — | Non-empty username; **must not contain `:`**. | +| `password` | `string` | Yes | — | Non-empty password. | +| `quic` | `bool` | No | `false` | `false` uses HTTP/2; `true` uses QUIC. | +| `udp` | `bool` | No | `false` | Enable UDP over TCP (UoT v2) if supported by the server. | +| `concurrency` | `u32` | No | `1` | Connection pool concurrency (must be `> 0`). | +| `congestion-controller` | `"default"` \| `"bbr"` \| `"bbrv2"` \| `"cubic"` \| `"reno"` | No | `"default"` | Congestion controller. | +| `request-timeout` | `u64` (ms) | No | `10000` | Request timeout (must be `> 0`). | +| `ca-cert` | `string` | No | `None` | Custom root/server PEM certificate (file path or inline PEM; **inline PEM only** inside `proxy-providers`). | +| `cronet-lib-path` | `string` | No | `None` | Path or library name of a shared `libcronet` (for dynamic builds). **Main config only** (rejected in `proxy-providers` and `--service-mode`). All Naive proxies share the first library loaded in the process; restart ClashRS to change it. | +| `skip-cert-verify` | `bool` | No | `false` | **Setting `true` is rejected with an error.** Trust self-signed certificates via `ca-cert` instead. | +| `sni` | `string` | No | `None` | **If set, must match `server` case-insensitively** or config validation fails. | + +### Operational Notes + +- With TUN active, Naive supports outbound interface selection on Linux, macOS, and Windows, and `routing-mark` on Linux (Android ignores both). +- If the proxy hostname cannot be resolved, configure `dns.proxy-server-nameserver` or add it to `dns.fake-ip-filter`. +- When a config reload or provider update replaces a Naive proxy, existing TCP/UDP sessions close once the old proxy instance is released. + +```yaml +proxies: + - name: naive-h2 + type: naive + server: naive.example.com + port: 443 + username: "your-username" + password: "your-password" + quic: false + udp: true + concurrency: 2 +``` + +--- + +## SOCKS5 (`type: socks5`) + +- **Feature**: Built-in (all platforms). +- **`connect-via`**: TCP + UDP supported. + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `server`, `port`, `connect-via` | Common | Yes (except `connect-via`) | — | Standard outbound options. | +| `username` | `string` | No | `None` | SOCKS5 authentication username. | +| `password` | `string` | No | `None` | SOCKS5 authentication password. | +| `tls` | `bool` | No | `false` | Wrap SOCKS5 control connection in TLS. | +| `sni` | `string` | No | `server` | TLS SNI (when `tls: true`). | +| `skip-cert-verify` | `bool` | No | `false` | Skip TLS certificate verification. | +| `udp` | `bool` | No | `true` | Enable UDP relay (`UDP_ASSOCIATE`). | + +```yaml +proxies: + - name: upstream-socks + type: socks5 + server: 192.0.2.10 + port: 1080 + username: "alice" + password: "secret" + tls: false + udp: true +``` diff --git a/docs/en/config/outbounds/tuic.md b/docs/en/config/outbounds/tuic.md new file mode 100644 index 0000000..e8542e0 --- /dev/null +++ b/docs/en/config/outbounds/tuic.md @@ -0,0 +1,51 @@ +# TUIC Outbound (`type: tuic`) + +Implements TUIC v5 over QUIC (powered by Wind TUIC + Quinn). + +- **Feature**: `tuic` (enabled in `standard` / default builds). +- **UDP**: Always enabled (`native` datagram or `quic` stream relay). +- **`connect-via`**: Parsed via common options, but ignored at runtime (QUIC dials directly). + +## Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `server`, `port` | Common | Yes | — | Standard outbound options. | +| `uuid` | UUID string | Yes | — | TUIC v5 UUID. | +| `password` | `string` | Yes | — | TUIC v5 password. | +| `ip` | `string` | No | `None` | Override resolved IP for `server`. | +| `sni` | `string` | No | `server` | TLS SNI. | +| `disable-sni` | `bool` | No | `false` | Omit SNI during TLS handshake. | +| `alpn` | `list[string]` | No | `["h3"]` | TLS ALPN list. | +| `skip-cert-verify` | `bool` | No | `false` | Skip TLS certificate verification. | +| `udp-relay-mode` | `"native"` \| `"quic"` | No | `"native"` | Case-insensitive; unknown strings fall back to `"quic"`. | +| `congestion-controller` | `"bbr"` \| `"bbr3"` \| `"cubic"` \| `"new_reno"` (`"newreno"`) | No | `"bbr"` | QUIC congestion control algorithm (case-insensitive). | +| `reduce-rtt` | `bool` | No | `false` | Enable QUIC 0-RTT handshake. | +| `fast-open` | `bool` | No | `false` | Logical OR with `reduce-rtt` (`reduce-rtt || fast-open`). | +| `heartbeat-interval` | `u64` (ms) | No | `3000` | Heartbeat interval in milliseconds. | +| `request-timeout` | `u64` (ms) | No | `4000` | Handshake/request timeout and QUIC idle timeout. | +| `max-open-stream` | `u64` | No | `32` | Maximum concurrent streams per QUIC connection. | +| `gc-interval` | `u64` (ms) | No | `3000` | UDP fragment garbage-collection interval. | +| `gc-lifetime` | `u64` (ms) | No | `15000` | UDP fragment maximum lifetime. | +| `send-window` | `u64` (bytes) | No | `16777216` (16 MiB) | QUIC send window. | +| `receive-window` | `u64` (bytes) | No | `8388608` (8 MiB) | QUIC receive window. | +| `max-udp-relay-packet-size` | `u64` | No | `1500` | Accepted for compatibility (unused in runtime). | +| `tls-cert`, `tls-key` | `string` | No | `None` | Paired mTLS client certificate and private key. | + +## Example + +```yaml +proxies: + - name: tuic-v5 + type: tuic + server: tuic.example.com + port: 8443 + uuid: "00000000-0000-0000-0000-000000000000" + password: "your-tuic-password" + sni: tuic.example.com + alpn: + - h3 + udp-relay-mode: native + congestion-controller: bbr3 + reduce-rtt: true +``` diff --git a/docs/en/config/outbounds/v2ray.md b/docs/en/config/outbounds/v2ray.md new file mode 100644 index 0000000..4a55328 --- /dev/null +++ b/docs/en/config/outbounds/v2ray.md @@ -0,0 +1,132 @@ +# Trojan, VMess & VLESS Outbounds + +All three protocols are built in (no optional Cargo feature required) and support TCP + UDP `connect-via` (`dialer-proxy`) chaining as well as mTLS (`tls-cert` / `tls-key`). + +For transport block details (`ws-opts`, `h2-opts`, `grpc-opts`, `xhttp-opts`, `reality-opts`), see [Common Types & Transports](../types.md#ws-opts). + +--- + +## Trojan (`type: trojan`) + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `server`, `port`, `connect-via` | Common | Yes (except `connect-via`) | — | Standard outbound options. | +| `password` | `string` | Yes | — | Trojan password. | +| `sni` | `string` | No | `server` | TLS SNI. | +| `alpn` | `list[string]` | No | `["http/1.1"]` for `ws`; `["h2", "http/1.1"]` otherwise | TLS ALPN protocols. | +| `skip-cert-verify` | `bool` | No | `false` | Skip TLS certificate verification. | +| `udp` | `bool` | No | `false` | Enable UDP relay. | +| `network` | `"ws"` \| `"grpc"` | No | Native TLS/TCP | Optional underlying transport. | +| `ws-opts` | [`WsOpt`](../types.md#ws-opts) | When `network: ws` | `None` | WebSocket transport options. | +| `grpc-opts` | [`GrpcOpt`](../types.md#grpc-opts) | When `network: grpc` | `None` | gRPC transport options. | +| `tls-cert`, `tls-key` | `string` | No | `None` | Paired mTLS client certificate and private key. | + +```yaml +proxies: + - name: trojan-grpc + type: trojan + server: trojan.example.com + port: 443 + password: "your-password" + sni: trojan.example.com + udp: true + network: grpc + grpc-opts: + grpc-service-name: "trojan-service" +``` + +--- + +## VMess (`type: vmess`) + +| Key | Alias | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | --- | +| `name`, `server`, `port`, `connect-via` | `dialer-proxy` | Common | Yes (except `connect-via`) | — | Standard outbound options. | +| `uuid` | — | `string` | Yes | — | Standard UUID. | +| `alter-id` | `alterId` | `u16` | Yes | — | Use `0` for AEAD. | +| `cipher` | — | `string` | Recommended | `""` | Must be one of `auto`, `aes-128-gcm`, `chacha20-poly1305`, or `none` (case-insensitive). **Leaving it omitted fails at dial time** with `invalid security`; `auto` selects `aes-128-gcm` on `x86_64`/`aarch64`/`s390x` and `chacha20-poly1305` elsewhere. | +| `udp` | — | `bool` | No | `true` | Enable UDP relay. | +| `tls` | — | `bool` | No | `false` | Enable TLS. | +| `skip-cert-verify` | — | `bool` | No | `false` | Skip TLS certificate verification. | +| `server-name` | `servername` | `string` | No | `ws-opts.headers.Host` → `xhttp-opts.host` → `server` | TLS SNI override. | +| `network` | — | `"ws"` \| `"h2"` \| `"grpc"` \| `"xhttp"` \| `"splithttp"` | No | Raw TCP | Transport protocol (when `tls: true`, ALPN defaults to `["http/1.1"]` for `ws` and `["h2"]` for `h2`/`grpc`/`xhttp`/`splithttp`). | +| `ws-opts` | — | [`WsOpt`](../types.md#ws-opts) | When `network: ws` | `None` | WebSocket options. | +| `h2-opts` | — | [`H2Opt`](../types.md#h2-opts) | When `network: h2` | `None` | HTTP/2 options. | +| `grpc-opts` | — | [`GrpcOpt`](../types.md#grpc-opts) | When `network: grpc` | `None` | gRPC options. | +| `xhttp-opts` | `splithttp-opts` | [`XhttpOpt`](../types.md#xhttp-opts) | Optional for `xhttp`/`splithttp` | Default `XhttpOpt` | XHTTP / SplitHTTP options. | +| `tls-cert`, `tls-key` | — | `string` | No | `None` | Paired mTLS client certificate and private key. | + +```yaml +proxies: + - name: vmess-ws-tls + type: vmess + server: vmess.example.com + port: 443 + uuid: "00000000-0000-0000-0000-000000000000" + alterId: 0 + cipher: auto + udp: true + tls: true + servername: vmess.example.com + network: ws + ws-opts: + path: /ws + headers: + Host: vmess.example.com +``` + +--- + +## VLESS (`type: vless`) + +| Key | Alias | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | --- | +| `name`, `server`, `port`, `connect-via` | `dialer-proxy` | Common | Yes (except `connect-via`) | — | Standard outbound options. | +| `uuid` | — | `string` | Yes | — | Standard UUID. | +| `udp` | — | `bool` | No | `true` | Enable UDP relay. | +| `tls` | — | `bool` | No | `false` | Enable standard TLS (overridden by `reality-opts` if present). | +| `skip-cert-verify` | — | `bool` | No | `false` | Skip TLS certificate verification. | +| `server-name` | `servername` | `string` | No | Fallback chain (or `server` for REALITY) | TLS / REALITY SNI. | +| `network` | — | `"tcp"` \| `"ws"` \| `"h2"` \| `"grpc"` \| `"xhttp"` \| `"splithttp"` | No | `"tcp"` | Transport protocol. | +| `ws-opts`, `h2-opts`, `grpc-opts`, `xhttp-opts` (`splithttp-opts`) | — | Transport blocks | Required for `ws`/`h2`/`grpc`; optional for `xhttp` | `None` | Same schema as VMess. | +| `reality-opts` | — | [`RealityOpt`](../types.md#reality-opts) | No | `None` | Enables TLS REALITY (`public-key`, `short-id`). | +| `flow` | — | `string` | No | `None` | Recognizes `"xtls-rprx-vision"` (applied to TCP streams only; UDP does not use Vision). | +| `client-fingerprint` | — | `string` | No | `None` | **Not yet implemented** (uTLS): accepted in YAML but ignored with a warning. | +| `tls-cert`, `tls-key` | — | `string` | No | `None` | Paired mTLS client certificate/key (non-REALITY TLS only). | + +=== "VLESS + REALITY + Vision" + + ```yaml + proxies: + - name: vless-reality + type: vless + server: reality.example.com + port: 443 + uuid: "00000000-0000-0000-0000-000000000000" + udp: true + tls: true + flow: xtls-rprx-vision + servername: www.example.org + reality-opts: + public-key: "REPLACE_WITH_32BYTE_URLSAFE_BASE64_KEY" + short-id: "0123456789abcdef" + ``` + +=== "VLESS + XHTTP" + + ```yaml + proxies: + - name: vless-xhttp + type: vless + server: xhttp.example.com + port: 443 + uuid: "00000000-0000-0000-0000-000000000000" + udp: true + tls: true + servername: xhttp.example.com + network: xhttp + xhttp-opts: + path: /xhttp + host: xhttp.example.com + x-padding-bytes: "100-1000" + ``` diff --git a/docs/en/config/outbounds/vpn.md b/docs/en/config/outbounds/vpn.md new file mode 100644 index 0000000..9f836bd --- /dev/null +++ b/docs/en/config/outbounds/vpn.md @@ -0,0 +1,135 @@ +# WireGuard, SSH, Tailscale & Tor Outbounds + +## WireGuard (`type: wireguard`) + +Userspace WireGuard client implemented with BoringTun. + +- **Feature**: `wireguard` (enabled in `standard` / default builds). +- **`connect-via`**: Ignored at runtime. + +### Fields + +| Key | Alias | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | --- | +| `name`, `server`, `port` | — | Common | Yes | — | Peer endpoint hostname/IP and UDP port. | +| `private-key` | — | `string` | Yes | — | Base64 WireGuard client private key. | +| `public-key` | — | `string` | Yes | — | Base64 peer public key. | +| `pre-shared-key` | `preshared-key` | `string` | No | `None` | Optional Base64 pre-shared key. | +| `ip` | — | IPv4 CIDR | Yes | — | Local tunnel IPv4 CIDR (e.g. `10.0.0.2/32`). | +| `ipv6` | — | IPv6 CIDR | No | `None` | Local tunnel IPv6 CIDR. | +| `mtu` | — | `u16` | No | `1420` | WireGuard tunnel MTU. | +| `udp` | — | `bool` | No | `false` | Enable UDP relay over the tunnel. | +| `remote-dns-resolve` | — | `bool` | No | `false` | Resolve destination domains through `dns` servers over the tunnel. | +| `dns` | — | `list[IP]` | No | `None` | DNS server IPs (port 53) used when `remote-dns-resolve: true`. | +| `allowed-ips` | — | `list[CIDR]` | No | `[]` | Allowed peer CIDRs. | +| `reserved-bits` | — | `list[u8]` | No | `[0, 0, 0]` | 3-byte WireGuard reserved field (first 3 bytes used when length >= 3). | + +```yaml +proxies: + - name: wg-peer + type: wireguard + server: wg.example.com + port: 51820 + ip: 10.66.66.2/32 + ipv6: fd42:42:42::2/128 + private-key: "BASE64_PRIVATE_KEY" + public-key: "BASE64_PEER_PUBLIC_KEY" + mtu: 1280 + udp: true + remote-dns-resolve: true + dns: + - 1.1.1.1 + reserved-bits: [0, 0, 0] +``` + +--- + +## SSH (`type: ssh`) + +- **Feature**: `ssh` (enabled in `standard` / default builds). +- **UDP**: Not supported (`false`). +- **`connect-via`**: TCP supported. + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `server`, `port`, `connect-via` | Common | Yes (except `connect-via`) | — | Standard outbound options. | +| `username` | `string` | Yes | — | SSH login username. | +| `password` | `string` | No | `None` | Password authentication secret. | +| `private-key` | `string` | No | `None` | Inline key (if containing `"PRIVATE KEY"`) or key file path (supports `~` home expansion). | +| `private-key-passphrase` | `string` | No | `None` | Passphrase for encrypted private key. | +| `host-key` | `list[string]` | No | `None` | OpenSSH public key strings to pin the server host key. If empty/omitted, host keys are not verified. | +| `host-key-algorithms` | `list[string]` | No | `None` | Allowed algorithms: `ssh-ed25519` (`ed25519`), `rsa-sha2-256`, `rsa-sha2-512`, `ssh-rsa` (`rsa`), `ecdsa-sha2-nistp256`, `ecdsa-sha2-nistp384`, `ecdsa-sha2-nistp521`. | +| `totp-opt` | map | No | `None` | Keyboard-interactive TOTP configuration:
- `otp-auth: ""` (RFC 6238 defaults), or
- `common: { secret, screw, step, digits, algorithm }` (`algorithm`: `SHA1` \| `SHA256` \| `SHA512`). | + +```yaml +proxies: + - name: ssh-bastion + type: ssh + server: ssh.example.com + port: 22 + username: ops + private-key: ~/.ssh/id_ed25519 + host-key: + - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleKeyData..." + totp-opt: + otp-auth: "JBSWY3DPEHPK3PXP" +``` + +--- + +## Tailscale (`type: tailscale`) + +Integrates directly into a Tailscale tailnet or self-hosted Headscale coordination server as a userspace node. + +- **Feature**: `tailscale` (enabled in `standard` / default builds). +- **UDP**: Always enabled. +- **`connect-via`**: Not supported (does not use `CommonConfigOptions`). + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name` | `string` | Yes | — | Unique proxy name. | +| `auth-key` | `string` | No | `None` | Tailscale / Headscale pre-authentication key. | +| `hostname` | `string` | No | `None` | Requested tailnet hostname. | +| `state-dir` | `string` | No | `None` | Directory for persisting `/tailscale_state.json` (relative to config directory). If unset with `ephemeral: false`, state lives in memory only with a warning. | +| `control-url` | `string` | No | Official Tailscale control plane | Custom coordination server URL (e.g. Headscale). | +| `client-name` | `string` | No | `"clash-rs"` | Client identifier reported to the control server. | +| `ephemeral` | `bool` | No | `false` | Register as an ephemeral node (ignores `state-dir` persistence). | + +```yaml +proxies: + - name: tailnet + type: tailscale + auth-key: "tskey-auth-REPLACE_ME" + hostname: clash-rs-node + state-dir: tailscale-state + control-url: "https://headscale.example.com" + ephemeral: false +``` + +--- + +## Tor (`type: tor`) + +Routes TCP traffic through the embedded Arti Tor client. + +- **Feature**: `onion` (**not** in `standard`; build with `--features plus` or `--features onion`). +- **UDP**: Not supported (`false`). +- **`connect-via`**: Not supported (does not use `CommonConfigOptions`). + +### Fields + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name` | `string` | Yes | — | Unique proxy name. | +| `interface` | `string` | No | `None` | Outbound network interface name (fails on non-Android if the interface is not found). | +| `routing-mark` | [`SocketMark`](../types.md#socketmark) | No | `None` | Linux/Android `SO_MARK`. | + +```yaml +proxies: + - name: tor-exit + type: tor +``` diff --git a/docs/en/config/providers.md b/docs/en/config/providers.md new file mode 100644 index 0000000..6cdcf7a --- /dev/null +++ b/docs/en/config/providers.md @@ -0,0 +1,145 @@ +# Providers (`proxy-providers`, `rule-providers`, `inbound-providers`) + +Providers load proxies, rules, or inbound listeners dynamically from remote HTTP endpoints, local files (with automatic OS filesystem hot-reload watching), or inline definitions. + +All local file and cache `path` values resolve relative to `-d` and are validated against [Safe Paths](../guides/compatibility.md#safe-paths). + +--- + +## Proxy Providers (`proxy-providers`) { #proxy-providers } + +Supports **`http`** and **`file`** types (`inline` is not supported for `proxy-providers`). + +### `type: http` + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `type` | `"http"` | Yes | — | Remote HTTP provider. | +| `url` | `string` | Yes | — | Valid HTTP(S) URL (fetched directly; `proxy` and custom `header` fields are not implemented). | +| `path` | `string` | No | `proxy_providers/.yaml` | Local cache file path (relative to `-d`). | +| `interval` | `u64` (seconds) | No | `86400` (24 hours) | Auto-refresh interval (`0` disables scheduled fetches). | +| `health-check` | object | No | See below | Health-check configuration. | + +### `type: file` + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `type` | `"file"` | Yes | — | Local file provider (auto-reloads on file edits via OS watcher with 50 ms debounce). | +| `path` | `string` | Yes | — | Local YAML path (relative to `-d`). | +| `interval` | `u64` (seconds) | No | `0` (disabled) | Optional polling interval. | +| `health-check` | object | No | See below | Health-check configuration. | + +### `health-check` + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `enable` | `bool` | — | **Important**: ClashRS currently does **not** check `enable`; automatic health checks run whenever `interval != 0`. Set `interval: 0` explicitly to disable automatic checks. | +| `url` | `string` | `"http://www.gstatic.com/generate_204"` | Latency test URL. | +| `interval` | `u64` (seconds) | `300` | Check interval (`0` disables automatic checks). | +| `lazy` | `bool` | `true` | Defer checks until traffic uses the provider. | + +### Provider File Format + +The YAML payload must contain a top-level `proxies:` list (invalid individual entries log a warning and are skipped): + +```yaml title="providers/nodes.yaml" +proxies: + - name: hk-01 + type: ss + server: hk01.example.com + port: 8388 + cipher: aes-256-gcm + password: "password" +``` + +```yaml title="config.yaml" +proxy-providers: + remote-sub: + type: http + url: "https://sub.example.com/proxies.yaml" + path: ./providers/remote-sub.yaml + interval: 3600 + health-check: + enable: true + url: http://www.gstatic.com/generate_204 + interval: 300 + lazy: true + + local-nodes: + type: file + path: ./providers/nodes.yaml + health-check: + interval: 0 +``` + +!!! note "Unsupported Mihomo `proxy-providers` Fields" + `proxy`, `header`, `filter`, `exclude-filter`, `exclude-type`, `override`, `payload`, `size-limit`, `dialer-proxy`, `health-check.expected-status`, and `health-check.timeout` are not defined. + +--- + +## Rule Providers (`rule-providers`) { #rule-providers } + +Supports **`http`**, **`file`**, and **`inline`** types; initialized asynchronously in the background. + +### Behaviors & Formats + +- **`behavior`** (required): + - `domain` — compiled into a compact `DomainSet` supporting exact domains, `*.example.com` (single-level wildcard), `.example.com` (subdomains only), and `+.example.com` (domain and all subdomains). + - `ipcidr` — compiled into a `CidrTrie` of IPv4/IPv6 CIDRs. + - `classical` — targetless routing rules (`TYPE,PAYLOAD[,OPTIONS]`, nested `RULE-SET` forbidden), with fast indexes for `DOMAIN`, `DOMAIN-SUFFIX`, `DOMAIN-KEYWORD`, and `IP-CIDR` (without `no-resolve`). +- **`format`** (optional, default `yaml`): + - `yaml` — YAML object with a `payload: [...]` list. + - `text` — line-delimited plain text (ignores blank lines and `#` / `//` comments). + - `mrs` — Mihomo Rule Set binary v1 (Zstandard compressed, `MRS\x01`); **supported for `domain` and `ipcidr` only** (`classical` returns an error). + +### Fields by Type + +| Type | Required Keys | Optional Keys & Defaults | +| --- | --- | --- | +| `http` | `type: http`, `url`, `behavior` | `interval` (`0`), `path` (`rules/`), `format` (`yaml`), `inline-rules` / `payload` (merged for `yaml`/`text`) | +| `file` | `type: file`, `path`, `behavior` | `interval` (`None`; uses OS file watcher), `format` (`yaml`), `inline-rules` / `payload` (merged for `yaml`/`text`) | +| `inline` | `type: inline`, `behavior`, `inline-rules` (alias `payload`) | `path` (`rules/`, unused at runtime) | + +```yaml +rule-providers: + ad-domains: + type: http + behavior: domain + format: mrs + url: "https://rules.example.com/ads.mrs" + path: ./rules/ads.mrs + interval: 86400 + + lan-cidrs: + type: file + behavior: ipcidr + format: text + path: ./rules/lan.txt + + custom-inline: + type: inline + behavior: classical + payload: + - DOMAIN-SUFFIX,internal.example.com + - IP-CIDR,198.51.100.0/24,no-resolve +``` + +--- + +## Inbound Providers (`inbound-providers`) { #inbound-providers } + +Dynamically loads additional [`listeners`](inbounds/index.md) from a local YAML file or remote HTTP endpoint. The payload must contain a top-level `listeners:` list. + +| Type | Required Keys | Optional Keys & Defaults | +| --- | --- | --- | +| `http` | `type: http`, `url` | `interval` (`86400` seconds), `path` (`inbound_providers/.yaml`) | +| `file` | `type: file`, `path` | `interval` (`0`, disables polling; uses file watcher) | + +For `shadowsocks`, `anytls`, and `hysteria2` listeners, updating `users` inside an inbound provider refreshes user credentials in place without closing the listening socket. + +```yaml +inbound-providers: + server-users: + type: file + path: ./inbounds/users.yaml +``` diff --git a/docs/en/config/proxy-groups.md b/docs/en/config/proxy-groups.md new file mode 100644 index 0000000..e3dbe4a --- /dev/null +++ b/docs/en/config/proxy-groups.md @@ -0,0 +1,164 @@ +# Proxy Groups (`proxy-groups`) + +Proxy groups combine individual outbound proxies and [`proxy-providers`](providers.md#proxy-providers) under selection, health-checking, failover, load-balancing, chaining, or adaptive-scoring strategies. + +## Common Rules + +- Group names must be globally unique and cannot be `DIRECT` or `REJECT`. +- Every group must reference at least one proxy via `proxies` and/or `use`. +- Nested group references are allowed; ClashRS topologically sorts groups via DAG validation and rejects cycles. +- A built-in **`GLOBAL`** group (`type: select`, `udp: true`) is created automatically containing all static proxies, groups, and `proxy-providers`. +- `interval` on `url-test`, `fallback`, and `load-balance` accepts either an integer or numeric string (seconds); `0` disables automatic periodic checks. + +!!! note "Unsupported Mihomo Proxy Group Keys" + `filter`, `exclude-filter`, `exclude-type`, `hidden`, `include-all`, `include-all-proxies`, `include-all-providers`, `disable-udp`, `expected-status`, `timeout`, `max-failed-times`, `interface-name`, and `routing-mark` are not defined on proxy groups in ClashRS (silently ignored unless `--strict-config` is used). + +--- + +## Supported Group Types (6 Types) + +### 1. `select` + +Manual selection via Web Dashboard or `PUT /proxies/{name}`. Defaults to the first entry and restores the last selection when `profile.store-selected: true` (default). + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name` | `string` | Yes | — | Group name. | +| `type` | `"select"` | Yes | — | Group type. | +| `proxies` | `list[string]` | At least one of `proxies` / `use` | `None` | Static proxy or group names. | +| `use` | `list[string]` | At least one of `proxies` / `use` | `None` | `proxy-providers` names. | +| `udp` | `bool` | No | `true` | Delegates `support_udp()` to selected proxy when `true`; forces `false` otherwise. | +| `url` | `string` | No | `http://www.gstatic.com/generate_204` | URL used only for manual latency tests. | +| `icon` | `string` | No | `None` | Icon URL/string exposed to dashboards via REST API. | + +--- + +### 2. `url-test` + +Automatically selects the lowest-latency alive proxy based on periodic HTTP health checks. + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name` | `string` | Yes | — | Group name. | +| `type` | `"url-test"` | Yes | — | Group type. | +| `proxies` / `use` | `list[string]` | At least one | `None` | Member proxies / providers. | +| `url` | `string` | **Yes** | — | Health-check URL (e.g. `http://www.gstatic.com/generate_204`). | +| `interval` | `u64` (seconds) | **Yes** | — | Periodic check interval (`0` disables automatic checks). | +| `tolerance` | `u16` (ms) | No | `0` | Latency difference threshold before switching proxies. | +| `lazy` | `bool` | No | `false` | Defer checks until the group is actively used. | +| `icon` | `string` | No | `None` | Dashboard icon. | + +**Advanced runtime behaviors**: + +- **Manual pin/override**: Supports `PUT /proxies/{name}` with `{"name": ""}` to pin a specific member; send `""` (or `"auto"` / `"default"` if no node has that name) to return to automatic selection. +- **Passive circuit breaker**: 3 consecutive connection failures within 60 seconds trip a 30-second cooldown, steering traffic around failing nodes. +- **High-throughput switch guard**: Skips routine latency-based switches while global throughput exceeds 250 KB/s (unless the current node fails or trips). +- **Adaptive tolerance**: After 12 consecutive checks without switching where average latency differs by > 20 ms, temporarily lowers effective tolerance to 20 ms until a switch occurs. + +--- + +### 3. `fallback` + +Selects the first alive proxy in list order; falls back to the first proxy if all checks fail. + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `type`, `proxies`, `use`, `icon` | Same as above | — | — | `type: fallback`. | +| `url` | `string` | **Yes** | — | Health-check URL. | +| `interval` | `u64` (seconds) | **Yes** | — | Check interval. | +| `lazy` | `bool` | No | `false` | Defer checks until traffic arrives. | + +--- + +### 4. `load-balance` + +Distributes connections across alive proxies. + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name`, `type`, `proxies`, `use`, `icon` | Same as above | — | — | `type: load-balance`. | +| `url` | `string` | **Yes** | — | Health-check URL. | +| `interval` | `u64` (seconds) | **Yes** | — | Check interval. | +| `lazy` | `bool` | No | `false` | Defer checks until traffic arrives. | +| `strategy` | `"consistent-hashing"` \| `"round-robin"` \| `"sticky-session"` | No | `"consistent-hashing"` | Distribution strategy. | + +!!! note "Current Runtime Caveats" + - Although all three `strategy` values are parsed, the current outbound manager instantiation always applies the default **`consistent-hashing`** strategy (Murmur3 + jump hash by eTLD+1 domain or destination IP). + - `load-balance` currently reports `support_udp() == false`. + +--- + +### 5. `relay` + +Chains proxies in order (`proxies[0] -> proxies[1] -> ... -> destination`) for multi-hop TCP and UDP forwarding. + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name` | `string` | Yes | — | Group name. | +| `type` | `"relay"` | Yes | — | Group type. | +| `proxies` / `use` | `list[string]` | At least one | `None` | Ordered hop list. | +| `url` | `string` | No | `http://www.gstatic.com/generate_204` | Manual latency test URL. | +| `icon` | `string` | No | `None` | Dashboard icon. | + +--- + +### 6. `smart` + +Adaptive scoring group that ranks proxies using historical latency, success rate, trend, stability, packet loss, RTT, and failure penalties. Supports exponential-backoff retries on TCP (100 ms up to 5 s); UDP selects the top-ranked node directly. Statistics persist every 30 seconds when `profile.store-smart-stats: true`. + +| Key | Type | Required | Default | Description | +| --- | --- | --- | --- | --- | +| `name` | `string` | Yes | — | Group name. | +| `type` | `"smart"` | Yes | — | Group type. | +| `proxies` / `use` | `list[string]` | At least one | `None` | Member proxies / providers. | +| `udp` | `bool` | No | `true` | Enable UDP support. | +| `lazy` | `bool` | No | `false` | Lazy evaluation flag. | +| `url` | `string` | No | `None` | Optional test URL. | +| `max-retries` | `u32` | No | Adaptive (`2..=6`, initial `3`) | Max TCP retry attempts; when omitted or `0`, computed adaptively from average success rate. | +| `bandwidth-weight` | `f64` | No | `0.0` (disabled) | When `> 0.0`, adds `delay * 0.1 * bandwidth-weight` to node scoring. | +| `site-stickiness` | `f64` | No | `None` | Parsed for compatibility (not yet wired into runtime options). | +| `icon` | `string` | No | `None` | Dashboard icon. | + +## Example + +```yaml +proxy-groups: + - name: PROXY + type: select + proxies: + - AUTO + - SMART + - FALLBACK + - DIRECT + + - name: AUTO + type: url-test + use: + - sub-provider + url: http://www.gstatic.com/generate_204 + interval: 300 + tolerance: 50 + + - name: SMART + type: smart + use: + - sub-provider + udp: true + max-retries: 3 + bandwidth-weight: 0.2 + + - name: FALLBACK + type: fallback + proxies: + - node-a + - node-b + - DIRECT + url: http://www.gstatic.com/generate_204 + interval: 300 + + - name: CHAIN + type: relay + proxies: + - entry-node + - exit-node +``` diff --git a/docs/en/config/rules.md b/docs/en/config/rules.md new file mode 100644 index 0000000..028ee18 --- /dev/null +++ b/docs/en/config/rules.md @@ -0,0 +1,85 @@ +# Routing Rules (`rules`) + +When `mode: rule` (default), ClashRS evaluates `rules` from top to bottom and routes each session to the target of the first matching rule. If no rule matches (for example when `MATCH` is omitted), traffic falls back to `DIRECT`. + +## Syntax + +```text +TYPE,PAYLOAD,TARGET[,OPTIONS...] +MATCH,TARGET[,OPTIONS...] +``` + +- Built-in targets: **`DIRECT`** and **`REJECT`** (plus any defined proxy or proxy group name). +- `REJECT-DROP`, `PASS`, and `COMPATIBLE` are **not** defined. +- `sub-rules` and `script` are **not** supported. + +## Supported Rule Types (18 Types) + +| Rule Type | Aliases | Payload & Matching Semantics | Triggers DNS Resolution? | +| --- | --- | --- | --- | +| `DOMAIN` | — | Exact domain match (ASCII case-insensitive; returns `false` for IP targets). | No | +| `DOMAIN-SUFFIX` | — | Matches the domain itself or any `.suffix` subdomain (case-insensitive; `google.com` will not match `fakegoogle.com`). | No | +| `DOMAIN-KEYWORD` | — | Case-insensitive substring match against the domain. | No | +| `DOMAIN-REGEX` | — | Rust `regex` match against the domain (case-insensitive by default). | No | +| `GEOSITE` | — | Matches a category from `geosite` database. Supports `!code` negation and `code@attr` attribute filtering (case-insensitive). | No | +| `GEOIP` | — | Matches ISO 3166-1 alpha-2 country code (e.g. `CN`) from `mmdb`. No special built-in `PRIVATE` override—relies on MMDB data. | Yes (unless `no-resolve`) | +| `IP-CIDR` | `IP-CIDR6` | Matches destination IPv4 or IPv6 CIDR (both names accept IPv4 and IPv6). | Yes (unless `no-resolve`) | +| `SRC-IP-CIDR` | — | Matches client source IP CIDR (`sess.source.ip()`). | No | +| `SRC-PORT` | `SRC-PORT-RANGE` | Source port(s): single port (`80`), range (`8000-8080` or `8000:8080`), or `/`-separated combinations (`80/443/8000-8080`). | No | +| `DST-PORT` | `DST-PORT-RANGE`, `PORT-RANGE` | Destination port(s); same syntax as `SRC-PORT`. | No | +| `IN-TYPE` | — | Case-insensitive inbound type: `HTTP`, `HTTPCONNECT`/`HTTP-CONNECT`, `SOCKS`/`SOCKS5`, `TUN`, `TPROXY`, `REDIR`, `TUNNEL`, `SHADOWSOCKS`/`SS`, `ANYTLS`, `HYSTERIA2`/`HY2`, `IGNORE`/`INNER`. | No | +| `IN-USER` | — | Exact match on authenticated inbound username (`sess.inbound_user`, e.g. from SS2022/AnyTLS/Hysteria2 multi-user listeners). Non-empty payload required. | No | +| `PROCESS-NAME` | — | Exact match on local process name (`Linux`, `macOS`, `Windows`; always `false` elsewhere). | No | +| `PROCESS-PATH` | — | Substring match against process name/path (`Linux`, `macOS`, `Windows`). | No | +| `NETWORK` | — | Transport protocol: `TCP`/`tcp` or `UDP`/`udp`. | No | +| `RULE-SET` | — | References a provider defined in [`rule-providers`](providers.md#rule-providers). | `domain`: No; `ipcidr`/`classical`: Yes unless `no-resolve` | +| `AND` / `OR` / `NOT` | — | Arbitrarily nested logical combinators (see below). | Yes if any leaf requires DNS | +| `MATCH` | — | Catch-all rule (`MATCH,TARGET[,interface=]`). | No | + +!!! warning "Unsupported Rule Types" + The following rule types are **not** supported and fail config loading with `unsupported rule type`: + `DOMAIN-WILDCARD`, `IN-PORT`, `IN-NAME`, `IN-IP`, `PROCESS-NAME-REGEX`, `PROCESS-PATH-REGEX`, `UID`, `DSCP`, `IP-ASN`, `IP-SUFFIX`, `SRC-GEOIP`, `SRC-IP-ASN`, `SRC-IP-SUFFIX`, `SUB-RULE`, `SCRIPT`, `FINAL` (use `MATCH`). + +## Rule Modifiers (Options) + +ClashRS strictly validates options—unknown or duplicate modifiers cause a config error. Exactly **2** modifiers are supported: + +1. **`no-resolve`** + - Skips DNS resolution for domain targets before evaluating IP-based rules. + - Allowed only on `GEOIP`, `IP-CIDR`, `IP-CIDR6`, `SRC-IP-CIDR`, and `RULE-SET`. +2. **`interface=`** + - Allowed on any top-level rule (including `MATCH` and `AND`/`OR`/`NOT`, but **not** on inner sub-expressions of logical rules). + - Binds the matched session's outbound socket to the named network interface (logs a warning and falls back to default if the interface is not found). + +## Logical Combinators (`AND`, `OR`, `NOT`) + +Sub-rules omit the target (they may still include `no-resolve`, but `interface=` must be placed on the outermost rule): + +```yaml +rules: + - AND,((NETWORK,UDP),(DST-PORT,443)),REJECT + - OR,((DOMAIN-SUFFIX,example.com),(IP-CIDR,192.0.2.0/24,no-resolve)),PROXY + - NOT,((GEOIP,CN,no-resolve)),PROXY + - AND,((IN-USER,alice),(GEOSITE,cn)),DIRECT,interface=eth0 +``` + +- `NOT` must contain **exactly 1** sub-expression. +- If a malformed compound rule fails to construct, ClashRS logs an error and falls back to `MATCH,REJECT` for safety. + +## Example + +```yaml +rules: + - IN-USER,vip-user,PROXY + - PROCESS-NAME,curl,DIRECT + - RULE-SET,private-domains,DIRECT + - DOMAIN-SUFFIX,example.com,PROXY + - DOMAIN-REGEX,^ad[0-9]+\.example\.net$,REJECT + - GEOSITE,cn,DIRECT + - GEOSITE,geolocation-!cn,PROXY + - IP-CIDR,127.0.0.0/8,DIRECT,no-resolve + - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve + - GEOIP,CN,DIRECT,no-resolve + - AND,((NETWORK,UDP),(DST-PORT,443)),REJECT + - MATCH,PROXY +``` diff --git a/docs/en/config/tun.md b/docs/en/config/tun.md new file mode 100644 index 0000000..4ef3754 --- /dev/null +++ b/docs/en/config/tun.md @@ -0,0 +1,136 @@ +# TUN Transparent Proxy + +ClashRS provides a built-in userspace network stack (`smoltcp` / `watfaq_netstack`) for L3 TUN transparent proxying across Windows, Linux, macOS, FreeBSD, Android, and iOS. + +Requires the `tun` Cargo feature (enabled in `standard` / default builds). + +## Native Mode vs. Mihomo-Compatible Mode + +ClashRS automatically enters **Mihomo-compatible TUN translation** whenever any of the following fields is set: + +- `stack`, `dns-mode`, `auto-detect-interface`, or `auto-route` is present +- `strict-route: true` +- `route-address` or `route-exclude-address` is non-empty + +When Mihomo-compatible mode is active, defaults adjust automatically: + +| Field | Native Default | Mihomo-Mode Default | +| --- | --- | --- | +| `gateway` | `198.18.0.1/24` | Address from `dns.fake-ip-range` with `/30` prefix (e.g. `198.18.0.1/30`) | +| `gateway-v6` | `None` | `fdfe:dcba:9876::1/126` when top-level `ipv6: true` | +| `auto-route` | `None` (uses `route-all`) | `true` | +| `auto-detect-interface` | `None` | `true` | +| `dns-hijack` | Disabled | `["any:53"]` (+ TUN subnet DNS host) | +| `dns-mode` | `None` | `""` (`Auto`: `hijack` when `auto-route && !macos`, else `disabled`) | + +## All `tun` Fields + +| Key | Alias | Type | Default | Description | +| --- | --- | --- | --- | --- | +| `enable` | — | `bool` | `false` | Enable the TUN inbound. | +| `device-id` | `device-url`, `device` | `string` | `"utun1989"` | Device specifier: `fd://` (Unix pre-opened fd), `dev://` (Windows also supports `dev://NAME?guid=`), or bare ``. | +| `stack` | — | `mips` \| `system` \| `gvisor` \| `mixed` | `None` | Mihomo compatibility field. All values use the same native Rust `watfaq_netstack` stack. | +| `dns-mode` | — | `""` (`Auto`) \| `disabled` \| `native` \| `hijack` | `None` (`Auto` in Mihomo mode) | Controls TUN adapter DNS setup and WFP DNS blocking (especially on Windows). | +| `auto-detect-interface` | — | `bool` | `None` (`true` in Mihomo mode) | Auto-detect default physical outbound interface when top-level `interface` is unset. On Windows, `true` dynamically tracks default route changes (1s cache). | +| `strict-route` | — | `bool` | `false` | Strict anti-leak routing (effective only when `auto-route` resolves to `true`). Currently implemented via Windows Filtering Platform (WFP). | +| `auto-redirect` | — | `bool` | `false` | Mihomo compatibility field. **Setting `auto-redirect: true` on Linux returns an `InvalidConfig` error** (ClashRS has no Linux redirect backend). Accepted and ignored on other platforms. | +| `exclude-interface` | — | `list[string]` | `[]` | **Windows-only compiled field** accepted for shared-profile compatibility (no-op). Not defined on non-Windows platforms. | +| `gateway` | — | IPv4 CIDR | `198.18.0.1/24` (or `/30` in Mihomo mode) | TUN IPv4 address and subnet. | +| `gateway-v6` | — | IPv6 CIDR | `None` (`fdfe:dcba:9876::1/126` in Mihomo mode + `ipv6: true`) | TUN IPv6 address and subnet (setting this enables TUN IPv6). | +| `routes` | — | `list[CIDR]` | `None` | Custom routes installed in native mode. | +| `route-all` | — | `bool` | `false` | Route all traffic through TUN in native mode. | +| `auto-route` | — | `bool` | `None` (`true` in Mihomo mode) | Mihomo-style automatic route installation. Falls back to `route-all` when unset. | +| `route-address` | — | `list[CIDR]` | `[]` | Subnets routed into TUN (requires `auto-route: true`). Defaults to `0.0.0.0/0` (and `::/0` with IPv6) when empty and `route-exclude-address` is set. | +| `route-exclude-address` | — | `list[CIDR]` | `[]` | Subnets carved out from `route-address` / full routes (requires `auto-route: true`). | +| `mtu` | — | `u16` | `65535` (Windows), `1500` (other platforms) | TUN interface MTU. | +| `so-mark` | — | [`SocketMark`](types.md#socketmark) | Inherits top-level `routing-mark` | Linux/Android `SO_MARK` for policy-routing loop avoidance. | +| `route-table` | — | `u32` | `2468` | Linux policy routing table ID; bypass FIB number on FreeBSD. | +| `dns-hijack` | — | `bool` or `list[string]` | Disabled (native) / `["any:53"]` (Mihomo) | DNS interception rules inside TUN. See below. | + +### `dns-hijack` Formats + +- **Boolean (`true` / `false`)**: `true` intercepts **UDP port 53 only** (not TCP 53). +- **List (e.g. `["any:53", "tcp://1.1.1.1:53"]`)**: Strips any optional `scheme://` prefix and matches **both TCP and UDP**. Accepts `any:` or `IP:port` (bracketed `[::1]:53` for IPv6). ClashRS also automatically appends the TUN subnet DNS host address (e.g. `198.18.0.2:53`). + +!!! note "Unsupported Mihomo TUN Keys" + `inet4-address` and `inet6-address` are not defined — use `gateway` and `gateway-v6` instead. `endpoint-independent-nat`, `gso`, `udp-timeout`, `include-uid`, `exclude-uid`, `include-package`, and `exclude-package` are also not defined. + +## Platform Notes + +=== "Windows" + + - Run as **Administrator**. + - Uses **Wintun**: place matching `wintun.dll` beside `clash-rs.exe`, or compile with `--features wintun-embed` (MSVC). + - Default MTU is `65535`. Adapter GUID can be pinned with `dev://ClashRS?guid=` (otherwise deterministically derived via UUIDv5 from the adapter name). + - Full routing installs split `/1` routes (`0.0.0.0/1`, `128.0.0.0/1`, plus `::/1` and `8000::/1` when IPv6 is enabled). + - With `strict-route: true` and `auto-route: true`, ClashRS installs session-scoped **WFP (Windows Filtering Platform)** filters that permit ClashRS and TUN traffic, block non-TUN port 53 when `dns-mode` resolves to `hijack`, and block non-TUN IPv6 (while preserving `::1` and ICMPv6 NDP) if `gateway-v6` is disabled. + +=== "Linux" + + - Requires root or `CAP_NET_ADMIN` and the `ip` (`iproute2`) command. + - Full routing uses policy routing with `route-table` (default `2468`) and `so-mark` (e.g. `ip rule add not fwmark table 2468`). + - Attempts `IFF_VNET_HDR` TUN offload (TSO/USO) on newly created devices and falls back cleanly if unsupported. + - **`auto-redirect: true` is rejected with an error.** + +=== "macOS" + + - Named devices **must start with `utun`** (e.g. `utun1989`). + - Full routing installs `/1` routes plus `-ifscope ` bypass routes to prevent loops. + - `dns-mode: auto` resolves to `disabled` on macOS (system DNS is not automatically rewritten). + +=== "FreeBSD" + + - Uses multiple FIBs (`setfib(2)` + `net.fibs`): FIB 0 routes through TUN while the ClashRS process moves into the bypass FIB (`route-table`). State is saved to a temp state file for crash recovery. + +=== "Android & iOS" + + - **Only `fd://` is supported** (passing a named device fails). + - Routes are managed by the host VPN service (`VpnService` / `NEPacketTunnelProvider`). + - In `--service-mode`, `fd://` is disallowed. + +## Examples + +=== "Mihomo-Style (Recommended for Desktop)" + + ```yaml + ipv6: true + + dns: + enable: true + ipv6: true + enhanced-mode: fake-ip + fake-ip-range: 198.18.0.1/16 + default-nameserver: + - 223.5.5.5 + - 8.8.8.8 + nameserver: + - https://1.1.1.1/dns-query + + tun: + enable: true + stack: mixed + auto-route: true + auto-detect-interface: true + strict-route: true + dns-hijack: + - any:53 + route-exclude-address: + - 192.168.0.0/16 + - 10.0.0.0/8 + ``` + +=== "Native Linux Gateway Style" + + ```yaml + routing-mark: 6666 + + tun: + enable: true + device-id: "dev://utun1989" + gateway: 198.18.0.1/24 + route-all: true + route-table: 2468 + so-mark: 6666 + dns-hijack: + - any:53 + ``` diff --git a/docs/en/config/types.md b/docs/en/config/types.md new file mode 100644 index 0000000..664af19 --- /dev/null +++ b/docs/en/config/types.md @@ -0,0 +1,106 @@ +# Common Types & Transports + +This page documents reusable scalar types, certificate formats, and transport blocks shared across multiple sections of a ClashRS configuration. + +## Scalar Types + +### `BindAddress` { #bindaddress } + +Used by top-level `bind-address` and `listeners[].listen`. Accepted forms: + +| Value | Parsed IP | Notes | +| --- | --- | --- | +| `"*"` | `0.0.0.0` | All IPv4 interfaces | +| `"localhost"` | `127.0.0.1` | IPv4 loopback | +| `"::"` or `"[::]"` | `::` | Dual-stack / all IPv6 interfaces | +| `"127.0.0.1"`, `"192.168.1.10"`, `"::1"` | Exact IP literal | Any valid IPv4 or IPv6 address | + +### `Port` { #port } + +Used by top-level port shortcuts (`port`, `socks-port`, `mixed-port`, `redir-port`, `tproxy-port`). Accepts either a YAML integer (`7890`) or a numeric string (`"7890"`) in the `u16` range (`0..=65535`). + +!!! note + Inside `listeners[]` and `proxies[]`, `port` must be a YAML integer (`u16`). + +### `SocketMark` { #socketmark } + +Unsigned 32-bit integer (`u32`) applied via `SO_MARK` on Linux (and Android builds with the `tproxy` feature). Ignored on other platforms. + +- **Linux**: Directly sets `SO_MARK` (`0` clears the mark). +- **Android (`socket_mark`)**: Validated against mask `0x7ce0_0000` (bits 21–23 and 26–30 only) and bitwise-ORed onto the existing socket mark. + +### `SocksAddr` { #socksaddr } + +Target address in `host:port` format (e.g. `example.com:443`, `192.0.2.53:53`, `[2001:db8::1]:443`), where `port` must be non-zero. Used by `tunnels`, `listeners` (`type: tunnel`), and the `/providers/rules/{name}/match` API. + +## TLS Certificates (`tls-cert` / `tls-key` / `certificate` / `private-key`) { #tls-certificates } + +Where ClashRS accepts PEM certificates or private keys (outbound mTLS `tls-cert`/`tls-key`, inbound `anytls`/`hysteria2` `certificate`/`private-key`, `naive` `ca-cert`), you may pass either: + +1. **A file path** (relative to `-d`, validated by `SafePaths`), or +2. **Inline PEM text** containing `-----BEGIN` (for example using a YAML block scalar `|`). + +```yaml +tls-cert: | + -----BEGIN CERTIFICATE----- + ... + -----END CERTIFICATE----- +tls-key: | + -----BEGIN PRIVATE KEY----- + ... + -----END PRIVATE KEY----- +``` + +!!! warning "Paired Requirement" + `tls-cert` and `tls-key` (and inbound `certificate` and `private-key`) must **both** be set or **both** be omitted; specifying only one causes a configuration error. + +## Shared Outbound Transport Blocks + +### `ws-opts` { #ws-opts } + +Used by `trojan`, `vmess`, and `vless` when `network: ws` (required when `network: ws`). + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `path` | `string` | `""` | HTTP upgrade path (e.g. `"/ws"`). | +| `headers` | `map[string -> string]` | `{}` | Extra HTTP headers (commonly `Host`). | +| `max-early-data` | `i32` | `0` | Enables WebSocket 0-RTT early data when `> 0`. | +| `early-data-header-name` | `string` | `""` | Header carrying early data (e.g. `"Sec-WebSocket-Protocol"`). | + +### `h2-opts` { #h2-opts } + +Used by `vmess` and `vless` when `network: h2` (required when `network: h2`). + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `host` | `list[string]` | `[server]` | List of HTTP/2 `:authority` hosts. | +| `path` | `string` | `""` | HTTP/2 request path (e.g. `"/h2"`). | + +### `grpc-opts` { #grpc-opts } + +Used by `trojan`, `vmess`, and `vless` when `network: grpc` (required when `network: grpc`). + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `grpc-service-name` | `string` | `""` | gRPC service name (sent as path `"/{grpc-service-name}"`). | + +### `xhttp-opts` (alias `splithttp-opts`) { #xhttp-opts } + +Used by `vmess` and `vless` when `network: xhttp` or `network: splithttp` (optional; defaults apply if omitted). + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `path` | `string` | `"/"` | Request path (leading/trailing `/` normalized while preserving `?query`). | +| `host` | `string` | `headers.Host` or `server` | Request host header. | +| `mode` | `string` | `"auto"` | Accepted for compatibility; ClashRS currently always streams over HTTP/2 POST. | +| `headers` | `map[string -> string]` | `{}` | Extra headers (`Host` and `Referer` are managed internally). | +| `x-padding-bytes` | `string` | Random `100..=1000` bytes in `Referer` query | Padding rule: `"0"` or `"0-0"` disables padding; accepts `"min-max"`, a fixed integer, or a literal string (also sends `X-Padding` header when explicitly set). | + +### `reality-opts` { #reality-opts } + +Used exclusively by `vless` to enable TLS REALITY (takes precedence over plain `tls: true`). + +| Key | Type | Required | Description | +| --- | --- | --- | --- | +| `public-key` | `string` | Yes | URL-safe unpadded Base64-encoded 32-byte X25519 public key. | +| `short-id` | `string` | Yes | Hexadecimal short ID (may be empty `""`). | diff --git a/docs/en/guides/api.md b/docs/en/guides/api.md new file mode 100644 index 0000000..3687384 --- /dev/null +++ b/docs/en/guides/api.md @@ -0,0 +1,119 @@ +# REST API & External Controller + +ClashRS exposes a Clash-compatible HTTP/WebSocket control API over TCP and/or local IPC (Unix Domain Socket on Unix, Named Pipe on Windows). + +## Transports, Authentication & Security + +### TCP Listener (`external-controller`) + +- A leading colon such as `:9090` expands to `127.0.0.1:9090`. +- **Non-loopback safety enforcement**: Binding to any non-loopback address (e.g. `0.0.0.0:9090`) **requires both** a non-empty `secret` and explicit CORS origins (`external-controller-cors` or `cors-allow-origins`), or startup fails. +- **Authentication**: When `secret` is non-empty, send `Authorization: Bearer ` on HTTP requests, or `?token=` on WebSocket upgrades. `/ui`, `/ui/*`, and CORS preflight `OPTIONS` requests (with an `Origin` header) are exempt. +- **CORS**: Allows `GET`, `POST`, `PUT`, and `PATCH` (note: `DELETE` is not currently included in the CORS allow-methods list), headers `Authorization` and `Content-Type`, and `allow-private-network: true` by default. + +### IPC Listener (`external-controller-ipc` / `--controller-ipc`) + +- **Unix**: Unix Domain Socket (parent directory created automatically; stale socket file removed before bind). +- **Windows**: Named Pipe (e.g. `\\.\pipe\clash-rs`), secured by Windows SDDL (`--controller-pipe-sddl` or `LISTEN_NAMEDPIPE_SDDL`; defaults to `D:(A;;GRGW;;;BU)(A;;GRGW;;;SY)`). +- **No bearer-token auth**: IPC relies on OS filesystem/pipe ACLs rather than `secret`. +- Can run simultaneously alongside the TCP listener. + +### Automatic WebSocket Path Rewriting + +Any request carrying WebSocket upgrade headers (`Connection: upgrade` and `Upgrade: websocket`) for a path not starting with `/ws` is automatically rewritten internally to `/ws` (preserving query parameters). Both `/connections` and `/ws/connections` work seamlessly for WebSocket clients. + +--- + +## Endpoints Reference + +### System & Dashboard + +| Method | Path | Description | +| --- | --- | --- | +| `GET` | `/` | Health check; returns `{"hello": "clash-rs"}`. | +| `GET` | `/version` | Returns `{"version": "", "meta": false}` (and optional `commit` when non-empty). | +| `POST` | `/restart` | Restarts the process after 1 second (preserves CLI args & env). Returns `{"status": "ok"}`. **Returns `409 Conflict` in `--service-mode`.** | +| `GET` | `/ui`, `/ui/`, `/ui/{*path}` | Serves `external-ui` static files or falls back to the embedded dashboard (`dashboard` feature). No auth required. | + +### Configuration & GeoData + +| Method | Path | Description | +| --- | --- | --- | +| `GET` | `/configs` | Returns current runtime summary (`port`, `socks-port`, `redir-port`, `tproxy-port`, `mixed-port`, `bind-address`, `mode`, `log-level`, `ipv6`, `unified-delay`, `allow-lan`, `listeners`, `lan-ips`, `dns-listen`). | +| `PUT` | `/configs` | Full configuration reload. JSON body `{"path"?: string, "payload"?: string}`: uses `payload` YAML directly if given, else loads `path` (validated by `SafePaths`), else reloads the startup config file. Returns `204 No Content`. | +| `PATCH` | `/configs` | Runtime partial update for `port`, `socks-port`, `redir-port`, `tproxy-port`, `mixed-port`, `bind-address`, `mode`, `log-level`, `ipv6`, `unified-delay`, `allow-lan`. Listener port/bind changes restart listeners. Returns `202 Accepted`. | +| `POST` | `/configs/geo` | Updates GeoData databases (Country MMDB, ASN MMDB, GeoSite; 60s timeout, atomic write with rollback) and flushes DNS cache. Returns `204 No Content`. | +| `POST` | `/upgrade/geo` | Mihomo-compatible alias for `POST /configs/geo`. | + +### Proxies & Proxy Groups + +| Method | Path | Description | +| --- | --- | --- | +| `GET` | `/proxies` | Lists all proxies and proxy groups (`{"proxies": {...}}`). | +| `GET` | `/proxies/{name}` | Details for a single proxy or group (`404` if missing). | +| `PUT` | `/proxies/{name}` | Selects an item in a `select` group (or pins/unpins a `url-test` group). Body: `{"name": ""}`. Persists when `profile.store-selected: true`. Returns `202 Accepted`. | +| `GET` | `/proxies/{name}/delay` | Latency test for a proxy or group. Required query params: `?url=&timeout=`. Returns `{"delay": , "overall": }`. | +| `GET` | `/group` | Lists all proxy groups (`{"proxies": [...]}`). | +| `GET` | `/group/{name}` | Details for a single proxy group (`404` if not a group). | +| `GET` | `/group/{name}/delay` | Tests all members in a group. Required query params: `?url=&timeout=`. Returns `{"": }`. | + +### Providers + +| Method | Path | Description | +| --- | --- | --- | +| `GET` | `/providers/proxies` | Lists all proxy providers (`{"providers": {...}}`). | +| `GET` | `/providers/proxies/{provider}` | Single proxy provider details. | +| `PUT` | `/providers/proxies/{provider}` | Triggers refresh of the proxy provider (`202 Accepted`). | +| `GET` | `/providers/proxies/{provider}/healthcheck` | Triggers health check for the provider (`202 Accepted`). | +| `GET` | `/providers/proxies/{provider}/{proxy}` | Details for a specific proxy inside a provider. | +| `GET` | `/providers/proxies/{provider}/{proxy}/healthcheck` | Tests latency of a specific proxy inside a provider (`?url=...&timeout=...`). | +| `GET` | `/providers/rules` | Lists all rule providers (`{"providers": {...}}`). | +| `GET` | `/providers/rules/{provider}` | Single rule provider details. | +| `PUT` | `/providers/rules/{provider}` | Refreshes the rule provider (`202 Accepted`). | +| `GET` | `/providers/rules/{provider}/rules` | **ClashRS extension**: lists the first 500 rules in the provider (`{"rules": [...]}`). | +| `GET` | `/providers/rules/{provider}/match` | **ClashRS extension**: tests whether `?target=` matches the provider (`{"match": }`). | + +### Rules, Connections, Flows & Telemetry + +| Method | Path | Description | +| --- | --- | --- | +| `GET` | `/rules` | Lists active routing rules (`{"rules": [...]}`). | +| `GET` | `/connections` | HTTP snapshot of active connections; WebSocket upgrade streams snapshots (optional `?interval=`, default `1`). | +| `DELETE` | `/connections` | Closes all active connections. | +| `DELETE` | `/connections/{id}` | Closes a single connection by UUID. | +| `GET` | `/flows` | **ClashRS extension**: aggregated flow stats grouped by `(dst_host, dst_port, protocol)`. Query params: `?top=<1..=500>` (default `20`), `?include_closed=` (default `true`). Supports WebSocket (`?interval=`, default `5`). | +| `GET` | `/memory` | HTTP returns `{"inuse": , "oslimit": }`; WebSocket streams updates (`?interval=`, default `1`; `oslimit` is `0` over WS). | +| `GET` (WS) | `/traffic` (or `/ws/traffic`) | WebSocket stream emitting `{"up": , "down": }` every second. | +| `GET` (WS) | `/logs` (or `/ws/logs`) | WebSocket stream emitting `LogEvent` JSON messages. | +| `GET` | `/user-stats` | **ClashRS extension**: returns and resets per-`inboundUser` traffic counters (`{"": {"upload": , "download": }}`). | + +### Cache & DNS + +| Method | Path | Description | +| --- | --- | --- | +| `POST` | `/cache/fakeip/flush` | Flushes the Fake-IP mapping table (`400` if Fake-IP is disabled; `204` on success). | +| `POST` | `/cache/dns/flush` | Flushes the DNS response cache (`204 No Content`). | +| `GET` | `/dns/query` | Queries the built-in DNS resolver (`400` in system-resolver mode). Required query params: `?name=&type=` (invalid `type` defaults to `A`). Returns DoH-JSON (`Status`, `Question`, `Answer`, etc.). | + +## Quick `curl` Examples + +```bash +# Check version +curl -H "Authorization: Bearer change-me" http://127.0.0.1:9090/version + +# Switch routing mode at runtime +curl -X PATCH http://127.0.0.1:9090/configs \ + -H "Authorization: Bearer change-me" \ + -H "Content-Type: application/json" \ + -d '{"mode": "global"}' + +# Switch selected node in group PROXY +curl -X PUT http://127.0.0.1:9090/proxies/PROXY \ + -H "Authorization: Bearer change-me" \ + -H "Content-Type: application/json" \ + -d '{"name": "vless-reality"}' + +# Query built-in DNS over Unix Domain Socket +curl --unix-socket /tmp/clash-rs.sock \ + "http://localhost/dns/query?name=example.com&type=A" +``` diff --git a/docs/en/guides/compatibility.md b/docs/en/guides/compatibility.md new file mode 100644 index 0000000..723e6e3 --- /dev/null +++ b/docs/en/guides/compatibility.md @@ -0,0 +1,110 @@ +# Mihomo Compatibility & Safe Paths + +ClashRS can operate as a drop-in replacement for Mihomo in launchers such as Clash Verge while enforcing strict filesystem path confinement for configuration-supplied assets. + +## Mihomo Compatibility Mode + +Enable compatibility mode when sharing a data directory and GeoData files with Mihomo: + +=== "CLI Flag" + + ```bash + clash-rs --compatibility -d ./profiles -f config.yaml + ``` + + This loads `./profiles/config.yaml` and sets `./profiles` as the working directory (if `-d` is omitted, the current directory is used). + +=== "Environment Variable" + + For launchers with a fixed command line, set: + + ```bash + CLASH_RS_COMPATIBILITY_MODE=1 # or "true" (case-insensitive) + ``` + + To disable it later, unset the variable and omit `--compatibility`, then restart ClashRS. + +### What Compatibility Mode Changes + +1. **Default GeoData paths** (applied only when omitted in YAML; preserved across profile reloads): + + | YAML Key | Default in Compatibility Mode | + | --- | --- | + | `mmdb` | `Country.mmdb` | + | `geosite` | `geosite.dat` | + +2. **Isolated proxy selection cache**: + - With `profile.store-selected: true`, compatibility mode stores selections in **`clash-rs-cache.db`** instead of `cache.db`, leaving Mihomo's `cache.db` untouched. + - A hot reload keeps the cache filename selected at startup. + +3. **Single-dash IPC flag aliases**: + - ClashRS automatically rewrites `-ext-ctl-unix` and `-ext-ctl-pipe` to `--ext-ctl-unix` / `--ext-ctl-pipe` before parsing CLI options. + +--- + +## Safe Paths { #safe-paths } + +By default, ClashRS confines **all configuration-supplied paths** to the working directory (`-d`, or current directory when omitted) in **both** normal and compatibility modes. This applies to: + +- GeoData files (`mmdb`, `asn-mmdb`, `geosite`) +- Provider files and local caches (`proxy-providers`, `rule-providers`, `inbound-providers`) +- TLS certificates and keys (`tls-cert`, `tls-key`, `certificate`, `private-key`, `ca-cert`) +- Dashboard directory (`external-ui`) +- Explicit profile paths submitted via `PUT /configs` + +!!! tip "Startup profile outside `-d`" + Outside `--service-mode`, you may pass a startup profile outside `-d` via `-c` / `-f`. Subsequent `PUT /configs` reloads with an empty `path` and `payload` keep that startup file. + +### Allowing Extra Directories (`SAFE_PATHS`) + +Set `SAFE_PATHS` in the process environment to allow additional absolute root directories (separated by `:` on Unix or `;` on Windows): + +```bash +# Linux / macOS +SAFE_PATHS=/srv/providers:/srv/geodata clash-rs -d /etc/clash -c config.yaml +``` + +```powershell +# Windows PowerShell +$env:SAFE_PATHS = "C:\clash\providers;C:\clash\geodata" +clash-rs -d C:\clash -c config.yaml +``` + +- An explicitly listed root directory may be a symlink or Windows junction (resolved once at startup; overlapping roots pick the most specific match). +- Any symlink or Windows reparse point **below** an allowed root is rejected. + +### Disabling Safe Paths (`SKIP_SAFE_PATH_CHECK`) + +To opt out of safe-path checking outside `--service-mode`, set `SKIP_SAFE_PATH_CHECK` to `1`, `t`, `T`, `true`, `TRUE`, or `True`. Both `SAFE_PATHS` and `SKIP_SAFE_PATH_CHECK` are read once at startup. + +--- + +## Service Mode (`--service-mode`) + +Designed for privileged background services (such as Clash Verge Service): + +- Requires `--directory` (`-d`). +- Forbids `--log-file` (`-l`). +- Unless `--test-config` is passed, requires non-empty `--controller-ipc` (and non-empty `--controller-pipe-sddl` / `LISTEN_NAMEDPIPE_SDDL` on Windows). +- Automatically enables `--compatibility`. +- **Ignores `SAFE_PATHS` and `SKIP_SAFE_PATH_CHECK`**—all config files and assets must live under `-d`. +- Forbids `fd://` TUN devices, custom Naive `cronet-lib-path`, and `POST /restart` (returns `409 Conflict`). + +--- + +## Quick Migration Checklist (Mihomo → ClashRS) + +| Mihomo Feature / Key | ClashRS Equivalent or Status | +| --- | --- | +| `fwmark` | Use `routing-mark` | +| `tun.inet4-address` / `tun.inet6-address` | Use `tun.gateway` / `tun.gateway-v6` | +| `tun.auto-redirect: true` (Linux) | Rejected on Linux; use `auto-route: true` with `so-mark` & `route-table` | +| `dns.enhanced-mode: redir-host` | Not supported (no-op); use `fake-ip` or `normal` | +| `dns.nameserver: ["system"]` | Not supported (skipped); specify concrete IPs or DoH/DoT URLs | +| `dns.nameserver-policy` list values | Must be a single upstream string per domain | +| `proxies[].type: http / snell / ssr` | Not supported (parse error) | +| `hysteria2` without `skip-cert-verify` | Must explicitly specify `skip-cert-verify: false` or `true` | +| `vmess` without `cipher` | Explicitly set `cipher: auto` (or concrete cipher) | +| `proxy-groups` `filter` / `include-all` | Not implemented | +| `rules`: `FINAL`, `SUB-RULE`, `IP-ASN`, `UID` | Not supported (use `MATCH` instead of `FINAL`) | +| `rule-providers` `format: mrs` | Supported for `domain` and `ipcidr` (`classical` unsupported) | diff --git a/docs/en/index.md b/docs/en/index.md index 39edbb4..8ad78d5 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -1,11 +1,45 @@ -# ClashRS User Manual +--- +hide: + - toc + - navigation +--- -ClashRS is a rule-based network proxy written in Rust. It can serve HTTP and SOCKS clients or act as a network gateway through a TUN device. +# Welcome to ClashRS User Manual -- [Quick start](quick-start.md) walks through starting a local proxy or choosing a graphical interface. -- [Inbounds](config/inbounds.md) explains how to accept connections. -- [Full configuration example](config/full.md) shows how DNS, outbounds and routing rules fit together. +**ClashRS** is a high-performance, rule-based network proxy core written in Rust. It lets you route TCP and UDP traffic flexibly across multiple proxy protocols, built-in anti-spoofing DNS, transparent proxying / TUN devices, and dynamic remote providers. -## Features +!!! info "Documentation Baseline" + This manual reflects **ClashRS v0.10.x** (`Watfaq/clash-rs`), including Mihomo compatibility mode, service-mode safe path enforcement, multi-protocol listeners, and all currently supported inbound and outbound protocols. -ClashRS can route traffic by source, destination, domain or GeoIP and load remote proxy and rule providers. Its DNS resolver supports UDP, TCP, DNS over HTTPS and DNS over TLS. Outbound protocols include Shadowsocks, Trojan and VMess. ClashRS also supports distributed tracing. See the [ClashRS feature list](https://github.com/Watfaq/clash-rs#-features). +## Key Features + +- **Flexible Traffic Routing**: 18 rule types including domain, regex, GeoIP, GeoSite, CIDR, port range, process name/path, inbound type/user, logical combinators (`AND`/`OR`/`NOT`), and rule sets (`yaml`, `text`, `mrs`). +- **Built-in Anti-Spoofing DNS**: Supports UDP, TCP, DoT, DoH, and DHCP upstreams, local UDP/TCP/DoT/DoH/DoH3 listeners, Fake-IP mode, fallback filtering, per-domain policies, EDNS Client Subnet, and rule-aware upstream routing. +- **Rich Inbound Modes**: HTTP, SOCKS5, Mixed, Shadowsocks (including SS2022 multi-user), AnyTLS, Hysteria2, Tunnel port forwarding, Linux/Android TProxy, Linux Redir, and cross-platform TUN. +- **16 Outbound Protocols**: Direct, Reject, Shadowsocks / SS2022 (with obfs / v2ray-plugin / ShadowTLS), SOCKS5, AnyTLS, Trojan, VMess, VLESS (with REALITY & XTLS Vision), WireGuard, TUIC v5, Hysteria2, Naive (Cronet), ShadowQUIC, SSH, Tailscale, and Tor. +- **Smart Proxy Groups & Providers**: `select`, `url-test` (with circuit breaker, adaptive tolerance, and manual lock), `fallback`, `load-balance`, `relay`, and `smart` scoring groups, plus HTTP/File/Inline providers with hot reload. +- **Controller & Drop-in Compatibility**: REST + WebSocket controller over TCP, Unix Domain Socket, or Windows Named Pipe, embedded Web Dashboard, and Mihomo compatibility mode (`--compatibility`). + +## Supported Platforms + +| Platform | Runtime Support | Notes | +| --- | --- | --- | +| **Linux** | Full (CLI, TUN, TProxy, Redir) | Policy routing (`route-table`) and `SO_MARK` anti-loop | +| **Windows** | Full (CLI, GUI, Wintun TUN) | Run TUN as Administrator; supports `wintun.dll` or `--features wintun-embed` and WFP `strict-route` | +| **macOS** | Full (CLI, GUI, `utun` TUN) | Supports `utun*` devices and XCFramework builds | +| **FreeBSD** | CLI, TUN | Multi-FIB routing via `setfib` | +| **Android** | FFI / TUN (`fd://`) / TProxy | Official client: [clash-android](https://github.com/rust-proxy/clash-android) | +| **iOS / iPadOS** | FFI / TUN (`fd://`) | Official client: [ChocLite](https://apps.apple.com/app/id6467517938) | + +## Quick Navigation + +- **New to ClashRS?** Start with [Quick Start](quick-start/index.md), [CLI & Environment](quick-start/cli.md), or [GUI & Clients](quick-start/gui.md). +- **Writing a config file?** Read [General Configuration](config/index.md), [DNS](config/dns.md), [TUN](config/tun.md), [Inbounds](config/inbounds/index.md), [Outbounds](config/outbounds/index.md), [Proxy Groups](config/proxy-groups.md), [Routing Rules](config/rules.md), and [Full Example](config/full.md). +- **Migrating from Mihomo or integrating a dashboard?** See [Mihomo Compatibility & Safe Paths](guides/compatibility.md) and [REST API & Controller](guides/api.md). + +## Links + +- Source Repository: [Watfaq/clash-rs](https://github.com/Watfaq/clash-rs) +- Releases: [GitHub Releases](https://github.com/Watfaq/clash-rs/releases) +- Container Images: [ghcr.io/watfaq/clash-rs](https://github.com/Watfaq/clash-rs/pkgs/container/clash-rs) +- Community: [Telegram User Group](https://t.me/thisisnotclash) diff --git a/docs/en/quick-start.md b/docs/en/quick-start.md deleted file mode 100644 index 94e07b1..0000000 --- a/docs/en/quick-start.md +++ /dev/null @@ -1,24 +0,0 @@ -# Quick start - -Download the binary for your platform from the [ClashRS releases](https://github.com/Watfaq/clash-rs/releases) and make it available as `clash-rs` on your PATH. - -## Start an HTTP proxy - -Save the following as `config.yaml`: - -```yaml -port: 7890 -``` - -Check the configuration, then start ClashRS: - -```sh -clash-rs -t -c config.yaml -clash-rs -c config.yaml -``` - -Set your application's HTTP proxy to `127.0.0.1:7890`. See [Inbounds](config/inbounds.md) for SOCKS and named listeners, or the [full configuration example](config/full.md) for routing and outbound settings. - -## Use a GUI - -[Clash Nyanpasu](https://github.com/LibNyanpasu/clash-nyanpasu) provides a graphical interface for ClashRS. diff --git a/docs/en/quick-start/cli.md b/docs/en/quick-start/cli.md new file mode 100644 index 0000000..5b7d707 --- /dev/null +++ b/docs/en/quick-start/cli.md @@ -0,0 +1,87 @@ +# CLI & Environment Variables + +This page documents every command-line flag and runtime environment variable recognized by `clash-rs`. + +## Command-Line Options + +```text +Usage: clash-rs [OPTIONS] +``` + +| Flag | Short / Aliases | Default | Description | +| --- | --- | --- | --- | +| `--directory ` | `-d` | Current working directory (`.`) | Sets the working directory (`$CWD`). Config-relative paths resolve from here. In `--compatibility` (non-service) mode, also changes the process working directory via `set_current_dir`. | +| `--config ` | `-c`, `-f` | `config.yaml` | Configuration file path. Outside `--service-mode`, resolved as `/` (absolute paths outside `-d` are accepted at startup) and auto-created with `port: 7890` if missing. Inside `--service-mode`, confined by `SafePaths` and never auto-created. | +| `--test-config` | `-t` | `false` | Parse and validate the configuration, then exit (`0` on success, `1` on failure). | +| `--version` | `-v`, `-V` | `false` | Print version string (`clash-rs `) and exit. | +| `--log-file ` | `-l` | None | Append logs to a file (relative to `$CWD`) in addition to standard output. **Cannot be combined with `--service-mode`.** | +| `--controller-ipc ` | `--ext-ctl-unix`, `--ext-ctl-pipe` (single-dash `-ext-ctl-unix` / `-ext-ctl-pipe` also accepted) | None | Overrides `external-controller-ipc` in config. Preserved across config reloads. | +| `--controller-pipe-sddl ` | Windows only (env: `LISTEN_NAMEDPIPE_SDDL`) | None | Sets the Windows Named Pipe SDDL security descriptor for the IPC controller. CLI flag overrides the environment variable. Preserved across reloads. | +| `--compatibility` | — | `false` | Enables Mihomo compatibility mode (default `Country.mmdb` / `geosite.dat`, separate `clash-rs-cache.db`). See [Mihomo Compatibility](../guides/compatibility.md). | +| `--service-mode` | — | `false` | Restricted mode for privileged system services (e.g., Clash Verge Service). Requires `--directory`, forbids `--log-file`, requires non-empty `--controller-ipc` (and `--controller-pipe-sddl` / `LISTEN_NAMEDPIPE_SDDL` on Windows) unless `--test-config` is passed, implies `--compatibility`, disables `SAFE_PATHS` / `SKIP_SAFE_PATH_CHECK`, forbids `fd://` TUN, forbids custom Naive `cronet-lib-path`, and disables `POST /restart`. | +| `--strict-config` | — | `false` | Rejects any unknown YAML keys at any nesting depth. By default, unknown keys are silently ignored for Mihomo / Clash compatibility. (Note: hot reloads via `PUT /configs` do not apply `--strict-config`.) | +| `--help-improve` | — | `false` | Enables opt-in crash reporting (Sentry). | +| `--help` | `-h` | — | Prints CLI help. | + +!!! warning "Clash Verge Service Enforcement" + If the executable path resides under `.../clash-verge-service/cores/`, ClashRS refuses to start unless `--service-mode` is passed. + +### Common CLI Examples + +```bash +# Run with explicit working directory and config file +clash-rs -d /etc/clash -c config.yaml + +# Test configuration in strict mode +clash-rs -d /etc/clash -c config.yaml -t --strict-config + +# Run in Mihomo compatibility mode with a Unix socket controller +clash-rs --compatibility -d ~/.config/mihomo -f config.yaml --ext-ctl-unix /tmp/clash-rs.sock + +# Additionally write logs to a file +clash-rs -d ./data -c config.yaml -l clash.log +``` + +## Runtime Environment Variables + +| Variable | Format / Values | Default | Effect | +| --- | --- | --- | --- | +| `CLASH_RS_COMPATIBILITY_MODE` | `1` or `true` (case-insensitive, trimmed) | Disabled | Equivalent to passing `--compatibility`. Useful for launchers with fixed command lines. | +| `SAFE_PATHS` | OS path list (`:` on Unix, `;` on Windows) of absolute directories | Empty | Additional root directories allowed for config-referenced assets (GeoData, providers, certificates, `external-ui`, API reload paths). **Ignored in `--service-mode`.** See [Safe Paths](../guides/compatibility.md#safe-paths). | +| `SKIP_SAFE_PATH_CHECK` | `1`, `t`, `T`, `true`, `TRUE`, `True` | Disabled | Disables safe-path confinement. **Ignored in `--service-mode`.** | +| `LISTEN_NAMEDPIPE_SDDL` | Windows SDDL string | `D:(A;;GRGW;;;BU)(A;;GRGW;;;SY)` | Default SDDL applied to the Windows Named Pipe IPC controller when `--controller-pipe-sddl` is not passed. | +| `CLASH_RS_MEM_LIMIT_MB` | ``, `:soft`, or `:hard` (`MB > 0`) | `0` (unlimited) | Enables memory limit management. When built with `jemallocator` and `MALLOC_CONF` is unset, also lowers jemalloc arena `dirty_decay_ms` and `muzzy_decay_ms` to `1000` ms for faster RSS reclamation. | +| `CLASH_RS_MEM_HARD_RATIO` | Float (`>= 1.0`, or `0` to disable hard eviction) | `2.0` | Multiplier above `CLASH_RS_MEM_LIMIT_MB` that triggers hard connection eviction (closes 20% of connections). | +| `MALLOC_CONF` | Standard jemalloc config string | Unset | If set, prevents ClashRS from overriding jemalloc decay settings when `CLASH_RS_MEM_LIMIT_MB` is used. | +| `RUST_LOG` | `tracing_subscriber` filter directives | `warn,clash=` | Overrides default log filtering when valid. | +| `CLASH_RS_BACKOFF_ROUNDS` | Positive integer | `12` | Health-check backoff interval (in rounds) for proxies that fail 3+ consecutive checks. | +| `CLASH_RS_HEALTHCHECK_CONCURRENCY` | Positive integer | `8` | Maximum concurrent proxy health checks. | +| `SSLKEYLOGFILE` | File path | Unset | When present, enables `rustls::KeyLogFile` TLS key logging for packet inspection tools such as Wireshark. | + +## Running as a systemd Service (Linux) + +```ini title="/etc/systemd/system/clash-rs.service" +[Unit] +Description=ClashRS Proxy Core +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/clash-rs -d /etc/clash -c config.yaml +Restart=on-failure +RestartSec=3 +AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE +CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE +LimitNOFILE=1048576 + +[Install] +WantedBy=multi-user.target +``` + +Enable and start the service: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now clash-rs +``` diff --git a/docs/en/quick-start/gui.md b/docs/en/quick-start/gui.md new file mode 100644 index 0000000..173d345 --- /dev/null +++ b/docs/en/quick-start/gui.md @@ -0,0 +1,60 @@ +# GUI Clients & Web Dashboard + +ClashRS can be driven by desktop GUI launchers, mobile apps built on `clash-ffi`, or a browser-based Web Dashboard via its REST controller. + +## Desktop Clients + +### Clash Nyanpasu + +[Clash Nyanpasu](https://github.com/LibNyanpasu/clash-nyanpasu) supports ClashRS directly as a selectable proxy core on Windows, macOS, and Linux. + +### Clash Verge + +ClashRS supports Mihomo-compatible profiles and TUN settings used by Clash Verge: + +1. Select **ClashRS** as the core in Clash Verge settings. +2. When using **Clash Verge Service**, keep configuration files and all referenced assets (GeoData, providers, certificates) inside the service runtime directory, because service mode enforces [Safe Paths](../guides/compatibility.md#safe-paths). +3. When enabling **TUN** on Windows, all stack choices (`system`, `gvisor`, `mixed`) use the same native ClashRS Rust network stack, and Wintun is handled automatically when `wintun.dll` is present or embedded. + +## Mobile Clients + +| Platform | Client | Notes | +| --- | --- | --- | +| **Android** | [clash-android](https://github.com/rust-proxy/clash-android) | Built on `clash-ffi` with VPN `fd://` TUN and TProxy support | +| **iOS / iPadOS** | [ChocLite](https://apps.apple.com/app/id6467517938) | Official iOS client built on ClashRS ([TestFlight Beta](https://testflight.apple.com/join/cLy4Ub5C)) | + +## Built-in & External Web Dashboard + +ClashRS exposes a web UI at `/ui/` whenever `external-controller` is configured. + +### Using the Embedded Dashboard + +Default release builds compile with the `dashboard` feature enabled. Simply enable `external-controller`: + +```yaml +external-controller: 127.0.0.1:9090 +secret: "change-me" +``` + +Then open `http://127.0.0.1:9090/ui/` in a browser. + +### Using an External Dashboard (`external-ui`) + +To serve a custom dashboard (such as Yacd or Metacubexd), configure `external-ui` and optionally `external-ui-url`: + +```yaml +external-controller: 127.0.0.1:9090 +secret: "change-me" +external-ui: ui +external-ui-url: "https://github.com/MetaCubeX/metacubexd/archive/refs/heads/gh-pages.zip" +``` + +- `external-ui` is resolved relative to the working directory (`-d`) and checked against `SafePaths`. +- If the directory does not exist or is empty and `external-ui-url` is set, ClashRS downloads and extracts the archive (`.zip` or `.tgz`). +- URL fragment modifiers supported on `external-ui-url`: + - `#force=true` — force re-download even if the directory is non-empty. + - `#_clash_outbound=` — download the archive through the named outbound proxy. +- If `external-ui` is missing or empty and no download succeeds, ClashRS falls back to the embedded dashboard (when compiled with `dashboard`). + +!!! warning "Exposing the Controller Beyond Localhost" + If `external-controller` binds to a non-loopback address (for example `0.0.0.0:9090`), ClashRS requires **both** a non-empty `secret` and explicit CORS origins (`external-controller-cors` or `cors-allow-origins`); otherwise the API server refuses to start. See [REST API & Controller](../guides/api.md). diff --git a/docs/en/quick-start/index.md b/docs/en/quick-start/index.md new file mode 100644 index 0000000..6080a8a --- /dev/null +++ b/docs/en/quick-start/index.md @@ -0,0 +1,144 @@ +# Quick Start + +This guide helps you install ClashRS, write a minimal working configuration, and verify that traffic is flowing. + +## Installation + +=== "Prebuilt Binary" + + Download the release archive for your operating system and architecture from [GitHub Releases](https://github.com/Watfaq/clash-rs/releases). + + On Linux/macOS, make the binary executable: + + ```bash + chmod +x clash-rs + ./clash-rs -v + ``` + + !!! note "Windows TUN requirement" + To use TUN on Windows with a standard build, place the architecture-matching [`wintun.dll`](https://wintun.net/) in the same directory as `clash-rs.exe` and run as Administrator. Alternatively, build with `--features wintun-embed` (Windows MSVC) to embed Wintun inside the executable. + +=== "Docker" + + Official container images are published to GitHub Container Registry: + + ```bash + docker run -d \ + --name clash-rs \ + --restart unless-stopped \ + -p 7890:7890 \ + -p 9090:9090 \ + -v /path/to/clash-config:/etc/clash \ + ghcr.io/watfaq/clash-rs:latest \ + -d /etc/clash -c config.yaml + ``` + + If you enable TUN inside Docker on Linux, also pass `--cap-add NET_ADMIN --device /dev/net/tun`. + +=== "Build from Source" + + ### Prerequisites + + - Rust toolchain (Edition 2024) + - `cmake` (3.29 or newer) + - `libclang` (LLVM) + - `protoc` (Protocol Buffers compiler for GeoData code generation) + - `nasm` (Windows only) + + ### Compile + + ```bash + git clone https://github.com/Watfaq/clash-rs.git + cd clash-rs + + # Standard release build (default features: standard, aws-lc-rs, dashboard) + cargo build --release + + # Plus build (includes Tor / onion support) + cargo build --release --features plus + + # Build with static Naive/Cronet support + cargo build --locked --release -p clash-rs --features naive-static,naive-download + ``` + +### Cargo Feature Bundles + +| Feature | Included Capabilities | +| --- | --- | +| `default` (`clash-bin`) | `standard`, `aws-lc-rs`, `dashboard` | +| `standard` | `shadowsocks`, `tuic`, `ssh`, `shadowquic`, `wireguard`, `tailscale`, `zero_copy`, `tproxy`, `tun`, `redir` | +| `plus` | Everything in `standard` plus `onion` (Tor) | +| `naive` / `naive-static` / `naive-download` | Naive outbound (Cronet-based); **not** enabled by default | +| `wintun-embed` | Embeds `wintun.dll` in Windows MSVC builds | +| `telemetry` | OpenTelemetry / Jaeger tracing export | + +## Minimal Configuration + +Create a working directory and save `config.yaml`: + +```yaml +mixed-port: 7890 +allow-lan: false +mode: rule +log-level: info +external-controller: 127.0.0.1:9090 + +proxies: + - name: demo-ss + type: ss + server: proxy.example.com + port: 8388 + cipher: 2022-blake3-aes-128-gcm + password: "YOUR_BASE64_PASSWORD" + udp: true + +proxy-groups: + - name: PROXY + type: select + proxies: + - demo-ss + - DIRECT + +rules: + - DOMAIN-SUFFIX,example.com,PROXY + - MATCH,DIRECT +``` + +!!! tip "Auto-generated bootstrap config" + Outside `--service-mode`, if the specified config file does not exist, ClashRS automatically creates a starter file containing `port: 7890`. + +## Validate and Run + +1. **Test your configuration** before starting: + + ```bash + clash-rs -d ./clash-data -c config.yaml -t + ``` + + Use `--strict-config` alongside `-t` if you want unknown YAML keys rejected instead of silently ignored: + + ```bash + clash-rs -d ./clash-data -c config.yaml -t --strict-config + ``` + +2. **Start ClashRS**: + + ```bash + clash-rs -d ./clash-data -c config.yaml + ``` + +3. **Verify proxy connectivity**: + + ```bash + curl -x http://127.0.0.1:7890 https://example.com + ``` + +4. **Open the built-in Web Dashboard**: + + When `external-controller` is set and the binary is compiled with the default `dashboard` feature, open `http://127.0.0.1:9090/ui/` in your browser. + +## Next Steps + +- Learn all flags and environment variables in [CLI & Environment](cli.md). +- Pair ClashRS with a desktop or mobile client in [GUI & Clients](gui.md). +- Explore full configuration options in [Configuration Overview](../config/index.md). diff --git a/docs/zh/config/dns.md b/docs/zh/config/dns.md new file mode 100644 index 0000000..5ab3807 --- /dev/null +++ b/docs/zh/config/dns.md @@ -0,0 +1,152 @@ +# DNS 解析与服务 + +ClashRS 内置防污染 DNS 解析器与多协议本地 DNS 服务器(支持 UDP、TCP、DoT、DoH 与 DoH3)。 + +当 `dns.enable` 为 `false`(默认值)时,ClashRS 直接使用操作系统 DNS 解析(`SystemResolver`),且不启动本地 DNS 监听服务。 + +## `dns` 全部配置项 + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `enable` | `bool` | `false` | 是否启用内置 DNS 解析器与本地 DNS 服务。 | +| `ipv6` | `bool` | `false` | 是否解析并返回 `AAAA` 记录。**实际生效条件为 `config.ipv6 && dns.ipv6`**(两者均为 `true` 才开启)。 | +| `use-hosts` | `bool` | `true` | 是否优先查询顶层 `hosts` 映射(无论此项为何值,`localhost -> 127.0.0.1` 始终内置)。 | +| `listen` | `string` 或对象 | 无 | 本地 DNS 监听地址;省略则不启动本地监听服务。详见 [本地 DNS 监听](#dns-listeners)。 | +| `enhanced-mode` | `normal` \| `fake-ip` \| `redir-host` | `normal` | `fake-ip` 启用 Fake-IP 虚拟地址池。**`redir-host` 仅保留解析兼容性、实际不生效**(启动时会打印警告)。 | +| `fake-ip-range` | CIDR 字符串 | `"198.18.0.1/16"` | `fake-ip` 模式的虚拟 IP 地址池 CIDR(即使 `dns.enable: false` 也会校验格式)。 | +| `fake-ip-filter` | `list[string]` | `[]` | 跳过 Fake-IP、返回真实 IP 的域名列表(支持 `*.lan`、`+.example.com` 等 Trie 模式)。普通出站代理的服务器域名会自动跳过以防回环。 | +| `default-nameserver` | `list[string]` | `["114.114.114.114", "8.8.8.8"]` | 引导 DNS,用于解析 DoH/DoT 上游及 `proxy-server-nameserver` 中的域名。**不能为空,且每项主机部分必须为纯 IP 地址**。不受 `respect-rules` 影响。 | +| `nameserver` | `list[string]` | `[]` | 主上游 DNS 列表。`dns.enable: true` 时不能为空;唯一例外是同时开启 Mihomo 风格 TUN 时,空的 `nameserver` 会自动回退为 `default-nameserver`。 | +| `fallback` | `list[string]` | `[]` | 备用上游 DNS 列表,配合 `fallback-filter` 使用。 | +| `fallback-filter` | 对象 | 见下文 | 控制何时采用 `fallback` 结果而非主 `nameserver` 结果的过滤规则。 | +| `proxy-server-nameserver` | `list[string]` | `[]` | 专门用于解析出站代理服务器域名的上游 DNS(允许域名形式的 DoH/DoT,由 `default-nameserver` 引导解析)。不受 `respect-rules` 影响。 | +| `nameserver-policy` | `map[域名 -> string]` | `{}` | 按域名指定上游 DNS。**注意:每个键对应的值是单个上游字符串**(而非列表)。 | +| `edns-client-subnet` | 对象 | 无 | 为上游请求附加 ECS(包含 `ipv4` 和/或 `ipv6` CIDR,至少设置其一)。若原请求已带 ECS 选项则不覆盖。 | +| `respect-rules` | `bool` | `false` | 为 `true` 时,`nameserver`、`fallback` 与 `nameserver-policy` 的上游请求通过路由规则引擎转发(而非固定 `DIRECT`)。 | + +!!! note "未实现的 Mihomo DNS 字段" + `use-system-hosts`、`cache-algorithm`、`fake-ip-filter-mode`、`direct-nameserver` 在 ClashRS 中未定义。内置响应缓存固定为 1,024 条 LRU(反向 IP→域名缓存固定容量 1,024、TTL 3 秒)。 + +## 本地 DNS 监听(`dns.listen`) { #dns-listeners } + +`dns.listen` 支持两种格式: + +=== "单 UDP 字符串" + + ```yaml + dns: + enable: true + listen: 127.0.0.1:5353 + ``` + + 以冒号开头的写法(如 `:5353`)会自动补全为 `0.0.0.0:5353`。 + +=== "多协议对象" + + 可同时提供 UDP、TCP、DoT、DoH 与 DoH3 服务: + + ```yaml + dns: + enable: true + listen: + udp: 127.0.0.1:5353 + tcp: 127.0.0.1:5353 + dot: + addr: 127.0.0.1:853 + ca-cert: certs/dns.crt + ca-key: certs/dns.key + doh: + addr: 127.0.0.1:8443 + ca-cert: certs/dns.crt + ca-key: certs/dns.key + hostname: dns.example.com + doh3: + addr: 127.0.0.1:8443 + ca-cert: certs/dns.crt + ca-key: certs/dns.key + hostname: dns.example.com + ``` + + - `dot`:`addr`(必填),可选 `ca-cert`、`ca-key`。 + - `doh` 与 `doh3`:`addr`(必填),可选 `ca-cert`、`ca-key`、`hostname`(TLS / QUIC SNI)。 + +## 上游名称服务器 URL 语法 + +| 协议前缀 | 默认端口 | 示例 | +| --- | --- | --- | +| `udp://`(或省略) | `53` | `1.1.1.1`、`udp://8.8.8.8:53`、`2400:3200::1` | +| `tcp://` | `53` | `tcp://8.8.8.8:53` | +| `tls://`(DoT) | `853` | `tls://dns.quad9.net:853` | +| `https://`(DoH) | `443` | `https://cloudflare-dns.com/dns-query` | +| `dhcp://` | — | `dhcp://eth0`(从指定网卡 DHCP 租约获取 DNS) | + +源码核实的关键行为: + +- **不支持 `"system"`** 作为上游项(会打印警告并跳过)。 +- **DoH 路径固定为 `/dns-query`**,`https://` URL 中的自定义路径会被忽略;使用纯 IP 地址访问 DoH 时会跳过主机名证书校验。 +- **支持 URL Fragment 路由修饰符**(`#` 后用 `&` 分隔): + - `#` 或 `#proxy=`:通过指定出站代理或代理组发起该上游的 DNS 请求。 + - `#interface=`:绑定出站物理网卡(`auto` 自动探测默认物理网卡;启用 TUN 时会自动继承 TUN 默认出站网卡)。 + +```yaml +nameserver: + - https://1.1.1.1/dns-query#PROXY + - 223.5.5.5#interface=eth0 +``` + +## `fallback-filter` + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `geoip` | `bool` | `true` | 当主 `nameserver` 返回的 IP 不属于 `geoip-code` 国家时采用 `fallback`。若未配置或尚未加载 `mmdb`,该过滤条件默认放行至 `fallback`。 | +| `geoip-code` | `string` | `"CN"` | 国家代码(内部统一转为大写)。 | +| `ipcidr` | `list[CIDR]` | `[]` | 主 DNS 返回 IP 命中列表内任一 CIDR 时改用 `fallback`。 | +| `domain` | `list[string]` | `[]` | 命中这些域名的查询直接采用 `fallback`。 | + +## 完整 DNS 配置示例 + +```yaml +ipv6: true +mmdb: Country.mmdb + +hosts: + router.lan: 192.168.1.1 + +dns: + enable: true + ipv6: true + use-hosts: true + listen: + udp: 127.0.0.1:5353 + tcp: 127.0.0.1:5353 + enhanced-mode: fake-ip + fake-ip-range: 198.18.0.1/16 + fake-ip-filter: + - "*.lan" + - "+.local" + - "time.windows.com" + default-nameserver: + - 223.5.5.5 + - 8.8.8.8 + proxy-server-nameserver: + - https://dns.alidns.com/dns-query + nameserver: + - 223.5.5.5 + - 119.29.29.29 + fallback: + - tls://1.1.1.1:853 + - https://dns.google/dns-query + fallback-filter: + geoip: true + geoip-code: CN + ipcidr: + - 240.0.0.0/4 + domain: + - "+.google.com" + - "+.github.com" + nameserver-policy: + "+.internal.example.com": 192.168.1.1 + edns-client-subnet: + ipv4: 198.51.100.0/24 + respect-rules: false +``` diff --git a/docs/zh/config/full.md b/docs/zh/config/full.md index 5495049..21da688 100644 --- a/docs/zh/config/full.md +++ b/docs/zh/config/full.md @@ -1,3 +1,5 @@ # 完整配置示例 +下方示例整合了基础设置、DNS、TUN、命名监听器、固定隧道转发、主流出站协议、代理组、内联规则提供者与路由规则。使用前请替换所有示例域名、UUID、密钥与密码,并通过 `clash-rs -c config.yaml -t --strict-config` 验证。 + --8<-- "full-example.md" diff --git a/docs/zh/config/inbounds.md b/docs/zh/config/inbounds.md deleted file mode 100644 index ae6f861..0000000 --- a/docs/zh/config/inbounds.md +++ /dev/null @@ -1,35 +0,0 @@ -# 入站监听 - -## 配置端口 - -顶层端口字段会创建带有预设名称的监听器。以下配置分别开启 HTTP 和 SOCKS 端口: - -```yaml -port: 7890 -socks-port: 7891 -``` - -| 字段 | 监听器名称 | -| --- | --- | -| `port` | `HTTP-IN` | -| `socks-port` | `SOCKS-IN` | -| `mixed-port` | `MIXED-IN` | -| `tproxy-port` | `TPROXY-IN`(需要 TPROXY 支持) | - -## 自定义监听器 - -通过 `listeners` 可以指定监听器名称、协议、端口和绑定地址: - -```yaml -listeners: - - name: in-http - type: http - listen: 127.0.0.1 - port: 15201 -``` - -常见类型包括 `http`、`socks`、`mixed`、`tproxy` 和 `tunnel`,可用类型取决于构建时启用的功能。`tunnel` 监听器可以通过 `proxy` 指定转发流量的出站名称。 - -### 绑定地址 - -`listen` 接受 IPv4 或 IPv6 地址。`127.0.0.1` 和 `localhost` 表示 IPv4 回环地址,`"*"` 表示所有 IPv4 接口,`"::"` 表示所有 IPv6 接口。 diff --git a/docs/zh/config/inbounds/http.md b/docs/zh/config/inbounds/http.md new file mode 100644 index 0000000..042901d --- /dev/null +++ b/docs/zh/config/inbounds/http.md @@ -0,0 +1,61 @@ +# HTTP 与 Mixed 入站 + +ClashRS 支持独立的 HTTP 代理(`http`)以及在单个 TCP 端口上同时兼容 HTTP 与 SOCKS5 的混合代理(`mixed`)。 + +## HTTP 入站(`type: http`) + +- **传输层**:仅支持 TCP(支持普通 HTTP 代理请求及 HTTPS `CONNECT` 隧道)。 +- **认证**:复用顶层 `authentication`,通过 HTTP Basic `Proxy-Authorization` 请求头校验。 +- **独有字段**:除 [通用监听器字段](index.md#listeners) 外无额外字段。 + +=== "顶层端口简写" + + ```yaml + port: 7890 + bind-address: 127.0.0.1 + allow-lan: false + authentication: + - "alice:secret123" + ``` + +=== "命名监听器" + + ```yaml + listeners: + - name: http-in + type: http + listen: 127.0.0.1 + port: 7890 + allow-lan: false + ``` + +## Mixed 入站(`type: mixed`) + +`mixed` 监听器会预读每个新 TCP 连接的首字节: + +- 首字节为 `0x05` 时按 **SOCKS5**(含 `UDP_ASSOCIATE`)处理; +- 否则按 **HTTP** 代理处理。 + +- **认证**:HTTP 与 SOCKS5 客户端共用顶层 `authentication`。 +- **独有字段**: + - `udp`(`bool`,可选,默认 `true`):保留配置兼容;运行时 SOCKS5 握手中的 `UDP_ASSOCIATE` 命令始终启用。 + +=== "顶层端口简写" + + ```yaml + mixed-port: 7890 + bind-address: 127.0.0.1 + allow-lan: false + ``` + +=== "命名监听器" + + ```yaml + listeners: + - name: mixed-in + type: mixed + listen: 0.0.0.0 + port: 7890 + allow-lan: true + udp: true + ``` diff --git a/docs/zh/config/inbounds/index.md b/docs/zh/config/inbounds/index.md new file mode 100644 index 0000000..9ded304 --- /dev/null +++ b/docs/zh/config/inbounds/index.md @@ -0,0 +1,65 @@ +# 入站监听概览 + +入站监听器负责接收本地或远端客户端连接,并将流量交由 ClashRS 路由调度器分发。ClashRS 支持五种入站配置方式: + +1. **顶层端口简写**(`port`、`socks-port`、`mixed-port`、`redir-port`、`tproxy-port`) +2. **显式命名 `listeners`**:支持多协议、多端口与细粒度控制 +3. **顶层 `tunnels`**:固定目标的 TCP / UDP 端口转发 +4. **`inbound-providers`**:从本地文件或 HTTP 远程动态加载入站列表 +5. **[`tun`](../tun.md)**:跨平台三层虚拟网卡透明代理 + +## 顶层端口简写映射 + +顶层端口简写字段(类型 [`Port`](../types.md#port))会自动转换为命名监听器,并继承顶层 `bind-address`、`allow-lan` 与 `routing-mark`: + +| 顶层键名 | 别名 | 生成监听器名 | 入站类型 | 隐式默认参数 | 所需特性 | +| --- | --- | --- | --- | --- | --- | +| `port` | `http_port` | `HTTP-IN` | `http` | — | 内置 | +| `socks-port` | — | `SOCKS-IN` | `socks` | `udp: true` | 内置 | +| `mixed-port` | — | `MIXED-IN` | `mixed` | `udp: true` | 内置 | +| `redir-port` | — | `REDIR-IN` | `redir` | — | `redir`(`standard`) | +| `tproxy-port` | — | `TPROXY-IN` | `tproxy` | `udp: true`、`dns-hijack: true` | `tproxy`(`standard`) | + +当 `bind-address` 保持默认值(`0.0.0.0`)且顶层 `ipv6: true` 时,顶层端口简写会自动升级为双栈 `::`。 + +## 支持的 `listeners` 类型 + +| 类型 | 传输协议 | 平台 / 编译特性 | 详细文档 | +| --- | --- | --- | --- | +| `http` | TCP | 全平台 / 内置 | [HTTP 与 Mixed](http.md) | +| `mixed` | TCP + SOCKS5 UDP | 全平台 / 内置 | [HTTP 与 Mixed](http.md) | +| `socks` | TCP + UDP(`UDP_ASSOCIATE`) | 全平台 / 内置 | [SOCKS5](socks.md) | +| `tproxy`(或 `t-proxy`) | TCP + UDP | Linux、Android / `tproxy` | [透明代理](transparent.md) | +| `redir` | TCP | Linux / `redir` | [透明代理](transparent.md) | +| `tunnel` | TCP / UDP | 全平台 / 内置 | [端口转发(Tunnel)](tunnel.md) | +| `shadowsocks` | TCP + UDP | 全平台 / `shadowsocks` | [协议入站](protocols.md) | +| `anytls` | TCP + UoT v2 | 全平台 / 内置 | [协议入站](protocols.md) | +| `hysteria2` | QUIC(UDP) | 全平台 / 内置 | [协议入站](protocols.md) | + +## `listeners` 通用字段 + +`listeners` 中的每一项均包含以下公共字段: + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name` | `string` | 是 | — | 监听器名称。 | +| `type` | `string` | 是 | — | 入站类型(见上表)。 | +| `listen` | [`BindAddress`](../types.md#bindaddress) | 是 | — | 监听 IP(支持 `*`、`localhost`、`::`、`[::]` 或具体 IP)。 | +| `port` | `u16` | 是 | — | 监听端口(须为整数)。 | +| `allow-lan` | `bool` | 否 | `false` | 是否允许非本机地址接入(注意 `tunnel` 与 `tproxy` 当前未在 accept 阶段校验此项)。 | +| `fw-mark` | [`SocketMark`](../types.md#socketmark) | 否 | 无 | Linux / Android 路由标记(写入 `Session.so_mark`)。 | + +```yaml +listeners: + - name: local-mixed + type: mixed + listen: 127.0.0.1 + port: 7890 + allow-lan: false +``` + +### 去重与认证规则 + +- **加载优先级**:先注册 `listeners`,再注册 `tunnels`,最后注册顶层端口简写。完全相同的条目会记录警告并去重(注意 `name` 参与判等,不同名称绑定同一端口会在监听时冲突)。 +- **全局 `authentication`**:顶层 `authentication: ["user:pass"]` 统一作用于 `http`、`socks` 和 `mixed` 入站(含顶层简写与 `listeners[]`)。协议入站(`shadowsocks`、`anytls`、`hysteria2`)各自使用自身的 `password` / `users` 进行认证。 +- **多用户热更新**:`shadowsocks`、`anytls` 与 `hysteria2` 通过 `inbound-providers` 更新 `users` 时支持原地热更新,无需重启监听端口。详见 [提供者(Providers)](../providers.md#inbound-providers)。 diff --git a/docs/zh/config/inbounds/protocols.md b/docs/zh/config/inbounds/protocols.md new file mode 100644 index 0000000..7aad582 --- /dev/null +++ b/docs/zh/config/inbounds/protocols.md @@ -0,0 +1,110 @@ +# 协议入站(Shadowsocks、AnyTLS、Hysteria2) + +ClashRS 可通过 `shadowsocks`、`anytls` 与 `hysteria2` 监听器充当服务端节点。这三类入站均支持多用户凭据(`users`),认证用户名会自动写入会话供 `IN-USER` 路由规则与 `/user-stats` 流量统计使用,且支持通过 [`inbound-providers`](../providers.md#inbound-providers) 在不重启端口的情况下热更新用户列表。 + +## 多用户结构(`InboundUser`) + +```yaml +users: + - name: alice + password: "user-specific-password" + - name: bob + password: "another-password" +``` + +`name` 字段会作为 `inbound_user` 记录到连接会话中,可用于 `IN-USER` 规则与 `GET /user-stats`。 + +--- + +## Shadowsocks 入站(`type: shadowsocks`) + +- **编译特性**:`shadowsocks`(默认 `standard` 构建已启用)。 +- **传输层**:TCP + 可选 UDP(`udp` 默认 `true`)。 + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `cipher` | `string` | 是 | — | 加密方式,详见 [Shadowsocks 出站支持的加密方式](../outbounds/shadowsocks.md#supported-ciphers)。 | +| `password` | `string` | 是 | — | 单用户密码,或 SS2022 多用户模式下的服务端 PSK。 | +| `udp` | `bool` | 否 | `true` | 是否启用 UDP 转发。 | +| `users` | `list[InboundUser]` | 否 | `[]` | SS2022 多用户 EIH 列表(`password` 为 Base64 用户密钥)。 | + +```yaml +listeners: + - name: ss2022-server + type: shadowsocks + listen: 0.0.0.0 + port: 8388 + allow-lan: true + cipher: 2022-blake3-aes-128-gcm + password: "BASE64_SERVER_PSK" + udp: true + users: + - name: alice + password: "BASE64_ALICE_KEY" +``` + +--- + +## AnyTLS 入站(`type: anytls`) + +- **编译特性**:全平台内置。 +- **传输层**:TCP + TLS;UDP 通过 UoT v2 复用在同一连接上传输。 + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `password` | `string` | 是 | — | 单用户明文密码(仅在 `users` 为空时生效)。 | +| `users` | `list[InboundUser]` | 否 | `[]` | 多用户明文密码列表;非空时替代 `password`,校验阶段会拒绝重复密码。 | +| `certificate` | `string` | 否 | 自动生成 `localhost` 自签证书 | PEM 证书链文件路径或内联 PEM,须与 `private-key` 成对设置或成对省略。 | +| `private-key` | `string` | 否 | 自动生成 `localhost` 自签私钥 | PEM 私钥文件路径或内联 PEM,须与 `certificate` 成对设置或成对省略。 | +| `fallback` | `string` | 否 | 无 | 密码认证失败的 TLS 连接回落转发地址(`host:port`,如本地 Web 服务,用于防主动探测伪装);未设置时直接丢弃。 | + +```yaml +listeners: + - name: anytls-server + type: anytls + listen: 0.0.0.0 + port: 8443 + allow-lan: true + password: "default-password" + certificate: certs/fullchain.pem + private-key: certs/privkey.pem + fallback: 127.0.0.1:80 + users: + - name: alice + password: "alice-password" +``` + +--- + +## Hysteria2 入站(`type: hysteria2`) + +- **编译特性**:全平台内置。 +- **传输层**:基于 QUIC(UDP),固定 ALPN `h3` 并通过 HTTP/3(`POST https://hysteria/auth`)鉴权;TCP 走 QUIC 双向流,UDP 走 QUIC datagram。 + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `password` | `string` | 是 | — | 单用户明文密码(仅在 `users` 为空时生效)。 | +| `users` | `list[InboundUser]` | 否 | `[]` | 多用户列表(非空时替代 `password`)。 | +| `certificate` | `string` | 否 | 自动生成 `localhost` 自签证书 | PEM 证书链路径或内联 PEM,须与 `private-key` 成对配置。 | +| `private-key` | `string` | 否 | 自动生成 `localhost` 自签私钥 | PEM 私钥路径或内联 PEM,须与 `certificate` 成对配置。 | + +```yaml +listeners: + - name: hy2-server + type: hysteria2 + listen: 0.0.0.0 + port: 8443 + allow-lan: true + password: "default-password" + certificate: certs/fullchain.pem + private-key: certs/privkey.pem + users: + - name: alice + password: "alice-hy2-password" +``` diff --git a/docs/zh/config/inbounds/socks.md b/docs/zh/config/inbounds/socks.md new file mode 100644 index 0000000..6568b0b --- /dev/null +++ b/docs/zh/config/inbounds/socks.md @@ -0,0 +1,45 @@ +# SOCKS5 入站 + +`socks` 入站实现完整 SOCKS5(`RFC 1928`),支持 TCP `CONNECT`、UDP `UDP_ASSOCIATE` 及可选用户名/密码认证(`RFC 1929`)。 + +- **平台 / 特性**:全平台内置。 +- **认证**:复用顶层 `authentication`(`username:password` 格式)。 +- **独有字段**: + - `udp`(`bool`,可选,默认 `true`):配置字段兼容;运行时 SOCKS5 握手中的 `UDP_ASSOCIATE` 始终开启(不额外占用固定 UDP 端口)。 + +=== "顶层端口简写" + + ```yaml + socks-port: 7891 + bind-address: 127.0.0.1 + allow-lan: false + authentication: + - "alice:secret123" + ``` + +=== "命名监听器" + + ```yaml + listeners: + - name: socks-in + type: socks + listen: 127.0.0.1 + port: 7891 + allow-lan: false + udp: true + ``` + +## 规则匹配与验证 + +可在 `rules` 中使用 `IN-TYPE,SOCKS,`(或 `SOCKS5`)匹配该入站流量: + +```yaml +rules: + - IN-TYPE,SOCKS,PROXY +``` + +使用 `curl` 验证连通性: + +```bash +curl --socks5-hostname 127.0.0.1:7891 https://example.com +``` diff --git a/docs/zh/config/inbounds/transparent.md b/docs/zh/config/inbounds/transparent.md new file mode 100644 index 0000000..5223ea7 --- /dev/null +++ b/docs/zh/config/inbounds/transparent.md @@ -0,0 +1,68 @@ +# 透明代理入站(TProxy 与 Redir) + +除 [TUN](../tun.md) 之外,ClashRS 还支持基于内核转发的 **TProxy**(TCP + UDP)与 **Redir**(TCP)透明代理入站。 + +## TProxy 入站(`type: tproxy`) + +- **支持平台**:**仅 Linux 与 Android**(其他平台启用时会打印警告并跳过)。 +- **编译特性**:`tproxy`(默认 `standard` 构建已启用)。 +- **传输层**:TCP 与 UDP(依赖 `IP_TRANSPARENT`)。 +- **类型别名**:同时支持 `type: tproxy` 与 `type: t-proxy`。 + +### 独有字段 + +除通用监听器字段(`name`、`listen`、`port`、`allow-lan`、`fw-mark`)外: + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `udp` | `bool` | `true` | 配置字段兼容;运行时 `TproxyInbound` 始终处理 UDP。 | +| `dns-hijack` | `bool` | `true` | 是否劫持经由 TProxy 的 UDP DNS 流量交由内置 DNS 解析。 | + +=== "顶层端口简写" + + ```yaml + tproxy-port: 7893 + routing-mark: 6666 + ``` + +=== "命名监听器" + + ```yaml + listeners: + - name: tproxy-in + type: tproxy + listen: 0.0.0.0 + port: 7893 + udp: true + dns-hijack: true + fw-mark: 6666 + ``` + +!!! tip "Linux 路由防环" + 务必配置顶层 `routing-mark`(或 `fw-mark`),并在 `iptables` / `nftables` 的 `TPROXY` 规则中跳过带有该标记的数据包,避免 ClashRS 自身发出的出站流量再次回流至 `tproxy-port`。 + +## Redir 入站(`type: redir`) + +- **支持平台**:**仅 Linux**(依赖 `SO_ORIGINAL_DST` / `IP6T_SO_ORIGINAL_DST`)。 +- **编译特性**:`redir`(默认 `standard` 构建已启用)。 +- **传输层**:仅 TCP。 +- **独有字段**:除通用监听器字段外无额外字段。 + +=== "顶层端口简写" + + ```yaml + redir-port: 7892 + routing-mark: 6666 + ``` + +=== "命名监听器" + + ```yaml + listeners: + - name: redir-in + type: redir + listen: 0.0.0.0 + port: 7892 + allow-lan: true + fw-mark: 6666 + ``` diff --git a/docs/zh/config/inbounds/tunnel.md b/docs/zh/config/inbounds/tunnel.md new file mode 100644 index 0000000..83da459 --- /dev/null +++ b/docs/zh/config/inbounds/tunnel.md @@ -0,0 +1,65 @@ +# 端口转发入站(Tunnel) + +Tunnel 入站可将本地端口收到的 TCP 和/或 UDP 流量直接转发到固定的目标地址 `target`。 + +- **平台 / 特性**:全平台内置。 +- **路由行为**: + - 指定 `proxy`(出站节点或代理组名,支持 `DIRECT`、`REJECT`、`GLOBAL` 以及运行时动态查找的 Provider 节点)时,在任意 `mode` 下均强制走该出站;若目标出站不可用,流量会被丢弃。 + - 省略 `proxy`(或为空字符串)时,走正常的路由规则分发。 + +## 顶层 `tunnels` 简写 + +顶层 `tunnels` 同时支持对象映射格式与逗号分隔字符串格式: + +```yaml +tunnels: + - network: [tcp, udp] + address: 127.0.0.1:1053 + target: 192.0.2.53:53 + proxy: DIRECT + - "tcp,127.0.0.1:8443,example.org:443" + - "tcp/udp,127.0.0.1:5353,1.1.1.1:53,PROXY" +``` + +### 映射字段 + +| YAML 键名 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| `network` | `list["tcp" \| "udp"]` | 是 | 非空协议列表(`tcp`、`udp`)。 | +| `address` | `string` | 是 | 本地监听 `host:port`(空主机或 `*` 解析为 `0.0.0.0`,`localhost` 解析为 `127.0.0.1`)。 | +| `target` | [`SocksAddr`](../types.md#socksaddr) | 是 | 固定转发目标 `host:port`(端口不能为 `0`)。 | +| `proxy` | `string` | 否 | 固定出站或代理组名;省略则走常规规则路由。 | + +### 字符串格式 + +```text +network,address,target[,proxy] +``` + +- `network` 用 `/` 分隔多协议(如 `tcp`、`udp`、`tcp/udp`)。 +- 相同 `(listen, port, transport)` 重复定义会报配置错误。 +- 生成的监听器名形如 `tunnel--`,`allow-lan` 自动设为 `!listen.ip().is_loopback()`,`fw-mark` 继承顶层 `routing-mark`。 + +## 命名监听器写法(`listeners` + `type: tunnel`) + +也可将 `address` 拆分为 `listen` 与 `port`,作为命名监听器配置: + +```yaml +listeners: + - name: dns-tunnel + type: tunnel + listen: 127.0.0.1 + port: 1053 + network: + - tcp + - udp + target: 192.0.2.53:53 + proxy: DIRECT +``` + +| YAML 键名 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| `name`、`type`、`listen`、`port`、`fw-mark` | 通用字段 | 是(`fw-mark` 可选) | 标准监听器字段(`type: tunnel`)。 | +| `network` | `list["tcp" \| "udp"]` | 是 | 监听协议列表(大小写不敏感)。 | +| `target` | [`SocksAddr`](../types.md#socksaddr) | 是 | 固定目标 `host:port`。 | +| `proxy` | `string` | 否 | 固定出站名;省略则走常规路由。 | diff --git a/docs/zh/config/index.md b/docs/zh/config/index.md new file mode 100644 index 0000000..f424f99 --- /dev/null +++ b/docs/zh/config/index.md @@ -0,0 +1,113 @@ +# 配置概览与基础设置 + +ClashRS 使用单个 YAML 配置文件(默认位于工作目录 `-d` 下的 `config.yaml`)。在反序列化之前,ClashRS 会自动展开标准 YAML 锚点与合并键(`<<: *anchor`)。 + +默认情况下,ClashRS 会静默忽略未知的 YAML 字段,以方便直接加载 Mihomo 或其他 Clash 客户端的配置;如需严格排查字段拼写或不支持的选项,请在命令行加上 `--strict-config`。 + +## 顶层配置区块 + +| 配置段 | 说明 | 详细文档 | +| --- | --- | --- | +| 基础与控制字段 | 端口简写、绑定、模式、日志、IPv6、GeoData、`hosts`、`profile`、`experimental`、外部控制 | 本页 | +| `dns` | 内置防污染 DNS、Fake-IP、分流策略与本地 DNS 服务 | [DNS 解析与服务](dns.md) | +| `tun` | 跨平台 TUN 虚拟网卡透明代理 | [TUN 虚拟网卡](tun.md) | +| `listeners` / `tunnels` / `inbound-providers` | 多协议入站监听器与固定端口转发 | [入站代理](inbounds/index.md) | +| `proxies` | 出站代理节点列表 | [出站代理](outbounds/index.md) | +| `proxy-groups` | 手动选择、自动测速、故障转移、负载均衡、链式代理与智能选路 | [代理组](proxy-groups.md) | +| `rules` | 流量分流规则 | [路由规则](rules.md) | +| `proxy-providers` / `rule-providers` | 远程、本地文件及内联节点/规则提供者 | [提供者(Providers)](providers.md) | + +## 基础配置项 + +### 入站端口简写与网络 + +| YAML 键名 | 别名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `port` | `http_port` | [`Port`](types.md#port) | 无 | HTTP 代理端口(自动映射为监听器 `HTTP-IN`)。 | +| `socks-port` | — | [`Port`](types.md#port) | 无 | SOCKS5 代理端口,默认开启 UDP(映射为 `SOCKS-IN`)。 | +| `mixed-port` | — | [`Port`](types.md#port) | 无 | HTTP + SOCKS5 混合端口,默认开启 UDP(映射为 `MIXED-IN`)。 | +| `redir-port` | — | [`Port`](types.md#port) | 无 | Linux TCP Redirect 透明代理端口(需 `redir` 特性,映射为 `REDIR-IN`)。 | +| `tproxy-port` | — | [`Port`](types.md#port) | 无 | Linux / Android TProxy 透明代理端口(需 `tproxy` 特性,映射为 `TPROXY-IN`)。 | +| `authentication` | — | `list[string]` | `[]` | `http`、`socks`、`mixed` 入站认证凭据,格式为 `"username:password"`(按首个 `:` 拆分,无 `:` 时密码为空)。 | +| `allow-lan` | — | `bool` | `false` | 是否允许非本机地址接入。为 `false` 时,入站监听器要求 `peer_addr.ip() == local_addr.ip()`。 | +| `bind-address` | — | [`BindAddress`](types.md#bindaddress) | `0.0.0.0`(未修改且 `ipv6: true` 时自动升级为 `::`) | 顶层端口简写的监听地址,支持 `*`、`localhost`、`::`、`[::]` 或具体 IP。 | +| `mode` | — | `rule` \| `global` \| `direct` | `rule` | 路由模式(亦接受首字母大写 `Rule`、`Global`、`Direct`)。 | +| `log-level` | — | `trace` \| `debug` \| `info` \| `warning`(`warn`)\| `error` \| `silent`(`off`) | `info` | 日志输出级别;若环境变量 `RUST_LOG` 有效则由其覆盖。 | +| `unified-delay` | — | `bool` | `false` | 在已建立的 HTTP 连接上执行二次测速,排除握手开销。 | +| `ipv6` | — | `bool` | `false` | 全局 IPv6 开关。影响默认 `bind-address` 升级为 `::`、DNS 实际 IPv6 开关(`config.ipv6 && dns.ipv6`)以及 Mihomo TUN 模式自动分配 `gateway-v6`。 | +| `interface` | `interface-name` | `string` | 无 | 启用 TUN 时的默认物理出站网卡名或 IP 地址。 | +| `routing-mark` | — | [`SocketMark`](types.md#socketmark) | 无 | Linux(及启用 `tproxy` 的 Android)出站 socket 路由标记(`SO_MARK`)。未设 `tun.so-mark` 时由 TUN 继承,DNS 客户端也会继承。 | + +### 外部控制与 Web 面板 + +| YAML 键名 | 别名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `external-controller` | — | `string` | 无 | REST API TCP 监听地址(如 `127.0.0.1:9090`;`:9090` 自动补全为 `127.0.0.1:9090`)。绑定非回环地址时,必须同时配置非空 `secret` 和 CORS 来源。 | +| `external-controller-ipc` | `external-controller-unix`(Unix)、`external-controller-pipe`(Windows) | `string` | 无 | Unix Domain Socket 路径或 Windows Named Pipe(如 `\\.\pipe\clash-rs`),可与 TCP 同时启用,可被 `--controller-ipc` 覆盖。 | +| `external-ui` | — | `string` | 无 | 外部 Web 面板目录(相对 `-d`),通过 `/ui/` 提供静态文件;为空或不存在时回退至内置面板。 | +| `external-ui-url` | — | `string` | 无 | 当 `external-ui` 为空时自动下载并解压的压缩包 URL(`.zip`/`.tgz`)。支持 `#force=true` 与 `#_clash_outbound=`。 | +| `secret` | — | `string` | 无 | TCP 控制接口鉴权密钥(`Authorization: Bearer ` 或 WebSocket `?token=`);IPC 不使用该鉴权。 | +| `external-controller-cors` | — | 对象 | 无 | CORS 策略,包含 `allow-origins: list[string]` 与 `allow-private-network: bool`(默认 `true`)。 | +| `cors-allow-origins` | — | `list[string]` | 无 | `external-controller-cors.allow-origins` 的旧版回退字段。 | + +```yaml +external-controller: 0.0.0.0:9090 +secret: "strong-random-secret" +external-controller-cors: + allow-origins: + - "https://metacubex.github.io" + - "http://127.0.0.1:9090" + allow-private-network: true +``` + +### GeoData 与静态 Hosts + +所有 GeoData 路径均相对 `-d` 解析(受 [安全路径](../guides/compatibility.md#safe-paths) 限制),**仅在显式配置路径时(或 `--compatibility` 模式下自动补全默认路径时)才会加载或自动下载**。 + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `mmdb` | `string` | 无(`--compatibility` 下默认 `Country.mmdb`) | 国家 GeoIP MMDB 文件路径,供 `GEOIP` 规则与 `dns.fallback-filter.geoip` 使用。 | +| `mmdb-download-url` | `string` | `https://github.com/Loyalsoldier/geoip/releases/latest/download/Country.mmdb` | `mmdb` 缺失或调用 `POST /configs/geo` 时使用的下载地址。 | +| `asn-mmdb` | `string` | 无 | ASN MMDB 数据库路径。 | +| `asn-mmdb-download-url` | `string` | `https://git.io/GeoLite2-ASN.mmdb` | `asn-mmdb` 下载地址。 | +| `geosite` | `string` | 无(`--compatibility` 下默认 `geosite.dat`) | GeoSite 数据库路径,供 `GEOSITE` 规则使用。 | +| `geosite-download-url` | `string` 或 `list[string]` | Loyalsoldier `v2ray-rules-dat`(jsDelivr + GitHub 镜像列表) | 单个 URL 或按优先级尝试的非空镜像列表。 | +| `hosts` | `map[域名 -> IP]` | `{}` | 静态域名到单个 IP 的映射(仅当 `dns.use-hosts: true` 生效;`localhost -> 127.0.0.1` 始终内置)。 | + +### `profile` + +控制工作目录 `-d` 内的本地持久化缓存: + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `store-selected` | `bool` | `true` | 将 `select` 代理组的选择结果持久化至 `cache.db`(`--compatibility` 模式下为 `clash-rs-cache.db`)。 | +| `store-fake-ip` | `bool` | `false` | 是否将 Fake-IP 映射表持久化至磁盘;为 `false` 时使用容量为 1,000 的内存存储。 | +| `store-smart-stats` | `bool` | `true` | 每 30 秒将 `smart` 代理组的评分统计数据持久化到缓存。 | + +```yaml +profile: + store-selected: true + store-fake-ip: false + store-smart-stats: true +``` + +### `experimental` + +实验性缓冲区与运行时调优参数: + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `tcp-buffer-size` | `usize`(字节) | `65536`(64 KiB) | TCP 双向转发拷贝缓冲区大小。 | +| `anytls-duplex-buffer-size` | `usize`(字节) | `16384`(16 KiB) | AnyTLS 内部 duplex 管道缓冲区大小。 | +| `anytls-relay-buffer-size` | `usize`(字节) | `4096`(4 KiB) | AnyTLS 中继读缓冲区大小。 | +| `closed-flows-cap` | `usize` | `50` | `/flows` 接口保留的已关闭流环形缓冲区条数上限。 | +| `ignore-resolve-fail` | `bool` | `false` | 为兼容配置保留的字段(当前运行时未读取)。 | + +## 不支持的 Mihomo / Clash 顶层字段 + +以下其他 Clash 分支常见的顶层字段在 ClashRS 中**未定义**(普通模式静默忽略,`--strict-config` 下报错): + +- `geodata-mode`、`geodata-loader`、`geox-url` +- `fwmark`(请使用 `routing-mark`) +- `skip-auth-prefixes`、`lan-allowed-ips`、`lan-disallowed-ips` +- `sniffer`、`ntp`、`sub-rules`、`script`、`find-process-mode`、`global-client-fingerprint`、`ebpf` diff --git a/docs/zh/config/outbounds/index.md b/docs/zh/config/outbounds/index.md new file mode 100644 index 0000000..85746f7 --- /dev/null +++ b/docs/zh/config/outbounds/index.md @@ -0,0 +1,57 @@ +# 出站代理概览 + +出站代理在顶层 `proxies` 列表中定义(或通过 [`proxy-providers`](../providers.md#proxy-providers) 动态加载),每个节点必须拥有全局唯一的 `name`。 + +系统会自动注册内置出站 **`DIRECT`** 与 **`REJECT`**,用户配置中不可定义同名节点。 + +## 支持的全部出站协议(共 16 种) + +| `type` | 传输层 / 特点 | 默认 UDP | `connect-via` 支持 | 所需编译特性 | 详细文档 | +| --- | --- | --- | --- | --- | --- | +| `direct` | 直连出口 | 恒为 `true` | TCP | 内置 | 本页 | +| `reject` | 拒绝连接 | `false` | 全部 | 内置 | 本页 | +| `ss` | 原生、`obfs`、`v2ray-plugin`(WS)、`shadow-tls` v3 | `true` | TCP + UDP | `shadowsocks`(`standard`) | [Shadowsocks](shadowsocks.md) | +| `trojan` | TLS、WS、gRPC、mTLS | `false` | TCP + UDP | 内置 | [Trojan / VMess / VLESS](v2ray.md) | +| `vmess` | TCP、TLS、WS、H2、gRPC、XHTTP、mTLS | `true` | TCP + UDP | 内置 | [Trojan / VMess / VLESS](v2ray.md) | +| `vless` | TCP、TLS、WS、H2、gRPC、XHTTP、REALITY、Vision、mTLS | `true` | TCP + UDP | 内置 | [Trojan / VMess / VLESS](v2ray.md) | +| `tuic` | QUIC v5(`bbr`/`bbr3`/`cubic`/`new_reno`)、mTLS | 恒为 `true` | 不支持 | `tuic`(`standard`) | [TUIC](tuic.md) | +| `hysteria2` | QUIC、端口跳跃、Salamander 混淆、mTLS | 服务端协商 | 无此字段 | 内置 | [Hysteria2 与 ShadowQUIC](quic.md) | +| `shadowquic` | QUIC / over-stream、JLS、brutal/bbr/bbr3 | 恒为 `true` | 不支持 | `shadowquic`(`standard`) | [Hysteria2 与 ShadowQUIC](quic.md) | +| `anytls` | TLS + UoT v2、mTLS | `false` | TCP + UDP | 内置 | [AnyTLS / Naive / SOCKS5](tls-socks.md) | +| `naive` | HTTP/2 或 QUIC(Cronet)+ UoT v2 | `false` | 显式拒绝报错 | `naive`(**默认未启用**) | [AnyTLS / Naive / SOCKS5](tls-socks.md) | +| `socks5` | 明文 TCP 或 TLS + UDP | `true` | TCP + UDP | 内置 | [AnyTLS / Naive / SOCKS5](tls-socks.md) | +| `wireguard` | 用户态 BoringTun(IPv4/IPv6) | `false` | 不支持 | `wireguard`(`standard`) | [WireGuard / SSH / Tailscale / Tor](vpn.md) | +| `ssh` | SSH 隧道(密码、私钥、host-key、TOTP) | `false` | TCP | `ssh`(`standard`) | [WireGuard / SSH / Tailscale / Tor](vpn.md) | +| `tailscale` | Tailnet / Headscale 组网 | 恒为 `true` | 不支持 | `tailscale`(`standard`) | [WireGuard / SSH / Tailscale / Tor](vpn.md) | +| `tor` | Tor 洋葱路由 | `false` | 不支持 | `onion`(`plus` 构建) | [WireGuard / SSH / Tailscale / Tor](vpn.md) | + +!!! warning "不支持的出站类型与单节点字段" + - **不支持的类型**:不支持 `http` 出站、`snell` 与 `ssr`(YAML 解析阶段直接报错)。 + - **不存在的单节点字段**:没有 `smux`、`ip-version` 或独立 `shadow-tls-opts`(ShadowTLS 通过 `ss` 的 `plugin: shadow-tls` 配置)。单节点 `interface` / `routing-mark` 仅 `tor` 出站支持;其他协议请使用顶层 `interface` / `routing-mark` 或路由规则修饰符 `interface=`。 + +## 通用出站字段(`CommonConfigOptions`) + +适用于 `ss`、`socks5`、`anytls`、`trojan`、`vmess`、`vless`、`wireguard`、`tuic`、`naive`、`ssh` 与 `shadowquic`: + +| YAML 键名 | 别名 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | --- | +| `name` | — | `string` | 是 | 全局唯一代理名称。 | +| `server` | — | `string` | 是 | 服务器域名或 IP。 | +| `port` | — | `u16` | 是 | 服务器端口(整数)。 | +| `connect-via` | `dialer-proxy` | `string` | 否 | 前置代理或代理组名(不能引用仅存在于 `proxy-provider` 中的节点名)。 | + +## 内置 `direct` 与 `reject` + +除自动注册的 `DIRECT` 与 `REJECT` 外,也可以定义自定义别名: + +```yaml +proxies: + - name: my-direct + type: direct + - name: my-reject + type: reject +``` + +## 客户端双向认证(mTLS) + +`anytls`、`trojan`、`vmess`、`vless`(非 REALITY)、`tuic` 与 `hysteria2` 均支持通过 `tls-cert` 与 `tls-key` 配置 mTLS 客户端证书(支持文件路径或内联 PEM,须成对提供)。详见 [TLS 证书与私钥](../types.md#tls-certificates)。 diff --git a/docs/zh/config/outbounds/quic.md b/docs/zh/config/outbounds/quic.md new file mode 100644 index 0000000..cd78656 --- /dev/null +++ b/docs/zh/config/outbounds/quic.md @@ -0,0 +1,87 @@ +# Hysteria2 与 ShadowQUIC 出站 + +## Hysteria2(`type: hysteria2`) + +- **编译特性**:全平台内置。 +- **UDP**:由服务端认证响应头 `Hysteria-UDP` 动态决定(建连前默认 `true`)。 +- **`connect-via`**:配置结构不含该字段。 + +### 字段 + +| YAML 键名 | 别名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | --- | +| `name` | — | `string` | 是 | — | 全局唯一节点名。 | +| `server` | — | `string` | 是 | — | 服务器域名或 IP。 | +| `port` | — | `u16` | 是 | — | 主 UDP 端口。 | +| `password` | — | `string` | 是 | — | Hysteria2 认证密码。 | +| `skip-cert-verify` | — | `bool` | **是** | 无 | **必须在 YAML 中显式填写**(`true` 或 `false`),该字段无默认值。 | +| `ports` | — | `string` | 否 | 无 | 端口跳跃范围/列表(如 `"20000-30000,40000"`)。 | +| `hop-interval` | `hop_interval` | `u64`(秒) | 否 | `30` | 端口跳跃间隔。 | +| `obfs` | — | `"salamander"` | 否 | 无 | 混淆类型;设置时 `obfs-password` 必填。 | +| `obfs-password` | — | `string` | 设置 `obfs` 时必填 | 无 | Salamander 混淆密码。 | +| `sni` | — | `string` | 否 | `server` | TLS SNI。 | +| `alpn` | — | `list[string]` | 否 | `["h3"]` | TLS ALPN 列表。 | +| `fingerprint` | — | `string` | 否 | 无 | 服务端证书 SHA-256 十六进制指纹固定校验。 | +| `udp-mtu` | — | `u32` | 否 | 无 | 自定义 UDP MTU。 | +| `disable-mtu-discovery` | — | `bool` | 否 | `false` | 是否禁用 QUIC PMTU 探测。 | +| `tls-cert`、`tls-key` | — | `string` | 否 | 无 | 成对的 mTLS 客户端证书与私钥。 | + +!!! note "仅保留解析、运行时未生效的字段" + `ca`(会打印警告)、`ca-str`、`up`、`down`、`cwnd` 仅为兼容外部配置而允许解析,当前运行时不会生效。 + +```yaml +proxies: + - name: hy2-node + type: hysteria2 + server: hy2.example.com + port: 443 + ports: "20000-30000" + hop-interval: 30 + password: "your-hy2-password" + obfs: salamander + obfs-password: "your-obfs-password" + sni: hy2.example.com + skip-cert-verify: false +``` + +--- + +## ShadowQUIC(`type: shadowquic`) + +- **编译特性**:`shadowquic`(默认 `standard` 构建已启用)。 +- **UDP**:始终支持(默认 QUIC datagram,设 `over-stream: true` 时改用 QUIC stream)。 +- **`connect-via`**:运行时忽略。 + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`server`、`port` | 通用字段 | 是 | — | 标准出站选项。 | +| `username` | `string` | 是 | — | JLS 用户名。 | +| `password` | `string` | 是 | — | JLS 密码。 | +| `server-name` | `string` | 是 | — | JLS 上游伪装域名(SNI)。 | +| `alpn` | `list[string]` | 否 | `["h3"]` | TLS ALPN 列表。 | +| `initial-mtu` | `u16` | 否 | `1300` | 初始 QUIC MTU(最小 `1200`)。 | +| `min-mtu` | `u16` | 否 | `1290` | 最小 QUIC MTU(最小 `1200`)。 | +| `congestion-control` | 字符串或对象 | 否 | `"bbr"` | 支持 `"bbr"`、`"cubic"`、`"new-reno"`、`"bbr3"`,或对象形式 `brutal: { bandwidth, min-window, cwnd-gain, min-ack-rate, min-sample-count, ack-compensate }`。 | +| `zero-rtt` | `bool` | 否 | `true` | 是否启用 QUIC 0-RTT。 | +| `over-stream` | `bool` | 否 | `false` | `true` 时通过 QUIC 流转发 UDP,`false` 时使用 QUIC datagram。 | +| `keep-alive-interval` | `u32`(毫秒) | 否 | `0`(禁用) | QUIC 保活间隔。 | +| `gso` | `bool` | 否 | `true` | 是否启用 UDP GSO 分片卸载。 | +| `mtu-discovery` | `bool` | 否 | `true` | 是否启用 QUIC 路径 MTU 探测。 | + +```yaml +proxies: + - name: sq-node + type: shadowquic + server: sq.example.com + port: 443 + username: "jls-user" + password: "jls-password" + server-name: www.example.org + alpn: + - h3 + congestion-control: bbr3 + zero-rtt: true + over-stream: false +``` diff --git a/docs/zh/config/outbounds/shadowsocks.md b/docs/zh/config/outbounds/shadowsocks.md new file mode 100644 index 0000000..d3732e9 --- /dev/null +++ b/docs/zh/config/outbounds/shadowsocks.md @@ -0,0 +1,108 @@ +# Shadowsocks 出站(`type: ss`) + +支持经典 AEAD 加密、Shadowsocks 2022 BLAKE3 加密,以及 `obfs`、`v2ray-plugin` 和 `shadow-tls` v3 插件。 + +- **编译特性**:`shadowsocks`(默认 `standard` 构建已启用)。 +- **`connect-via` / `dialer-proxy`**:支持 TCP 与 UDP。 + +## 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`server`、`port`、`connect-via`(`dialer-proxy`) | 通用字段 | 是(`connect-via` 可选) | — | 标准出站选项。 | +| `cipher` | `string` | 是 | — | 加密算法(见下方支持列表)。 | +| `password` | `string` | 是 | — | 密码或 SS2022 Base64 PSK。 | +| `udp` | `bool` | 否 | `true` | 是否启用 UDP 转发。 | +| `plugin` | `string` | 否 | 无 | 可选 `"obfs"`、`"v2ray-plugin"` 或 `"shadow-tls"`;设置时必须提供 `plugin-opts`。 | +| `plugin-opts` | map | 设置 `plugin` 时必填 | 无 | 插件专属参数(见下文)。 | + +## 支持的加密方式 { #supported-ciphers } + +ClashRS 精确支持以下 8 种加密方式: + +- `aes-128-gcm` +- `aes-256-gcm` +- `chacha20-ietf-poly1305` +- `xchacha20-ietf-poly1305` +- `2022-blake3-aes-128-gcm` +- `2022-blake3-aes-256-gcm` +- `2022-blake3-chacha20-ietf-poly1305` +- `rc4-md5` + +## 插件配置 + +=== "shadow-tls(v3)" + + | `plugin-opts` 键名 | 类型 | 必填 | 默认值 | 说明 | + | --- | --- | --- | --- | --- | + | `password` | `string` | 是 | — | ShadowTLS v3 密码。 | + | `host` | `string` | 否 | `"bing.com"` | TLS 握手 SNI 主机名。 | + | `strict` | `bool` | 否 | `true` | 是否开启严格模式。 | + + ```yaml + proxies: + - name: ss-shadowtls + type: ss + server: proxy.example.com + port: 443 + cipher: 2022-blake3-aes-128-gcm + password: "BASE64_PSK" + udp: true + plugin: shadow-tls + plugin-opts: + host: www.example.org + password: "shadowtls-password" + strict: true + ``` + +=== "v2ray-plugin" + + | `plugin-opts` 键名 | 类型 | 必填 | 默认值 | 说明 | + | --- | --- | --- | --- | --- | + | `mode` | `string` | 是 | — | 仅支持 `"websocket"`。 | + | `host` | `string` | 否 | `"bing.com"` | WebSocket `Host` 头与 TLS SNI。 | + | `path` | `string` | 否 | `""`(发包自动转为 `"/"`) | WebSocket 路径。 | + | `tls` | `bool` | 否 | `false` | 是否启用 TLS。 | + | `port` | `u16` | 否 | `tls` 为 `true` 时 `443`,否则 `80` | 仅用于 WebSocket Upgrade `Host` 头。 | + | `skip-cert-verify` | `bool` | 否 | `false` | 是否跳过证书校验。 | + | `headers` | map | 否 | `{}` | 附加请求头(未包含 `Host` 时自动补全)。 | + | `mux` | `bool` | 否 | `false` | **设为 `true` 会直接报错**(不支持 mux)。 | + + ```yaml + proxies: + - name: ss-v2ray-ws + type: ss + server: proxy.example.com + port: 443 + cipher: aes-256-gcm + password: "password" + plugin: v2ray-plugin + plugin-opts: + mode: websocket + tls: true + host: ws.example.com + path: /ws + ``` + +=== "obfs(已弃用)" + + 启动时会输出弃用警告。 + + | `plugin-opts` 键名 | 类型 | 必填 | 默认值 | 说明 | + | --- | --- | --- | --- | --- | + | `mode` | `"http"` \| `"tls"` | 是 | — | 混淆模式。 | + | `host` | `string` | 否 | `"bing.com"` | 伪装的 HTTP / TLS 主机名。 | + + ```yaml + proxies: + - name: ss-obfs + type: ss + server: proxy.example.com + port: 8388 + cipher: aes-256-gcm + password: "password" + plugin: obfs + plugin-opts: + mode: tls + host: www.example.com + ``` diff --git a/docs/zh/config/outbounds/tls-socks.md b/docs/zh/config/outbounds/tls-socks.md new file mode 100644 index 0000000..4b2bb4b --- /dev/null +++ b/docs/zh/config/outbounds/tls-socks.md @@ -0,0 +1,111 @@ +# AnyTLS / Naive / SOCKS5 出站 + +## AnyTLS(`type: anytls`) + +- **编译特性**:全平台内置。 +- **`connect-via`**:支持 TCP 与 UDP。 + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`server`、`port`、`connect-via` | 通用字段 | 是(`connect-via` 可选) | — | 标准出站选项。 | +| `password` | `string` | 是 | — | AnyTLS 密码。 | +| `sni` | `string` | 否 | `server` | TLS SNI。 | +| `alpn` | `list[string]` | 否 | `["h2", "http/1.1"]` | TLS ALPN 列表。 | +| `skip-cert-verify` | `bool` | 否 | `false` | 是否跳过 TLS 证书校验。 | +| `udp` | `bool` | 否 | `false` | 是否通过 UoT v2 启用 UDP 转发。 | +| `tls-cert`、`tls-key` | `string` | 否 | 无 | 成对的 mTLS 客户端证书与私钥。 | + +!!! note "仅保留解析、运行时未生效的字段" + `fingerprint`、`client-fingerprint`、`idle-session-check-interval`、`idle-session-timeout`、`min-idle-session` 允许解析但会打印警告且运行时不生效。 + +```yaml +proxies: + - name: anytls-node + type: anytls + server: anytls.example.com + port: 443 + password: "your-anytls-password" + sni: anytls.example.com + udp: true +``` + +--- + +## Naive(`type: naive`) + +基于 Wind + Chromium Cronet,支持 HTTP/2 与 QUIC 传输及可选 UDP over TCP(UoT v2)。 + +- **编译特性**:`naive`(**默认与 `standard` 构建均未启用**)。在受支持平台上可直接拉取静态 Cronet 编译: + +```bash +cargo build --locked --release -p clash-rs --features naive-static,naive-download +``` + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`server`、`port` | 通用字段 | 是(`port > 0`) | — | 标准出站选项(IPv6 字面量允许带方括号如 `[::1]`)。**设置 `connect-via` / `dialer-proxy` 会直接报 `InvalidConfig` 错误。** | +| `username` | `string` | 是 | — | 非空用户名,且**不能包含冒号 `:`**。 | +| `password` | `string` | 是 | — | 非空密码。 | +| `quic` | `bool` | 否 | `false` | `false` 使用 HTTP/2,`true` 使用 QUIC。 | +| `udp` | `bool` | 否 | `false` | 启用 UDP over TCP(UoT v2,需服务端支持)。 | +| `concurrency` | `u32` | 否 | `1` | 连接并发度(必须 `> 0`)。 | +| `congestion-controller` | `"default"` \| `"bbr"` \| `"bbrv2"` \| `"cubic"` \| `"reno"` | 否 | `"default"` | 拥塞控制算法。 | +| `request-timeout` | `u64`(毫秒) | 否 | `10000` | 请求超时(必须 `> 0`)。 | +| `ca-cert` | `string` | 否 | 无 | 自定义 CA / 自签 PEM 证书(文件路径或内联 PEM;在 `proxy-providers` 中**仅允许内联 PEM**)。 | +| `cronet-lib-path` | `string` | 否 | 无 | 动态链接构建时指定 `libcronet` 共享库路径或库名。**仅允许在主配置中设置**(`proxy-providers` 与 `--service-mode` 中禁止);整个进程内所有 Naive 节点共用首次加载的库,修改后需重启进程。 | +| `skip-cert-verify` | `bool` | 否 | `false` | **设为 `true` 会直接报错拒绝**;自签证书请使用 `ca-cert`。 | +| `sni` | `string` | 否 | 无 | **若显式设置,必须忽略大小写等于 `server` 主机名**,否则校验报错。 | + +### 运行说明 + +- 启用 TUN 时,Naive 在 Linux、macOS 与 Windows 上支持绑定出站网卡,在 Linux 上支持 `routing-mark`(Android 忽略这两项)。 +- 若代理域名无法解析,请配置 `dns.proxy-server-nameserver` 或将其加入 `dns.fake-ip-filter`。 +- 配置热重载或 Provider 更新替换 Naive 节点后,旧节点释放时会关闭其活跃 TCP/UDP 会话。 + +```yaml +proxies: + - name: naive-h2 + type: naive + server: naive.example.com + port: 443 + username: "your-username" + password: "your-password" + quic: false + udp: true + concurrency: 2 +``` + +--- + +## SOCKS5(`type: socks5`) + +- **编译特性**:全平台内置。 +- **`connect-via`**:支持 TCP 与 UDP。 + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`server`、`port`、`connect-via` | 通用字段 | 是(`connect-via` 可选) | — | 标准出站选项。 | +| `username` | `string` | 否 | 无 | SOCKS5 用户名。 | +| `password` | `string` | 否 | 无 | SOCKS5 密码。 | +| `tls` | `bool` | 否 | `false` | 是否为 SOCKS5 连接启用 TLS。 | +| `sni` | `string` | 否 | `server` | TLS SNI(`tls: true` 时生效)。 | +| `skip-cert-verify` | `bool` | 否 | `false` | 是否跳过 TLS 证书校验。 | +| `udp` | `bool` | 否 | `true` | 是否启用 UDP 转发(`UDP_ASSOCIATE`)。 | + +```yaml +proxies: + - name: upstream-socks + type: socks5 + server: 192.0.2.10 + port: 1080 + username: "alice" + password: "secret" + tls: false + udp: true +``` diff --git a/docs/zh/config/outbounds/tuic.md b/docs/zh/config/outbounds/tuic.md new file mode 100644 index 0000000..cdcdb4f --- /dev/null +++ b/docs/zh/config/outbounds/tuic.md @@ -0,0 +1,51 @@ +# TUIC 出站(`type: tuic`) + +基于 Wind TUIC 与 Quinn 实现的 TUIC v5(QUIC)出站协议。 + +- **编译特性**:`tuic`(默认 `standard` 构建已启用)。 +- **UDP**:始终支持(可选 `native` datagram 或 `quic` stream 模式)。 +- **`connect-via`**:允许解析但运行时忽略(QUIC 直连)。 + +## 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`server`、`port` | 通用字段 | 是 | — | 标准出站选项。 | +| `uuid` | UUID 字符串 | 是 | — | TUIC v5 UUID。 | +| `password` | `string` | 是 | — | TUIC v5 密码。 | +| `ip` | `string` | 否 | 无 | 覆盖 `server` 的 DNS 解析结果。 | +| `sni` | `string` | 否 | `server` | TLS SNI。 | +| `disable-sni` | `bool` | 否 | `false` | 握手时不发送 SNI。 | +| `alpn` | `list[string]` | 否 | `["h3"]` | TLS ALPN 列表。 | +| `skip-cert-verify` | `bool` | 否 | `false` | 是否跳过 TLS 证书校验。 | +| `udp-relay-mode` | `"native"` \| `"quic"` | 否 | `"native"` | 大小写不敏感;未知字符串回退为 `"quic"`。 | +| `congestion-controller` | `"bbr"` \| `"bbr3"` \| `"cubic"` \| `"new_reno"`(`"newreno"`) | 否 | `"bbr"` | QUIC 拥塞控制算法(大小写不敏感)。 | +| `reduce-rtt` | `bool` | 否 | `false` | 启用 QUIC 0-RTT 握手。 | +| `fast-open` | `bool` | 否 | `false` | 与 `reduce-rtt` 取逻辑或(`reduce-rtt || fast-open`)。 | +| `heartbeat-interval` | `u64`(毫秒) | 否 | `3000` | 心跳间隔。 | +| `request-timeout` | `u64`(毫秒) | 否 | `4000` | 请求超时,同时用作 QUIC 空闲超时。 | +| `max-open-stream` | `u64` | 否 | `32` | 单条 QUIC 连接最大并发流数。 | +| `gc-interval` | `u64`(毫秒) | 否 | `3000` | UDP 分片 GC 间隔。 | +| `gc-lifetime` | `u64`(毫秒) | 否 | `15000` | UDP 分片最大存活时间。 | +| `send-window` | `u64`(字节) | 否 | `16777216`(16 MiB) | QUIC 发送窗口。 | +| `receive-window` | `u64`(字节) | 否 | `8388608`(8 MiB) | QUIC 接收窗口。 | +| `max-udp-relay-packet-size` | `u64` | 否 | `1500` | 兼容保留字段(运行时未使用)。 | +| `tls-cert`、`tls-key` | `string` | 否 | 无 | 成对的 mTLS 客户端证书与私钥。 | + +## 配置示例 + +```yaml +proxies: + - name: tuic-v5 + type: tuic + server: tuic.example.com + port: 8443 + uuid: "00000000-0000-0000-0000-000000000000" + password: "your-tuic-password" + sni: tuic.example.com + alpn: + - h3 + udp-relay-mode: native + congestion-controller: bbr3 + reduce-rtt: true +``` diff --git a/docs/zh/config/outbounds/v2ray.md b/docs/zh/config/outbounds/v2ray.md new file mode 100644 index 0000000..4d705a2 --- /dev/null +++ b/docs/zh/config/outbounds/v2ray.md @@ -0,0 +1,132 @@ +# Trojan / VMess / VLESS 出站 + +这三个协议均为全平台内置(无需额外 Cargo 特性),支持 TCP 与 UDP 维度的 `connect-via`(`dialer-proxy`)前置链式代理,并支持 mTLS 客户端证书(`tls-cert` / `tls-key`)。 + +共享传输层配置块(`ws-opts`、`h2-opts`、`grpc-opts`、`xhttp-opts`、`reality-opts`)的完整字段请参阅 [通用类型与传输层](../types.md#ws-opts)。 + +--- + +## Trojan(`type: trojan`) + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`server`、`port`、`connect-via` | 通用字段 | 是(`connect-via` 可选) | — | 标准出站选项。 | +| `password` | `string` | 是 | — | Trojan 密码。 | +| `sni` | `string` | 否 | `server` | TLS SNI。 | +| `alpn` | `list[string]` | 否 | `ws` 时为 `["http/1.1"]`,其余为 `["h2", "http/1.1"]` | TLS ALPN 列表。 | +| `skip-cert-verify` | `bool` | 否 | `false` | 是否跳过 TLS 证书校验。 | +| `udp` | `bool` | 否 | `false` | 是否启用 UDP 转发。 | +| `network` | `"ws"` \| `"grpc"` | 否 | 原生 TLS/TCP | 可选底层传输协议。 | +| `ws-opts` | [`WsOpt`](../types.md#ws-opts) | `network: ws` 时必填 | 无 | WebSocket 配置。 | +| `grpc-opts` | [`GrpcOpt`](../types.md#grpc-opts) | `network: grpc` 时必填 | 无 | gRPC 配置。 | +| `tls-cert`、`tls-key` | `string` | 否 | 无 | 成对的 mTLS 客户端证书与私钥。 | + +```yaml +proxies: + - name: trojan-grpc + type: trojan + server: trojan.example.com + port: 443 + password: "your-password" + sni: trojan.example.com + udp: true + network: grpc + grpc-opts: + grpc-service-name: "trojan-service" +``` + +--- + +## VMess(`type: vmess`) + +| YAML 键名 | 别名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | --- | +| `name`、`server`、`port`、`connect-via` | `dialer-proxy` | 通用字段 | 是(`connect-via` 可选) | — | 标准出站选项。 | +| `uuid` | — | `string` | 是 | — | 标准 UUID。 | +| `alter-id` | `alterId` | `u16` | 是 | — | 设为 `0` 启用 AEAD。 | +| `cipher` | — | `string` | 强烈建议显式填写 | `""` | 仅接受 `auto`、`aes-128-gcm`、`chacha20-poly1305` 或 `none`(大小写不敏感)。**若省略,建连时会因空串报 `invalid security`**;`auto` 在 `x86_64`/`aarch64`/`s390x` 上选用 `aes-128-gcm`,其余架构选用 `chacha20-poly1305`。 | +| `udp` | — | `bool` | 否 | `true` | 是否启用 UDP 转发。 | +| `tls` | — | `bool` | 否 | `false` | 是否启用 TLS。 | +| `skip-cert-verify` | — | `bool` | 否 | `false` | 是否跳过 TLS 证书校验。 | +| `server-name` | `servername` | `string` | 否 | `ws-opts.headers.Host` → `xhttp-opts.host` → `server` | TLS SNI。 | +| `network` | — | `"ws"` \| `"h2"` \| `"grpc"` \| `"xhttp"` \| `"splithttp"` | 否 | 裸 TCP | 底层传输协议(开启 `tls: true` 时,`ws` 默认 ALPN 为 `["http/1.1"]`,`h2`/`grpc`/`xhttp`/`splithttp` 为 `["h2"]`)。 | +| `ws-opts` | — | [`WsOpt`](../types.md#ws-opts) | `network: ws` 时必填 | 无 | WebSocket 配置。 | +| `h2-opts` | — | [`H2Opt`](../types.md#h2-opts) | `network: h2` 时必填 | 无 | HTTP/2 配置。 | +| `grpc-opts` | — | [`GrpcOpt`](../types.md#grpc-opts) | `network: grpc` 时必填 | 无 | gRPC 配置。 | +| `xhttp-opts` | `splithttp-opts` | [`XhttpOpt`](../types.md#xhttp-opts) | `xhttp`/`splithttp` 时可选 | 默认 `XhttpOpt` | XHTTP / SplitHTTP 配置。 | +| `tls-cert`、`tls-key` | — | `string` | 否 | 无 | 成对的 mTLS 客户端证书与私钥。 | + +```yaml +proxies: + - name: vmess-ws-tls + type: vmess + server: vmess.example.com + port: 443 + uuid: "00000000-0000-0000-0000-000000000000" + alterId: 0 + cipher: auto + udp: true + tls: true + servername: vmess.example.com + network: ws + ws-opts: + path: /ws + headers: + Host: vmess.example.com +``` + +--- + +## VLESS(`type: vless`) + +| YAML 键名 | 别名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | --- | +| `name`、`server`、`port`、`connect-via` | `dialer-proxy` | 通用字段 | 是(`connect-via` 可选) | — | 标准出站选项。 | +| `uuid` | — | `string` | 是 | — | 标准 UUID。 | +| `udp` | — | `bool` | 否 | `true` | 是否启用 UDP 转发。 | +| `tls` | — | `bool` | 否 | `false` | 是否启用普通 TLS(若同时设置了 `reality-opts`,则走 REALITY)。 | +| `skip-cert-verify` | — | `bool` | 否 | `false` | 是否跳过证书校验。 | +| `server-name` | `servername` | `string` | 否 | 同 VMess 回退链(REALITY 回退至 `server`) | TLS / REALITY SNI。 | +| `network` | — | `"tcp"` \| `"ws"` \| `"h2"` \| `"grpc"` \| `"xhttp"` \| `"splithttp"` | 否 | `"tcp"` | 底层传输协议。 | +| `ws-opts`、`h2-opts`、`grpc-opts`、`xhttp-opts`(`splithttp-opts`) | — | 传输层块 | `ws`/`h2`/`grpc` 必填,`xhttp` 可选 | 无 | 同 VMess。 | +| `reality-opts` | — | [`RealityOpt`](../types.md#reality-opts) | 否 | 无 | 启用 TLS REALITY(`public-key`、`short-id`)。 | +| `flow` | — | `string` | 否 | 无 | 仅识别 `"xtls-rprx-vision"`(仅对 TCP 流生效,UDP 不启用 Vision)。 | +| `client-fingerprint` | — | `string` | 否 | 无 | **尚未实现**(uTLS):允许解析但运行时忽略并打印警告。 | +| `tls-cert`、`tls-key` | — | `string` | 否 | 无 | 成对的 mTLS 证书与私钥(仅非 REALITY 普通 TLS 生效)。 | + +=== "VLESS + REALITY + Vision" + + ```yaml + proxies: + - name: vless-reality + type: vless + server: reality.example.com + port: 443 + uuid: "00000000-0000-0000-0000-000000000000" + udp: true + tls: true + flow: xtls-rprx-vision + servername: www.example.org + reality-opts: + public-key: "REPLACE_WITH_32BYTE_URLSAFE_BASE64_KEY" + short-id: "0123456789abcdef" + ``` + +=== "VLESS + XHTTP" + + ```yaml + proxies: + - name: vless-xhttp + type: vless + server: xhttp.example.com + port: 443 + uuid: "00000000-0000-0000-0000-000000000000" + udp: true + tls: true + servername: xhttp.example.com + network: xhttp + xhttp-opts: + path: /xhttp + host: xhttp.example.com + x-padding-bytes: "100-1000" + ``` diff --git a/docs/zh/config/outbounds/vpn.md b/docs/zh/config/outbounds/vpn.md new file mode 100644 index 0000000..6396fd5 --- /dev/null +++ b/docs/zh/config/outbounds/vpn.md @@ -0,0 +1,135 @@ +# WireGuard / SSH / Tailscale / Tor 出站 + +## WireGuard(`type: wireguard`) + +基于 BoringTun 的用户态 WireGuard 客户端。 + +- **编译特性**:`wireguard`(默认 `standard` 构建已启用)。 +- **`connect-via`**:运行时忽略。 + +### 字段 + +| YAML 键名 | 别名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | --- | +| `name`、`server`、`port` | — | 通用字段 | 是 | — | 对端节点域名/IP 与 UDP 端口。 | +| `private-key` | — | `string` | 是 | — | Base64 编码的本地私钥。 | +| `public-key` | — | `string` | 是 | — | Base64 编码的对端公钥。 | +| `pre-shared-key` | `preshared-key` | `string` | 否 | 无 | 可选 Base64 预共享密钥。 | +| `ip` | — | IPv4 CIDR | 是 | — | 本地隧道 IPv4 CIDR(如 `10.0.0.2/32`)。 | +| `ipv6` | — | IPv6 CIDR | 否 | 无 | 本地隧道 IPv6 CIDR。 | +| `mtu` | — | `u16` | 否 | `1420` | 隧道 MTU。 | +| `udp` | — | `bool` | 否 | `false` | 是否在隧道内启用 UDP 转发。 | +| `remote-dns-resolve` | — | `bool` | 否 | `false` | 是否通过隧道向 `dns` 列表解析目标域名。 | +| `dns` | — | `list[IP]` | 否 | 无 | 隧道内 DNS 服务器 IP 列表(固定端口 53,`remote-dns-resolve: true` 时随机选取)。 | +| `allowed-ips` | — | `list[CIDR]` | 否 | `[]` | 允许的对端网段列表。 | +| `reserved-bits` | — | `list[u8]` | 否 | `[0, 0, 0]` | 3 字节 WireGuard 保留位(长度 >= 3 时取前 3 字节)。 | + +```yaml +proxies: + - name: wg-peer + type: wireguard + server: wg.example.com + port: 51820 + ip: 10.66.66.2/32 + ipv6: fd42:42:42::2/128 + private-key: "BASE64_PRIVATE_KEY" + public-key: "BASE64_PEER_PUBLIC_KEY" + mtu: 1280 + udp: true + remote-dns-resolve: true + dns: + - 1.1.1.1 + reserved-bits: [0, 0, 0] +``` + +--- + +## SSH(`type: ssh`) + +- **编译特性**:`ssh`(默认 `standard` 构建已启用)。 +- **UDP**:不支持(`false`)。 +- **`connect-via`**:支持 TCP 前置代理。 + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`server`、`port`、`connect-via` | 通用字段 | 是(`connect-via` 可选) | — | 标准出站选项。 | +| `username` | `string` | 是 | — | SSH 登录用户名。 | +| `password` | `string` | 否 | 无 | 密码认证凭据。 | +| `private-key` | `string` | 否 | 无 | 若包含 `"PRIVATE KEY"` 视为内联私钥,否则视为文件路径(支持 `~` 展开为用户主目录)。 | +| `private-key-passphrase` | `string` | 否 | 无 | 加密私钥的解密口令。 | +| `host-key` | `list[string]` | 否 | 无 | 用于固定校验服务端主机密钥的 OpenSSH 公钥列表;为空/省略时不校验主机密钥。 | +| `host-key-algorithms` | `list[string]` | 否 | 无 | 支持 `ssh-ed25519`(`ed25519`)、`rsa-sha2-256`、`rsa-sha2-512`、`ssh-rsa`(`rsa`)、`ecdsa-sha2-nistp256`、`ecdsa-sha2-nistp384`、`ecdsa-sha2-nistp521`。 | +| `totp-opt` | map | 否 | 无 | 用于 keyboard-interactive 动态码认证:
- `otp-auth: ""`(RFC 6238 默认参数);或
- `common: { secret, screw, step, digits, algorithm }`(`algorithm`:`SHA1` \| `SHA256` \| `SHA512`)。 | + +```yaml +proxies: + - name: ssh-bastion + type: ssh + server: ssh.example.com + port: 22 + username: ops + private-key: ~/.ssh/id_ed25519 + host-key: + - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleKeyData..." + totp-opt: + otp-auth: "JBSWY3DPEHPK3PXP" +``` + +--- + +## Tailscale(`type: tailscale`) + +以用户态节点直接接入 Tailscale Tailnet 或自建 Headscale 控制平面。 + +- **编译特性**:`tailscale`(默认 `standard` 构建已启用)。 +- **UDP**:始终支持。 +- **`connect-via`**:不支持(不使用 `CommonConfigOptions`)。 + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name` | `string` | 是 | — | 全局唯一节点名。 | +| `auth-key` | `string` | 否 | 无 | Tailscale / Headscale 预认证密钥。 | +| `hostname` | `string` | 否 | 无 | 注册到 Tailnet 的主机名。 | +| `state-dir` | `string` | 否 | 无 | 持久化 `/tailscale_state.json` 的目录(相对配置文件目录解析);若 `ephemeral: false` 且未配置,则仅保存在内存并打印警告。 | +| `control-url` | `string` | 否 | 官方 Tailscale 控制面 | 自定义控制面 URL(如 Headscale)。 | +| `client-name` | `string` | 否 | `"clash-rs"` | 上报给控制服务器的客户端名称。 | +| `ephemeral` | `bool` | 否 | `false` | 设为 `true` 时注册为临时节点并忽略 `state-dir` 持久化。 | + +```yaml +proxies: + - name: tailnet + type: tailscale + auth-key: "tskey-auth-REPLACE_ME" + hostname: clash-rs-node + state-dir: tailscale-state + control-url: "https://headscale.example.com" + ephemeral: false +``` + +--- + +## Tor(`type: tor`) + +通过内嵌的 Arti Tor 客户端路由 TCP 流量。 + +- **编译特性**:`onion`(**`standard` 默认不含**,需使用 `--features plus` 或 `--features onion` 编译)。 +- **UDP**:不支持(`false`)。 +- **`connect-via`**:不支持(不使用 `CommonConfigOptions`)。 + +### 字段 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name` | `string` | 是 | — | 全局唯一节点名。 | +| `interface` | `string` | 否 | 无 | 指定出站网卡名(非 Android 平台若找不到该网卡会报错)。 | +| `routing-mark` | [`SocketMark`](../types.md#socketmark) | 否 | 无 | Linux / Android 路由标记(`SO_MARK`)。 | + +```yaml +proxies: + - name: tor-exit + type: tor +``` diff --git a/docs/zh/config/providers.md b/docs/zh/config/providers.md new file mode 100644 index 0000000..49c52f0 --- /dev/null +++ b/docs/zh/config/providers.md @@ -0,0 +1,145 @@ +# 提供者(`proxy-providers`、`rule-providers`、`inbound-providers`) + +提供者用于从远程 HTTP、本地文件(支持操作系统文件监听自动热重载)或内联列表动态加载代理节点、路由规则和入站监听器。 + +所有本地文件与缓存 `path` 均相对 `-d` 解析,并受 [安全路径](../guides/compatibility.md#safe-paths) 检查约束。 + +--- + +## 代理提供者(`proxy-providers`) { #proxy-providers } + +支持 **`http`** 与 **`file`** 两种类型(不支持 `inline`)。 + +### `type: http` + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `type` | `"http"` | 是 | — | 远程 HTTP 节点提供者。 | +| `url` | `string` | 是 | — | 合法 HTTP(S) URL(直连拉取;未实现 `proxy` 与自定义 `header` 字段)。 | +| `path` | `string` | 否 | `proxy_providers/.yaml` | 本地缓存文件路径(相对 `-d`)。 | +| `interval` | `u64`(秒) | 否 | `86400`(24 小时) | 定时拉取间隔(`0` 禁用定时刷新)。 | +| `health-check` | 对象 | 否 | 见下文 | 健康检查配置。 | + +### `type: file` + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `type` | `"file"` | 是 | — | 本地文件节点提供者(自动开启文件系统监听,50 ms 防抖热重载)。 | +| `path` | `string` | 是 | — | 本地 YAML 路径(相对 `-d`)。 | +| `interval` | `u64`(秒) | 否 | `0`(禁用轮询) | 可选轮询间隔。 | +| `health-check` | 对象 | 否 | 见下文 | 健康检查配置。 | + +### `health-check` + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `enable` | `bool` | — | **重要说明**:当前运行时**未读取 `enable` 字段**;只要 `interval != 0` 就会执行自动健康检查。如需关闭自动测速,请显式设置 `interval: 0`。 | +| `url` | `string` | `"http://www.gstatic.com/generate_204"` | 测速地址。 | +| `interval` | `u64`(秒) | `300` | 检测间隔(`0` 关闭自动检测)。 | +| `lazy` | `bool` | `true` | 是否仅在有流量使用时才测速。 | + +### 提供者文件格式 + +内容必须是包含顶层 `proxies:` 列表的 YAML(单个解析失败的节点会记录警告并跳过,不影响其他节点): + +```yaml title="providers/nodes.yaml" +proxies: + - name: hk-01 + type: ss + server: hk01.example.com + port: 8388 + cipher: aes-256-gcm + password: "password" +``` + +```yaml title="config.yaml" +proxy-providers: + remote-sub: + type: http + url: "https://sub.example.com/proxies.yaml" + path: ./providers/remote-sub.yaml + interval: 3600 + health-check: + enable: true + url: http://www.gstatic.com/generate_204 + interval: 300 + lazy: true + + local-nodes: + type: file + path: ./providers/nodes.yaml + health-check: + interval: 0 +``` + +!!! note "未实现的 Mihomo `proxy-providers` 字段" + `proxy`、`header`、`filter`、`exclude-filter`、`exclude-type`、`override`、`payload`、`size-limit`、`dialer-proxy`、`health-check.expected-status`、`health-check.timeout` 均未定义。 + +--- + +## 规则提供者(`rule-providers`) { #rule-providers } + +支持 **`http`**、**`file`** 与 **`inline`** 三种类型,并在路由初始化时后台异步加载。 + +### 行为(`behavior`)与格式(`format`) + +- **`behavior`**(必填): + - `domain`:构建为高效 `DomainSet`,支持精确域名、`*.example.com`(单级通配)、`.example.com`(仅子域)、`+.example.com`(自身及所有子域)。 + - `ipcidr`:构建为 IPv4/IPv6 `CidrTrie`。 + - `classical`:不带目标的常规规则列表(`TYPE,PAYLOAD[,OPTIONS]`,不允许嵌套 `RULE-SET`),自动对 `DOMAIN`、`DOMAIN-SUFFIX`、`DOMAIN-KEYWORD` 与无 `no-resolve` 的 `IP-CIDR` 建立快速索引。 +- **`format`**(可选,默认 `yaml`): + - `yaml`:包含 `payload: [...]` 列表的 YAML 对象。 + - `text`:按行分隔的纯文本(自动跳过空行及 `#` / `//` 注释行)。 + - `mrs`:Mihomo Rule Set v1 二进制格式(Zstandard 压缩,magic `MRS\x01`);**仅支持 `domain` 与 `ipcidr`**,`classical` 下报错。 + +### 各类型字段汇总 + +| 类型 | 必填字段 | 可选字段与默认值 | +| --- | --- | --- | +| `http` | `type: http`、`url`、`behavior` | `interval`(`0`)、`path`(`rules/`)、`format`(`yaml`)、`inline-rules` / `payload`(在 `yaml`/`text` 下合并) | +| `file` | `type: file`、`path`、`behavior` | `interval`(无;使用系统文件监听热重载)、`format`(`yaml`)、`inline-rules` / `payload`(在 `yaml`/`text` 下合并) | +| `inline` | `type: inline`、`behavior`、`inline-rules`(别名 `payload`) | `path`(`rules/`,运行时不用) | + +```yaml +rule-providers: + ad-domains: + type: http + behavior: domain + format: mrs + url: "https://rules.example.com/ads.mrs" + path: ./rules/ads.mrs + interval: 86400 + + lan-cidrs: + type: file + behavior: ipcidr + format: text + path: ./rules/lan.txt + + custom-inline: + type: inline + behavior: classical + payload: + - DOMAIN-SUFFIX,internal.example.com + - IP-CIDR,198.51.100.0/24,no-resolve +``` + +--- + +## 入站提供者(`inbound-providers`) { #inbound-providers } + +从本地文件或远程 HTTP 动态加载额外 [`listeners`](inbounds/index.md) 列表,内容 YAML 需包含顶层 `listeners:` 字段。 + +| 类型 | 必填字段 | 可选字段与默认值 | +| --- | --- | --- | +| `http` | `type: http`、`url` | `interval`(`86400` 秒)、`path`(`inbound_providers/.yaml`) | +| `file` | `type: file`、`path` | `interval`(`0`,禁用轮询;走文件监听) | + +对于 `shadowsocks`、`anytls` 与 `hysteria2` 监听器,修改提供者中的 `users` 列表会直接原地热更新用户凭据,不中断监听端口。 + +```yaml +inbound-providers: + server-users: + type: file + path: ./inbounds/users.yaml +``` diff --git a/docs/zh/config/proxy-groups.md b/docs/zh/config/proxy-groups.md new file mode 100644 index 0000000..3758e1f --- /dev/null +++ b/docs/zh/config/proxy-groups.md @@ -0,0 +1,164 @@ +# 代理组(`proxy-groups`) + +代理组将单个出站节点和 [`proxy-providers`](providers.md#proxy-providers) 组合为手动选择、自动测速、故障转移、负载均衡、链式代理或智能评分选路策略。 + +## 通用规则 + +- 组名必须全局唯一,且不能为保留名称 `DIRECT` 或 `REJECT`。 +- 每个代理组必须通过 `proxies` 和/或 `use` 至少包含一个代理成员。 +- 支持代理组嵌套引用;ClashRS 在初始化时做 DAG 拓扑排序并拒绝循环依赖。 +- 系统会自动创建内置 **`GLOBAL`** 代理组(`type: select`、`udp: true`),包含所有静态节点、代理组与 `proxy-providers`。 +- `url-test`、`fallback` 与 `load-balance` 的 `interval` 同时接受整数或数字字符串(单位秒),`0` 表示禁用自动定时测速。 + +!!! note "未实现的 Mihomo 代理组字段" + `filter`、`exclude-filter`、`exclude-type`、`hidden`、`include-all`、`include-all-proxies`、`include-all-providers`、`disable-udp`、`expected-status`、`timeout`、`max-failed-times`、`interface-name`、`routing-mark` 在 ClashRS 代理组中未定义(非严格模式下静默忽略)。 + +--- + +## 支持的代理组类型(共 6 种) + +### 1. `select`(手动选择) + +通过 Web 面板或 `PUT /proxies/{name}` 手动切换节点。默认选第一个成员;开启 `profile.store-selected: true`(默认)时会自动记住并恢复上次选择。 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name` | `string` | 是 | — | 代理组名。 | +| `type` | `"select"` | 是 | — | 组类型。 | +| `proxies` | `list[string]` | 与 `use` 至少其一 | 无 | 静态代理或子代理组名称列表。 | +| `use` | `list[string]` | 与 `proxies` 至少其一 | 无 | 引用的 `proxy-providers` 键名列表。 | +| `udp` | `bool` | 否 | `true` | 为 `true` 时委托给当前选中节点的 UDP 能力;为 `false` 时强制禁用 UDP。 | +| `url` | `string` | 否 | `http://www.gstatic.com/generate_204` | 仅用于手动触发测速。 | +| `icon` | `string` | 否 | 无 | 通过 REST API 暴露给面板的图标地址。 | + +--- + +### 2. `url-test`(自动测速选优) + +按周期执行 HTTP 测速,自动选择最低延迟的可用节点。 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name` | `string` | 是 | — | 代理组名。 | +| `type` | `"url-test"` | 是 | — | 组类型。 | +| `proxies` / `use` | `list[string]` | 至少其一 | 无 | 成员节点或提供者。 | +| `url` | `string` | **是** | — | 健康检查 URL(如 `http://www.gstatic.com/generate_204`)。 | +| `interval` | `u64`(秒) | **是** | — | 自动测速间隔(`0` 禁用定时测速)。 | +| `tolerance` | `u16`(毫秒) | 否 | `0` | 切换节点的延迟容差阈值。 | +| `lazy` | `bool` | 否 | `false` | 是否仅在有流量经过时才触发测速。 | +| `icon` | `string` | 否 | 无 | 面板图标。 | + +**高级运行时特性**: + +- **手动锁定**:可通过 `PUT /proxies/{name}` 传入 `{"name": ""}` 临时锁定到指定节点;传入 `""`(或无同名节点时的 `"auto"` / `"default"`)即可解除锁定恢复自动测速。 +- **被动熔断器(Circuit Breaker)**:60 秒内连续 3 次连接失败会触发 30 秒冷却,期间优先绕过故障节点。 +- **高吞吐防抖**:全局速率超过 250 KB/s 时跳过常规测速切换(除非当前节点失效或触发熔断)。 +- **自适应容差**:连续 12 轮未切换且平均延迟差 > 20 ms 时,临时将有效容差下调至 20 ms,切换后恢复配置的 `tolerance`。 + +--- + +### 3. `fallback`(故障转移) + +按列表顺序选择第一个存活节点;若全部不可用则回退到第一个节点。 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`type`、`proxies`、`use`、`icon` | 同上 | — | — | `type: fallback`。 | +| `url` | `string` | **是** | — | 健康检查 URL。 | +| `interval` | `u64`(秒) | **是** | — | 检测间隔。 | +| `lazy` | `bool` | 否 | `false` | 延迟检测开关。 | + +--- + +### 4. `load-balance`(负载均衡) + +在存活节点间分发连接。 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name`、`type`、`proxies`、`use`、`icon` | 同上 | — | — | `type: load-balance`。 | +| `url` | `string` | **是** | — | 健康检查 URL。 | +| `interval` | `u64`(秒) | **是** | — | 检测间隔。 | +| `lazy` | `bool` | 否 | `false` | 延迟检测开关。 | +| `strategy` | `"consistent-hashing"` \| `"round-robin"` \| `"sticky-session"` | 否 | `"consistent-hashing"` | 分配策略。 | + +!!! note "当前运行时实现说明" + - 虽然配置解析接受全部三种 `strategy`,当前出站管理器实例化时实际生效的是默认的 **`consistent-hashing`**(基于目标 eTLD+1 域名或目标 IP 的 Murmur3 + Jump Hash)。 + - `load-balance` 当前运行时不支持 UDP(`support_udp()` 返回 `false`)。 + +--- + +### 5. `relay`(链式多跳代理) + +将节点按顺序串联转发(`proxies[0] -> proxies[1] -> ... -> 目标`),支持 TCP 与 UDP 链式转发。 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name` | `string` | 是 | — | 代理组名。 | +| `type` | `"relay"` | 是 | — | 组类型。 | +| `proxies` / `use` | `list[string]` | 至少其一 | 无 | 按跳转顺序排列的代理列表。 | +| `url` | `string` | 否 | `http://www.gstatic.com/generate_204` | 手动测速 URL。 | +| `icon` | `string` | 否 | 无 | 面板图标。 | + +--- + +### 6. `smart`(智能评分选路) + +综合历史延迟、成功率、延迟趋势、稳定性、丢包率、RTT 与失败惩罚动态打分选优。TCP 连接支持指数退避重试(100 ms 起,上限 5 s),UDP 直接走最优节点不重试。开启 `profile.store-smart-stats: true` 时每 30 秒持久化统计数据。 + +| YAML 键名 | 类型 | 必填 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `name` | `string` | 是 | — | 代理组名。 | +| `type` | `"smart"` | 是 | — | 组类型。 | +| `proxies` / `use` | `list[string]` | 至少其一 | 无 | 成员节点或提供者。 | +| `udp` | `bool` | 否 | `true` | 是否支持 UDP。 | +| `lazy` | `bool` | 否 | `false` | 延迟评估开关。 | +| `url` | `string` | 否 | 无 | 可选测试 URL。 | +| `max-retries` | `u32` | 否 | 自适应(`2..=6`,初始 `3`) | TCP 最大重试次数;省略或为 `0` 时按平均成功率动态计算。 | +| `bandwidth-weight` | `f64` | 否 | `0.0`(禁用) | 大于 `0.0` 时将 `delay * 0.1 * bandwidth-weight` 计入节点评分。 | +| `site-stickiness` | `f64` | 否 | 无 | 兼容解析字段(尚未接入运行时)。 | +| `icon` | `string` | 否 | 无 | 面板图标。 | + +## 配置示例 + +```yaml +proxy-groups: + - name: PROXY + type: select + proxies: + - AUTO + - SMART + - FALLBACK + - DIRECT + + - name: AUTO + type: url-test + use: + - sub-provider + url: http://www.gstatic.com/generate_204 + interval: 300 + tolerance: 50 + + - name: SMART + type: smart + use: + - sub-provider + udp: true + max-retries: 3 + bandwidth-weight: 0.2 + + - name: FALLBACK + type: fallback + proxies: + - node-a + - node-b + - DIRECT + url: http://www.gstatic.com/generate_204 + interval: 300 + + - name: CHAIN + type: relay + proxies: + - entry-node + - exit-node +``` diff --git a/docs/zh/config/rules.md b/docs/zh/config/rules.md new file mode 100644 index 0000000..9c607d3 --- /dev/null +++ b/docs/zh/config/rules.md @@ -0,0 +1,85 @@ +# 路由规则(`rules`) + +在 `mode: rule`(默认模式)下,ClashRS 从上到下依次匹配 `rules`,并将连接转发至首条命中规则的目标。若所有规则均未命中(例如省略 `MATCH`),连接会自动回退至 `DIRECT`。 + +## 语法格式 + +```text +TYPE,PAYLOAD,TARGET[,OPTIONS...] +MATCH,TARGET[,OPTIONS...] +``` + +- 内置目标:**`DIRECT`** 与 **`REJECT`**(以及配置中定义的任意代理或代理组名称)。 +- **不存在** `REJECT-DROP`、`PASS`、`COMPATIBLE`。 +- **不支持** `sub-rules` 与 `script`。 + +## 支持的全部规则类型(共 18 类) + +| 规则关键字 | 别名 | 匹配规则与语义 | 是否触发 DNS 解析 | +| --- | --- | --- | --- | +| `DOMAIN` | — | 精确域名匹配(ASCII 大小写不敏感;对纯 IP 目标返回 `false`)。 | 否 | +| `DOMAIN-SUFFIX` | — | 域名后缀匹配(匹配自身及 `.suffix` 子域,不会误匹配 `fakegoogle.com`)。 | 否 | +| `DOMAIN-KEYWORD` | — | 域名子串包含匹配(大小写不敏感)。 | 否 | +| `DOMAIN-REGEX` | — | Rust 正则匹配域名(默认大小写不敏感)。 | 否 | +| `GEOSITE` | — | 匹配 `geosite` 数据库分类;支持 `!code` 取反与 `code@attr` 属性过滤(大小写不敏感)。 | 否 | +| `GEOIP` | — | 匹配 `mmdb` 中的国家代码(如 `CN`);无内置 `PRIVATE` 特判,完全依赖 MMDB 数据。 | 是(除非带 `no-resolve`) | +| `IP-CIDR` | `IP-CIDR6` | 匹配目标 IPv4 / IPv6 CIDR(两个关键字均可同时匹配 v4/v6)。 | 是(除非带 `no-resolve`) | +| `SRC-IP-CIDR` | — | 匹配客户端源 IP CIDR(`sess.source.ip()`)。 | 否 | +| `SRC-PORT` | `SRC-PORT-RANGE` | 匹配源端口:单端口(`80`)、范围(`8000-8080` 或 `8000:8080`)或 `/` 分隔多段(`80/443/8000-8080`)。 | 否 | +| `DST-PORT` | `DST-PORT-RANGE`、`PORT-RANGE` | 匹配目标端口,语法同 `SRC-PORT`。 | 否 | +| `IN-TYPE` | — | 匹配入站类型(大小写不敏感):`HTTP`、`HTTPCONNECT`/`HTTP-CONNECT`、`SOCKS`/`SOCKS5`、`TUN`、`TPROXY`、`REDIR`、`TUNNEL`、`SHADOWSOCKS`/`SS`、`ANYTLS`、`HYSTERIA2`/`HY2`、`IGNORE`/`INNER`。 | 否 | +| `IN-USER` | — | 精确匹配入站认证用户名(`sess.inbound_user`,如 SS2022/AnyTLS/Hysteria2 多用户),payload 不可为空。 | 否 | +| `PROCESS-NAME` | — | 精确匹配本机进程名(支持 Linux / macOS / Windows,其余平台恒为 `false`)。 | 否 | +| `PROCESS-PATH` | — | 对进程名/路径执行子串包含匹配(Linux / macOS / Windows)。 | 否 | +| `NETWORK` | — | 匹配传输层协议:`TCP`/`tcp` 或 `UDP`/`udp`。 | 否 | +| `RULE-SET` | — | 引用 [`rule-providers`](providers.md#rule-providers) 中定义的规则集。 | `domain` 不解析;`ipcidr`/`classical` 默认解析,带 `no-resolve` 时不解析 | +| `AND` / `OR` / `NOT` | — | 支持任意层嵌套的逻辑组合规则(见下文)。 | 任一子规则需解析时触发 | +| `MATCH` | — | 兜底匹配所有剩余流量(`MATCH,TARGET[,interface=]`)。 | 否 | + +!!! warning "不支持的规则类型" + 以下规则类型在 ClashRS 中**不存在**,配置加载时会直接报 `unsupported rule type`: + `DOMAIN-WILDCARD`、`IN-PORT`、`IN-NAME`、`IN-IP`、`PROCESS-NAME-REGEX`、`PROCESS-PATH-REGEX`、`UID`、`DSCP`、`IP-ASN`、`IP-SUFFIX`、`SRC-GEOIP`、`SRC-IP-ASN`、`SRC-IP-SUFFIX`、`SUB-RULE`、`SCRIPT`、`FINAL`(请改用 `MATCH`)。 + +## 规则修饰符(Options) + +修饰符采用严格校验(出现未知或重复修饰符均会报错),共支持 **2 个**: + +1. **`no-resolve`** + - 遇到域名目标时不触发 DNS 解析。 + - 仅允许用于 `GEOIP`、`IP-CIDR`、`IP-CIDR6`、`SRC-IP-CIDR` 与 `RULE-SET`。 +2. **`interface=`** + - 可用于任意顶层规则(含 `MATCH` 与 `AND`/`OR`/`NOT`,**不可**写在逻辑组合内部子规则上)。 + - 命中规则后将出站 socket 绑定到指定网卡(找不到该网卡时记录警告并回退默认网卡)。 + +## 逻辑组合规则(`AND`、`OR`、`NOT`) + +内部子规则省略目标字段(子规则可带 `no-resolve`,但 `interface=` 只能写在最外层): + +```yaml +rules: + - AND,((NETWORK,UDP),(DST-PORT,443)),REJECT + - OR,((DOMAIN-SUFFIX,example.com),(IP-CIDR,192.0.2.0/24,no-resolve)),PROXY + - NOT,((GEOIP,CN,no-resolve)),PROXY + - AND,((IN-USER,alice),(GEOSITE,cn)),DIRECT,interface=eth0 +``` + +- `NOT` 必须恰好包含 **1 个** 子表达式。 +- 若复合规则构造失败,ClashRS 会打印错误并出于安全回退为 `MATCH,REJECT`。 + +## 配置示例 + +```yaml +rules: + - IN-USER,vip-user,PROXY + - PROCESS-NAME,curl,DIRECT + - RULE-SET,private-domains,DIRECT + - DOMAIN-SUFFIX,example.com,PROXY + - DOMAIN-REGEX,^ad[0-9]+\.example\.net$,REJECT + - GEOSITE,cn,DIRECT + - GEOSITE,geolocation-!cn,PROXY + - IP-CIDR,127.0.0.0/8,DIRECT,no-resolve + - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve + - GEOIP,CN,DIRECT,no-resolve + - AND,((NETWORK,UDP),(DST-PORT,443)),REJECT + - MATCH,PROXY +``` diff --git a/docs/zh/config/tun.md b/docs/zh/config/tun.md new file mode 100644 index 0000000..ee95cc5 --- /dev/null +++ b/docs/zh/config/tun.md @@ -0,0 +1,136 @@ +# TUN 虚拟网卡透明代理 + +ClashRS 内置用户态 Rust 网络协议栈(`smoltcp` / `watfaq_netstack`),可在 Windows、Linux、macOS、FreeBSD、Android 与 iOS 上提供三层 TUN 透明代理能力。 + +需编译启用 `tun` 特性(默认 `standard` 构建已包含)。 + +## 原生模式与 Mihomo 兼容模式 + +只要 `tun` 配置块中出现以下任意一项,ClashRS 就会自动进入 **Mihomo 兼容转换模式**: + +- 设置了 `stack`、`dns-mode`、`auto-detect-interface` 或 `auto-route` 中任一字段; +- `strict-route: true`; +- `route-address` 或 `route-exclude-address` 非空。 + +两种模式的默认值差异如下: + +| YAML 字段 | 原生模式默认值 | Mihomo 兼容模式默认值 | +| --- | --- | --- | +| `gateway` | `198.18.0.1/24` | 取 `dns.fake-ip-range` 的地址并设为 `/30`(如 `198.18.0.1/30`) | +| `gateway-v6` | 无 | 当顶层 `ipv6: true` 时默认 `fdfe:dcba:9876::1/126` | +| `auto-route` | 无(回退 `route-all`) | `true` | +| `auto-detect-interface` | 无 | `true` | +| `dns-hijack` | 关闭 | `["any:53"]`(并自动附加 TUN 子网 DNS 主机地址) | +| `dns-mode` | 无 | `""`(`Auto`:`auto-route && !macos` 时为 `hijack`,否则为 `disabled`) | + +## `tun` 全部字段 + +| YAML 键名 | 别名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | --- | +| `enable` | — | `bool` | `false` | 是否启用 TUN 入站。 | +| `device-id` | `device-url`、`device` | `string` | `"utun1989"` | 设备标识:`fd://`(Unix 已打开文件描述符)、`dev://`(Windows 支持 `dev://NAME?guid=`)或裸名称 ``。 | +| `stack` | — | `mips` \| `system` \| `gvisor` \| `mixed` | 无 | Mihomo 兼容字段;运行时统一使用内置 Rust 协议栈(`watfaq_netstack`)。 | +| `dns-mode` | — | `""`(`Auto`)\| `disabled` \| `native` \| `hijack` | 无(Mihomo 模式默认 `Auto`) | 控制 TUN 网卡 DNS 配置与 WFP DNS 阻断策略(Windows 上生效显著)。 | +| `auto-detect-interface` | — | `bool` | 无(Mihomo 模式默认 `true`) | 未配置顶层 `interface` 时自动探测默认物理出站网卡。Windows 上为 `true` 时会动态跟随系统默认路由变化(1 秒缓存)。 | +| `strict-route` | — | `bool` | `false` | 严格防泄漏路由(仅当 `auto-route` 为 `true` 时生效)。目前在 Windows 上通过 WFP 实现。 | +| `auto-redirect` | — | `bool` | `false` | Mihomo 兼容字段。**在 Linux 上设为 `true` 会直接报 `InvalidConfig` 错误**(ClashRS 不提供 Linux redirect 后端);其他平台接受并忽略。 | +| `exclude-interface` | — | `list[string]` | `[]` | **仅 Windows 编译存在的兼容字段**(运行时不做过滤);非 Windows 平台不存在此字段。 | +| `gateway` | — | IPv4 CIDR | `198.18.0.1/24`(Mihomo 模式 `/30`) | TUN 接口 IPv4 地址与网段。 | +| `gateway-v6` | — | IPv6 CIDR | 无(Mihomo 模式 + `ipv6: true` 时为 `fdfe:dcba:9876::1/126`) | TUN 接口 IPv6 地址与网段(配置即启用 TUN IPv6)。 | +| `routes` | — | `list[CIDR]` | 无 | 原生模式下的自定义路由网段列表。 | +| `route-all` | — | `bool` | `false` | 原生模式下的全流量接管开关。 | +| `auto-route` | — | `bool` | 无(Mihomo 模式默认 `true`) | Mihomo 风格自动安装系统路由;未设时回退至 `route-all`。 | +| `route-address` | — | `list[CIDR]` | `[]` | 纳入 TUN 的目标网段(需 `auto-route: true`);若为空且设置了 `route-exclude-address`,默认从 `0.0.0.0/0`(及 IPv6 `::/0`)开始拆分。 | +| `route-exclude-address` | — | `list[CIDR]` | `[]` | 从接管网段中排除的 CIDR 列表(需 `auto-route: true`),内部自动做子网拆分。 | +| `mtu` | — | `u16` | Windows `65535`,其他平台 `1500` | TUN 接口 MTU。 | +| `so-mark` | — | [`SocketMark`](types.md#socketmark) | 继承顶层 `routing-mark` | Linux / Android 策略路由防环标记。 | +| `route-table` | — | `u32` | `2468` | Linux 策略路由表编号;FreeBSD 上用作 bypass FIB 编号。 | +| `dns-hijack` | — | `bool` 或 `list[string]` | 原生关闭 / Mihomo `["any:53"]` | TUN 内 DNS 劫持规则,详见下文。 | + +### `dns-hijack` 两种写法差异 + +- **布尔值(`true` / `false`)**:设为 `true` 仅劫持 **UDP 53 端口**(不劫持 TCP 53)。 +- **列表(如 `["any:53", "tcp://1.1.1.1:53"]`)**:剥离可选的 `scheme://` 前缀后**同时匹配 TCP 与 UDP**;支持 `any:` 或 `IP:port`(IPv6 需方括号如 `[::1]:53`),且自动附加 TUN 子网计算出的 DNS 主机地址(如 `198.18.0.2:53`)。 + +!!! note "未定义的 Mihomo TUN 字段" + `inet4-address` 与 `inet6-address` 不存在,请改用 `gateway` 与 `gateway-v6`。`endpoint-independent-nat`、`gso`、`udp-timeout`、`include-uid`、`exclude-uid`、`include-package`、`exclude-package` 等字段也未实现。 + +## 各平台注意事项 + +=== "Windows" + + - 需要**管理员权限**运行。 + - 基于 **Wintun**:需在 `clash-rs.exe` 同级目录放置对应架构的 `wintun.dll`,或在 MSVC 下启用 `--features wintun-embed` 编译内嵌。 + - 默认 MTU 为 `65535`;可通过 `dev://ClashRS?guid=` 固定适配器 GUID(否则基于名称按 UUIDv5 确定性生成以复用适配器)。 + - 全路由模式安装 `/1` 拆分路由(`0.0.0.0/1`、`128.0.0.0/1`,开启 IPv6 时加 `::/1`、`8000::/1`)。 + - 开启 `strict-route: true` 且 `auto-route: true` 时,会安装生命周期绑定的 **WFP(Windows Filtering Platform)** 过滤规则:放行 ClashRS 进程与 TUN 流量;当 `dns-mode` 为 `hijack` 时阻断非 TUN 的 53 端口;若未开启 `gateway-v6`,保留 `::1` 与 ICMPv6 NDP 并阻断其他出站 IPv6。 + +=== "Linux" + + - 需要 `root` 或 `CAP_NET_ADMIN` 权限,并依赖系统 `ip`(`iproute2`)命令。 + - 全路由模式使用策略路由表(`route-table`,默认 `2468`)配合 `so-mark`(如 `ip rule add not fwmark table 2468`)防环。 + - 新建设备时尝试开启 `IFF_VNET_HDR` TUN offload(TSO/USO),不支持时自动回退。 + - **`auto-redirect: true` 会直接报错拒绝。** + +=== "macOS" + + - 命名设备名**必须以 `utun` 开头**(如 `utun1989`)。 + - 全路由模式安装 `/1` 路由并通过 `-ifscope ` 绕过物理网卡防止回环。 + - `dns-mode: auto` 在 macOS 上解析为 `disabled`(不会自动改写系统 DNS)。 + +=== "FreeBSD" + + - 采用多路由表(`setfib(2)` + `net.fibs`):FIB 0 默认路由指向 TUN,ClashRS 进程切入 bypass FIB(编号取 `route-table`),并将状态持久化至临时文件以支持崩溃重启自愈。 + +=== "Android 与 iOS" + + - **仅支持 `fd://`**(传入命名设备会直接报错)。 + - 路由由宿主 VPN 服务(`VpnService` / `NEPacketTunnelProvider`)负责管理。 + - 在 `--service-mode` 下禁止使用 `fd://`。 + +## 配置示例 + +=== "Mihomo 风格(桌面端推荐)" + + ```yaml + ipv6: true + + dns: + enable: true + ipv6: true + enhanced-mode: fake-ip + fake-ip-range: 198.18.0.1/16 + default-nameserver: + - 223.5.5.5 + - 8.8.8.8 + nameserver: + - https://1.1.1.1/dns-query + + tun: + enable: true + stack: mixed + auto-route: true + auto-detect-interface: true + strict-route: true + dns-hijack: + - any:53 + route-exclude-address: + - 192.168.0.0/16 + - 10.0.0.0/8 + ``` + +=== "Linux 网关原生风格" + + ```yaml + routing-mark: 6666 + + tun: + enable: true + device-id: "dev://utun1989" + gateway: 198.18.0.1/24 + route-all: true + route-table: 2468 + so-mark: 6666 + dns-hijack: + - any:53 + ``` diff --git a/docs/zh/config/types.md b/docs/zh/config/types.md new file mode 100644 index 0000000..8501411 --- /dev/null +++ b/docs/zh/config/types.md @@ -0,0 +1,106 @@ +# 通用类型与传输层选项 + +本页说明 ClashRS 配置中多处复用的基础数据类型、证书格式以及出站共享传输层配置块。 + +## 基础数据类型 + +### `BindAddress` { #bindaddress } + +用于顶层 `bind-address` 与 `listeners[].listen`,支持以下写法: + +| 取值 | 解析结果 | 说明 | +| --- | --- | --- | +| `"*"` | `0.0.0.0` | 监听所有 IPv4 网卡 | +| `"localhost"` | `127.0.0.1` | IPv4 本机回环 | +| `"::"` 或 `"[::]"` | `::` | 监听所有 IPv6 / 双栈地址 | +| `"127.0.0.1"`、`"192.168.1.10"`、`"::1"` | 对应 IP 字面量 | 任意合法 IPv4 或 IPv6 地址 | + +### `Port` { #port } + +用于顶层端口简写字段(`port`、`socks-port`、`mixed-port`、`redir-port`、`tproxy-port`),同时接受 YAML 整数(`7890`)或数字字符串(`"7890"`),范围 `0..=65535`。 + +!!! note + 在 `listeners[]` 与 `proxies[]` 内部,`port` 必须为 YAML 整数(`u16`)。 + +### `SocketMark` { #socketmark } + +32 位无符号整数(`u32`),在 Linux(及启用 `tproxy` 特性的 Android)上通过 `SO_MARK` 生效,其他平台忽略。 + +- **Linux**:直接设置 `SO_MARK`(设为 `0` 时清除标记)。 +- **Android(`socket_mark`)**:校验掩码 `0x7ce0_0000`(仅允许 bits 21–23 与 26–30),应用时按位 OR 到现有 socket 标记。 + +### `SocksAddr` { #socksaddr } + +`host:port` 格式的目标地址(如 `example.com:443`、`192.0.2.53:53`、`[2001:db8::1]:443`),端口不能为 `0`。用于 `tunnels`、`listeners`(`type: tunnel`)以及 `/providers/rules/{name}/match` API。 + +## TLS 证书与私钥(`tls-cert` / `tls-key` / `certificate` / `private-key`) { #tls-certificates } + +凡接受 PEM 证书或私钥的配置项(出站 mTLS 的 `tls-cert`/`tls-key`、入站 `anytls`/`hysteria2` 的 `certificate`/`private-key`、`naive` 的 `ca-cert`),均支持两种写法: + +1. **文件路径**(相对 `-d` 解析,受 `SafePaths` 校验); +2. **内联 PEM 文本**(内容包含 `-----BEGIN`,可使用 YAML 多行块 `|`)。 + +```yaml +tls-cert: | + -----BEGIN CERTIFICATE----- + ... + -----END CERTIFICATE----- +tls-key: | + -----BEGIN PRIVATE KEY----- + ... + -----END PRIVATE KEY----- +``` + +!!! warning "必须成对配置" + 出站 `tls-cert` 与 `tls-key`(以及入站 `certificate` 与 `private-key`)必须**同时提供**或**同时省略**,仅提供其一会报配置错误。 + +## 共享出站传输层配置块 + +### `ws-opts` { #ws-opts } + +用于 `trojan`、`vmess`、`vless` 且 `network: ws` 时(必填)。 + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `path` | `string` | `""` | WebSocket 握手路径(如 `"/ws"`)。 | +| `headers` | `map[string -> string]` | `{}` | 附加 HTTP 请求头(常见如 `Host`)。 | +| `max-early-data` | `i32` | `0` | 大于 `0` 时启用 WebSocket 0-RTT Early Data。 | +| `early-data-header-name` | `string` | `""` | 携带 Early Data 的请求头名(如 `"Sec-WebSocket-Protocol"`)。 | + +### `h2-opts` { #h2-opts } + +用于 `vmess`、`vless` 且 `network: h2` 时(必填)。 + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `host` | `list[string]` | `[server]` | HTTP/2 `:authority` 主机列表。 | +| `path` | `string` | `""` | HTTP/2 请求路径(如 `"/h2"`)。 | + +### `grpc-opts` { #grpc-opts } + +用于 `trojan`、`vmess`、`vless` 且 `network: grpc` 时(必填)。 + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `grpc-service-name` | `string` | `""` | gRPC 服务名(实际请求路径拼接为 `"/{grpc-service-name}"`)。 | + +### `xhttp-opts`(别名 `splithttp-opts`) { #xhttp-opts } + +用于 `vmess`、`vless` 且 `network: xhttp` 或 `network: splithttp` 时(可选,省略则全用默认值)。 + +| YAML 键名 | 类型 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `path` | `string` | `"/"` | 请求路径(自动规范化首尾 `/` 并保留 `?query`)。 | +| `host` | `string` | `headers.Host` 或 `server` | 请求 `Host` 头。 | +| `mode` | `string` | `"auto"` | 兼容字段;当前 ClashRS 统一通过 HTTP/2 POST 流传输。 | +| `headers` | `map[string -> string]` | `{}` | 额外请求头(`Host` 与 `Referer` 由内部处理)。 | +| `x-padding-bytes` | `string` | 在 `Referer` query 中随机生成 100..=1000 字节 | 填充规则:`"0"` 或 `"0-0"` 禁用填充;支持 `"min-max"` 范围、固定数字或字面量(显式设置时同时发送 `X-Padding` 头)。 | + +### `reality-opts` { #reality-opts } + +仅用于 `vless` 启用 TLS REALITY(设置后优先于普通 `tls: true`)。 + +| YAML 键名 | 类型 | 必填 | 说明 | +| --- | --- | --- | --- | +| `public-key` | `string` | 是 | URL-safe 无填充 Base64 编码的 32 字节 X25519 公钥。 | +| `short-id` | `string` | 是 | 十六进制 Short ID(可为空字符串 `""`)。 | diff --git a/docs/zh/guides/api.md b/docs/zh/guides/api.md new file mode 100644 index 0000000..a0f669d --- /dev/null +++ b/docs/zh/guides/api.md @@ -0,0 +1,119 @@ +# REST API 与外部控制 + +ClashRS 通过 TCP 和/或本地 IPC(Unix Domain Socket / Windows Named Pipe)提供兼容 Clash 生态的 HTTP 与 WebSocket 控制接口。 + +## 监听方式、鉴权与安全策略 + +### TCP 监听(`external-controller`) + +- 以冒号开头的地址(如 `:9090`)会自动补全为 `127.0.0.1:9090`。 +- **非回环地址强制安全检查**:监听任何非本机回环地址(如 `0.0.0.0:9090`)时,**必须同时设置**非空 `secret` 和 CORS 允许来源(`external-controller-cors` 或 `cors-allow-origins`),否则控制接口会拒绝启动。 +- **鉴权**:配置非空 `secret` 后,HTTP 请求需携带 `Authorization: Bearer `,WebSocket 握手亦支持 `?token=`。`/ui`、`/ui/*` 以及带 `Origin` 头的 `OPTIONS` 预检请求免鉴权。 +- **CORS**:允许方法为 `GET`、`POST`、`PUT`、`PATCH`(注意:当前未包含 `DELETE`),允许请求头 `Authorization` 与 `Content-Type`,默认开启 `allow-private-network: true`。 + +### IPC 监听(`external-controller-ipc` / `--controller-ipc`) + +- **Unix**:Unix Domain Socket(自动创建父目录,绑定前自动清理同名旧 socket 文件)。 +- **Windows**:Named Pipe(如 `\\.\pipe\clash-rs`),通过 SDDL 安全描述符控制访问权限(`--controller-pipe-sddl` 或 `LISTEN_NAMEDPIPE_SDDL`,默认 `D:(A;;GRGW;;;BU)(A;;GRGW;;;SY)`)。 +- **无 Token 鉴权**:IPC 依赖操作系统文件/管道权限,不使用 `secret`。 +- 可与 TCP 控制器同时启用。 + +### WebSocket 路径自动重写 + +凡携带 WebSocket 升级头(`Connection: upgrade` 与 `Upgrade: websocket`)且路径不以 `/ws` 开头的请求,中间件会自动在内部重写为 `/ws` 并保留查询参数。因此客户端直接连接 `/connections` 或 `/ws/connections` 均可正常工作。 + +--- + +## 接口完整参考 + +### 系统与 Web 面板 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| `GET` | `/` | 欢迎/存活接口,返回 `{"hello": "clash-rs"}`。 | +| `GET` | `/version` | 返回 `{"version": "", "meta": false}`(非空时附带 `commit`)。 | +| `POST` | `/restart` | 1 秒后重启进程(保留原命令行参数与环境变量),返回 `{"status": "ok"}`。**`--service-mode` 下返回 `409 Conflict` 拒绝重启。** | +| `GET` | `/ui`、`/ui/`、`/ui/{*path}` | 提供 `external-ui` 静态资源;未配置或为空时回退至内置面板(`dashboard` 特性)。免鉴权。 | + +### 配置与 GeoData + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| `GET` | `/configs` | 获取当前运行配置摘要(含端口、`bind-address`、`mode`、`log-level`、`ipv6`、`unified-delay`、`allow-lan`、`listeners`、`lan-ips`、`dns-listen`)。 | +| `PUT` | `/configs` | 全量重载配置。JSON 体 `{"path"?: string, "payload"?: string}`:提供 `payload` 时直接解析 YAML;否则若 `path` 非空经 `SafePaths` 校验后加载;均为空时重载启动配置文件。成功返回 `204 No Content`。 | +| `PATCH` | `/configs` | 运行时局部修改 `port`、`socks-port`、`redir-port`、`tproxy-port`、`mixed-port`、`bind-address`、`mode`、`log-level`、`ipv6`、`unified-delay`、`allow-lan`;修改端口/绑定地址会自动重启入站监听器。返回 `202 Accepted`。 | +| `POST` | `/configs/geo` | 在线更新 GeoData(Country MMDB / ASN MMDB / GeoSite;60 秒超时,原子替换与回滚)并清空 DNS 缓存。返回 `204 No Content`。 | +| `POST` | `/upgrade/geo` | `POST /configs/geo` 的 Mihomo 兼容别名。 | + +### 代理与代理组 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| `GET` | `/proxies` | 获取所有代理与代理组(`{"proxies": {...}}`)。 | +| `GET` | `/proxies/{name}` | 获取单个代理或代理组详情(不存在返回 `404`)。 | +| `PUT` | `/proxies/{name}` | 切换 `select` 组选中节点(或锁定/解锁 `url-test` 组)。请求体 `{"name": ""}`;开启 `profile.store-selected` 时自动持久化。返回 `202 Accepted`。 | +| `GET` | `/proxies/{name}/delay` | 单节点/代理组测速。必填参数:`?url=&timeout=`。返回 `{"delay": , "overall": }`。 | +| `GET` | `/group` | 获取所有代理组列表(`{"proxies": [...]}`)。 | +| `GET` | `/group/{name}` | 获取单个代理组详情(非组或不存在返回 `404`)。 | +| `GET` | `/group/{name}/delay` | 对指定代理组及其所有成员测速。必填参数:`?url=&timeout=`。返回 `{"": }`。 | + +### 提供者(Providers) + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| `GET` | `/providers/proxies` | 获取所有代理提供者(`{"providers": {...}}`)。 | +| `GET` | `/providers/proxies/{provider}` | 获取单个代理提供者详情。 | +| `PUT` | `/providers/proxies/{provider}` | 触发刷新指定代理提供者(`202 Accepted`)。 | +| `GET` | `/providers/proxies/{provider}/healthcheck` | 触发指定代理提供者健康检查(`202 Accepted`)。 | +| `GET` | `/providers/proxies/{provider}/{proxy}` | 获取提供者中单个节点详情。 | +| `GET` | `/providers/proxies/{provider}/{proxy}/healthcheck` | 对提供者中单个节点测速(`?url=...&timeout=...`)。 | +| `GET` | `/providers/rules` | 获取所有规则提供者(`{"providers": {...}}`)。 | +| `GET` | `/providers/rules/{provider}` | 获取单个规则提供者详情。 | +| `PUT` | `/providers/rules/{provider}` | 触发刷新规则提供者(`202 Accepted`)。 | +| `GET` | `/providers/rules/{provider}/rules` | **ClashRS 扩展接口**:返回该规则提供者的前 500 条规则(`{"rules": [...]}`)。 | +| `GET` | `/providers/rules/{provider}/match` | **ClashRS 扩展接口**:测试 `?target=` 是否命中该规则提供者(`{"match": }`)。 | + +### 规则、连接、流聚合与监控 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| `GET` | `/rules` | 获取当前全部路由规则(`{"rules": [...]}`)。 | +| `GET` | `/connections` | HTTP 返回当前活跃连接快照;WebSocket 升级后按周期推送快照(可选 `?interval=`,默认 `1`)。 | +| `DELETE` | `/connections` | 关闭所有活跃连接。 | +| `DELETE` | `/connections/{id}` | 按 UUID 关闭单个连接。 | +| `GET` | `/flows` | **ClashRS 扩展接口**:按 `(dst_host, dst_port, protocol)` 聚合流统计。参数:`?top=<1..=500>`(默认 `20`)、`?include_closed=`(默认 `true`);WebSocket 升级支持 `?interval=`(默认 `5`)。 | +| `GET` | `/memory` | HTTP 返回 `{"inuse": , "oslimit": }`;WebSocket 周期推送(可选 `?interval=`,默认 `1`;WS 路径下 `oslimit` 固定 `0`)。 | +| `GET`(WS) | `/traffic`(或 `/ws/traffic`) | WebSocket 每秒推送实时速率 `{"up": , "down": }`。 | +| `GET`(WS) | `/logs`(或 `/ws/logs`) | WebSocket 推送实时 `LogEvent` JSON 日志流。 | +| `GET` | `/user-stats` | **ClashRS 扩展接口**:返回并清零自上次调用以来按 `inboundUser` 累计的流量(`{"": {"upload": , "download": }}`)。 | + +### 缓存与 DNS + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| `POST` | `/cache/fakeip/flush` | 清空 Fake-IP 映射缓存(未开启 Fake-IP 返回 `400`,成功返回 `204`)。 | +| `POST` | `/cache/dns/flush` | 清空 DNS 响应缓存(`204 No Content`)。 | +| `GET` | `/dns/query` | 调用内置 DNS 解析器查询(系统解析器模式下返回 `400`)。必填参数:`?name=&type=`(无效 `type` 回退 `A`),返回 DoH JSON 响应。 | + +## `curl` 调用示例 + +```bash +# 查看版本 +curl -H "Authorization: Bearer change-me" http://127.0.0.1:9090/version + +# 运行时切换路由模式 +curl -X PATCH http://127.0.0.1:9090/configs \ + -H "Authorization: Bearer change-me" \ + -H "Content-Type: application/json" \ + -d '{"mode": "global"}' + +# 切换 PROXY 代理组选中节点 +curl -X PUT http://127.0.0.1:9090/proxies/PROXY \ + -H "Authorization: Bearer change-me" \ + -H "Content-Type: application/json" \ + -d '{"name": "vless-reality"}' + +# 通过 Unix Domain Socket 查询内置 DNS +curl --unix-socket /tmp/clash-rs.sock \ + "http://localhost/dns/query?name=example.com&type=A" +``` diff --git a/docs/zh/guides/compatibility.md b/docs/zh/guides/compatibility.md new file mode 100644 index 0000000..5d79e17 --- /dev/null +++ b/docs/zh/guides/compatibility.md @@ -0,0 +1,110 @@ +# Mihomo 兼容模式与安全路径 + +ClashRS 可直接作为 Mihomo 的替代内核用于 Clash Verge 等启动器,同时默认对配置中引用的外部文件路径实施严格的安全路径约束。 + +## Mihomo 兼容模式 + +需要与 Mihomo 共享数据目录和 GeoData 文件时,启用兼容模式: + +=== "命令行参数" + + ```bash + clash-rs --compatibility -d ./profiles -f config.yaml + ``` + + 该命令加载 `./profiles/config.yaml`,并将 `./profiles` 设为进程工作目录(省略 `-d` 时使用当前目录)。 + +=== "环境变量" + + 若启动器命令行固定,可在内核进程环境中设置: + + ```bash + CLASH_RS_COMPATIBILITY_MODE=1 # 或 "true"(不区分大小写) + ``` + + 如需关闭,移除该环境变量并去掉 `--compatibility` 后重启内核。 + +### 兼容模式带来的变化 + +1. **自动补全 GeoData 默认路径**(仅在 YAML 中未显式设置时生效,配置热重载后持续保留): + + | YAML 字段 | 兼容模式默认值 | + | --- | --- | + | `mmdb` | `Country.mmdb` | + | `geosite` | `geosite.dat` | + +2. **独立代理选择缓存文件**: + - 开启 `profile.store-selected: true` 时,兼容模式读写 **`clash-rs-cache.db`**(普通模式使用 `cache.db`),避免与 Mihomo 互相覆盖缓存。 + - 热重载配置时会保持启动时选定的缓存文件名。 + +3. **兼容单短横线 IPC 参数**: + - 命令行解析前会自动将 `-ext-ctl-unix` / `-ext-ctl-pipe` 规范化为 `--ext-ctl-unix` / `--ext-ctl-pipe`。 + +--- + +## 安全路径(`SafePaths`) { #safe-paths } + +无论普通模式还是兼容模式,ClashRS 默认都将**配置文件中提供的所有外部路径**限定在工作目录(`-d`,缺省为当前目录)以内,覆盖范围包括: + +- GeoData 文件(`mmdb`、`asn-mmdb`、`geosite`) +- Provider 本地文件与缓存(`proxy-providers`、`rule-providers`、`inbound-providers`) +- TLS 证书与私钥(`tls-cert`、`tls-key`、`certificate`、`private-key`、`ca-cert`) +- 外部面板目录(`external-ui`) +- 通过 `PUT /configs` 传入的显式配置文件路径 + +!!! tip "启动配置位于 `-d` 之外" + 在非 `--service-mode` 模式下,启动时仍允许通过 `-c` / `-f` 指定工作目录之外的配置文件;后续向 `PUT /configs` 发送空的 `path` 与 `payload` 重载时,会继续沿用该启动配置路径。 + +### 允许额外根目录(`SAFE_PATHS`) + +在进程环境变量中设置 `SAFE_PATHS` 指定额外允许的绝对目录(Unix 用 `:` 分隔,Windows 用 `;` 分隔): + +```bash +# Linux / macOS +SAFE_PATHS=/srv/providers:/srv/geodata clash-rs -d /etc/clash -c config.yaml +``` + +```powershell +# Windows PowerShell +$env:SAFE_PATHS = "C:\clash\providers;C:\clash\geodata" +clash-rs -d C:\clash -c config.yaml +``` + +- 显式列出的根目录本身可以是符号链接或 Windows Junction(启动时解析一次,重叠时取最具体路径); +- 但根目录之下的任意子路径均**禁止**再出现符号链接或 Windows reparse point。 + +### 跳过安全路径检查(`SKIP_SAFE_PATH_CHECK`) + +在非 `--service-mode` 模式下,将 `SKIP_SAFE_PATH_CHECK` 设为 `1`、`t`、`T`、`true`、`TRUE` 或 `True` 可关闭检查。`SAFE_PATHS` 与 `SKIP_SAFE_PATH_CHECK` 均仅在启动时读取一次。 + +--- + +## 服务受限模式(`--service-mode`) + +面向高权限后台服务(如 Clash Verge Service): + +- 必须指定 `--directory`(`-d`); +- 禁止使用 `--log-file`(`-l`); +- 除 `-t` 校验外,必须指定非空 `--controller-ipc`(Windows 上还必须提供非空 `--controller-pipe-sddl` / `LISTEN_NAMEDPIPE_SDDL`); +- 自动开启 `--compatibility`; +- **强制忽略 `SAFE_PATHS` 与 `SKIP_SAFE_PATH_CHECK`**——所有配置文件与资源都必须置于 `-d` 内部; +- 禁止 `fd://` TUN、禁止 Naive 自定义 `cronet-lib-path`,并拒绝 `POST /restart`(返回 `409 Conflict`)。 + +--- + +## 从 Mihomo 迁移常见差异速查 + +| Mihomo 特性 / 字段 | ClashRS 对应写法或现状 | +| --- | --- | +| `fwmark` | 请使用 `routing-mark` | +| `tun.inet4-address` / `tun.inet6-address` | 请使用 `tun.gateway` / `tun.gateway-v6` | +| `tun.auto-redirect: true`(Linux) | Linux 下报错拒绝;请使用 `auto-route: true` 配合 `so-mark` 与 `route-table` | +| `dns.enhanced-mode: redir-host` | 不支持(无操作);请改用 `fake-ip` 或 `normal` | +| `dns.nameserver: ["system"]` | 不支持(跳过);请填写具体 IP 或 DoH/DoT 地址 | +| `dns.nameserver-policy` 列表值 | 每个域名仅接受单个上游字符串 | +| `proxies[].type: http / snell / ssr` | 不支持(YAML 解析报错) | +| `hysteria2` 省略 `skip-cert-verify` | 必须显式填写 `skip-cert-verify: false` 或 `true` | +| `vmess` 省略 `cipher` | 需显式指定 `cipher: auto`(或具体算法) | +| `proxy-groups` 的 `filter` / `include-all` | 未实现 | +| 规则 `FINAL`、`SUB-RULE`、`IP-ASN`、`UID` | 不支持(`FINAL` 请改用 `MATCH`) | +| `rule-providers` 的 `format: mrs` | 支持 `domain` 与 `ipcidr`(`classical` 不支持) | diff --git a/docs/zh/index.md b/docs/zh/index.md index 7e4b841..5d05e0c 100644 --- a/docs/zh/index.md +++ b/docs/zh/index.md @@ -1,11 +1,45 @@ -# ClashRS 用户手册 +--- +hide: + - toc + - navigation +--- -ClashRS 是用 Rust 编写的规则代理。它可以为应用程序提供 HTTP 和 SOCKS 代理,也可以通过 TUN 设备接管网络流量。 +# 欢迎使用 ClashRS 用户文档 -- [快速开始](quick-start.md)介绍如何启动本地代理或使用图形界面。 -- [入站监听](config/inbounds.md)介绍如何配置接收连接的端口和地址。 -- [完整配置示例](config/full.md)展示 DNS、出站代理和路由规则如何配合使用。 +**ClashRS** 是一款使用 Rust 编写的高性能、基于规则的网络代理核心。它支持多协议入站与出站代理、内置防污染 DNS、跨平台 TUN 虚拟网卡与透明代理、动态远程节点/规则加载,以及完整的外部控制 API。 -## 功能 +!!! info "文档版本基线" + 本文档基于 **ClashRS v0.10.x**(`Watfaq/clash-rs`)源码核实编写,完整涵盖 Mihomo 兼容模式、`--service-mode` 安全路径限制、多协议监听器及当前支持的全部入站与出站协议。 -ClashRS 可以按来源、目的地址、域名或 GeoIP 分流,也可以加载远程代理和规则。DNS 解析支持 UDP、TCP、DoH 和 DoT。出站协议包括 Shadowsocks、Trojan 和 VMess,并支持分布式追踪。详见[项目功能列表](https://github.com/Watfaq/clash-rs#-features)。 +## 核心特性 + +- **灵活的流量路由**:支持 18 类路由规则(域名、正则、GeoIP、GeoSite、CIDR、端口范围、进程名/路径、入站类型/用户、`AND`/`OR`/`NOT` 逻辑组合及 `yaml`/`text`/`mrs` 规则集),支持 `no-resolve` 与按规则绑定出站网卡 `interface=`。 +- **内置防污染 DNS**:支持 UDP、TCP、DoT、DoH 及 DHCP 上游,本地可同时监听 UDP/TCP/DoT/DoH/DoH3;支持 Fake-IP、`fallback-filter`、域名分流策略(`nameserver-policy`)、EDNS Client Subnet 与 `respect-rules`。 +- **丰富的入站模式**:支持 HTTP、SOCKS5、Mixed、Shadowsocks(含 SS2022 多用户)、AnyTLS、Hysteria2、Tunnel 固定端口转发、Linux/Android TProxy、Linux Redir 及跨平台 TUN。 +- **16 种出站协议**:支持 Direct、Reject、Shadowsocks / SS2022(含 obfs / v2ray-plugin / ShadowTLS)、SOCKS5、AnyTLS、Trojan、VMess、VLESS(含 REALITY 与 XTLS Vision)、WireGuard、TUIC v5、Hysteria2、Naive(Cronet)、ShadowQUIC、SSH、Tailscale 与 Tor。 +- **多策略代理组与热重载提供者**:支持 `select`、`url-test`(含熔断器、自适应容差与手动锁定)、`fallback`、`load-balance`、`relay` 与 `smart` 智能选路组,支持 HTTP/File/Inline 提供者与本地文件自动热更新。 +- **外部控制与平滑迁移**:支持 TCP、Unix Domain Socket 与 Windows Named Pipe 控制接口、内置 Web 面板,以及 Mihomo 兼容模式(`--compatibility`)。 + +## 平台支持 + +| 平台 | 运行支持 | 说明 | +| --- | --- | --- | +| **Linux** | 完整支持(CLI、TUN、TProxy、Redir) | 支持策略路由(`route-table`)与 `SO_MARK` 防环 | +| **Windows** | 完整支持(CLI、GUI、Wintun TUN) | TUN 需管理员权限;支持外置 `wintun.dll` 或 `--features wintun-embed` 与 WFP `strict-route` | +| **macOS** | 完整支持(CLI、GUI、`utun` TUN) | 支持 `utun*` 设备及 Apple XCFramework 构建 | +| **FreeBSD** | CLI、TUN | 通过 `setfib` 多路由表(FIB)实现防环 | +| **Android** | FFI / TUN(`fd://`) / TProxy | 官方客户端:[clash-android](https://github.com/rust-proxy/clash-android) | +| **iOS / iPadOS** | FFI / TUN(`fd://`) | 官方客户端:[ChocLite](https://apps.apple.com/app/id6467517938) | + +## 文档导览 + +- **初次上手?** 请阅读 [快速开始](quick-start/index.md)、[命令行与环境变量](quick-start/cli.md) 或 [图形客户端与面板](quick-start/gui.md)。 +- **编写配置文件?** 请查阅 [基础配置](config/index.md)、[DNS 解析与服务](config/dns.md)、[TUN 虚拟网卡](config/tun.md)、[入站代理](config/inbounds/index.md)、[出站代理](config/outbounds/index.md)、[代理组](config/proxy-groups.md)、[路由规则](config/rules.md) 与 [完整配置示例](config/full.md)。 +- **从 Mihomo 迁移或对接控制面板?** 请参阅 [Mihomo 兼容与安全路径](guides/compatibility.md) 与 [REST API 与外部控制](guides/api.md)。 + +## 相关链接 + +- 源码仓库:[Watfaq/clash-rs](https://github.com/Watfaq/clash-rs) +- 版本发布:[GitHub Releases](https://github.com/Watfaq/clash-rs/releases) +- 容器镜像:[ghcr.io/watfaq/clash-rs](https://github.com/Watfaq/clash-rs/pkgs/container/clash-rs) +- 交流社区:[Telegram 用户群](https://t.me/thisisnotclash) diff --git a/docs/zh/quick-start.md b/docs/zh/quick-start.md deleted file mode 100644 index c8a254a..0000000 --- a/docs/zh/quick-start.md +++ /dev/null @@ -1,24 +0,0 @@ -# 快速开始 - -从 [ClashRS 发布页](https://github.com/Watfaq/clash-rs/releases)下载适合当前平台的可执行文件,放到 PATH 中,确保可以运行 `clash-rs`。 - -## 启动 HTTP 代理 - -将以下内容保存为 `config.yaml`: - -```yaml -port: 7890 -``` - -先检查配置,再启动 ClashRS: - -```sh -clash-rs -t -c config.yaml -clash-rs -c config.yaml -``` - -将应用程序的 HTTP 代理设为 `127.0.0.1:7890`。要使用 SOCKS 或自定义监听器,请参阅[入站监听](config/inbounds.md)。路由和出站配置可参考[完整配置示例](config/full.md)。 - -## 使用图形界面 - -[Clash Nyanpasu](https://github.com/LibNyanpasu/clash-nyanpasu) 提供支持 ClashRS 的图形界面。 diff --git a/docs/zh/quick-start/cli.md b/docs/zh/quick-start/cli.md new file mode 100644 index 0000000..45cbeca --- /dev/null +++ b/docs/zh/quick-start/cli.md @@ -0,0 +1,87 @@ +# 命令行与环境变量 + +本页列出 `clash-rs` 可执行文件支持的全部命令行参数与运行时环境变量。 + +## 命令行参数 + +```text +Usage: clash-rs [OPTIONS] +``` + +| 参数 | 短参数 / 别名 | 默认值 | 说明 | +| --- | --- | --- | --- | +| `--directory ` | `-d` | 当前工作目录(`.`) | 指定工作目录(`$CWD`),配置中的相对路径均基于此解析。在 `--compatibility` 且非 `--service-mode` 下,还会将进程工作目录切换至此目录。 | +| `--config ` | `-c`、`-f` | `config.yaml` | 指定配置文件路径。非 `--service-mode` 时按 `/` 解析(启动时可指向目录外的绝对路径),文件不存在会自动生成仅含 `port: 7890` 的默认配置;`--service-mode` 下受 `SafePaths` 约束且不会自动生成模板。 | +| `--test-config` | `-t` | `false` | 仅解析并校验配置文件后退出(成功退出码 `0`,失败退出码 `1`)。 | +| `--version` | `-v`、`-V` | `false` | 打印版本信息(`clash-rs `)后退出。 | +| `--log-file ` | `-l` | 无 | 在终端输出之外将日志追加写入文件(相对 `$CWD`)。**不能与 `--service-mode` 同时使用。** | +| `--controller-ipc ` | `--ext-ctl-unix`、`--ext-ctl-pipe`(亦兼容单横线 `-ext-ctl-unix`、`-ext-ctl-pipe`) | 无 | 覆盖配置中的 `external-controller-ipc`(Unix Domain Socket 或 Windows Named Pipe 路径),配置热重载时自动保留。 | +| `--controller-pipe-sddl ` | 仅 Windows(绑定环境变量 `LISTEN_NAMEDPIPE_SDDL`) | 无 | 设置控制器 Windows Named Pipe 的 SDDL 安全描述符。CLI 参数优先于环境变量,热重载时保留。 | +| `--compatibility` | — | `false` | 开启 Mihomo 兼容模式(默认加载 `Country.mmdb` / `geosite.dat`,并使用独立的 `clash-rs-cache.db`)。详见 [Mihomo 兼容与安全路径](../guides/compatibility.md)。 | +| `--service-mode` | — | `false` | 供高权限系统服务(如 Clash Verge Service)使用的受限模式。强制要求 `--directory`,禁止 `--log-file`,除 `-t` 外强制要求非空 `--controller-ipc`(Windows 上还需 `--controller-pipe-sddl` / `LISTEN_NAMEDPIPE_SDDL`);隐含启用 `--compatibility`,强制禁用 `SAFE_PATHS` / `SKIP_SAFE_PATH_CHECK`,禁止 `fd://` TUN、禁止 Naive 自定义 `cronet-lib-path`,并拒绝 `POST /restart`。 | +| `--strict-config` | — | `false` | 严格配置模式:拒绝任意嵌套层级上的未知 YAML 字段。默认关闭(静默忽略未知字段以兼容 Mihomo 等配置)。注意:通过 `PUT /configs` 热重载时不应用严格模式。 | +| `--help-improve` | — | `false` | 开启可选的崩溃上报(Sentry)。 | +| `--help` | `-h` | — | 打印帮助信息。 | + +!!! warning "Clash Verge Service 保护检查" + 若 `clash-rs` 可执行文件位于 `.../clash-verge-service/cores/` 目录下,必须携带 `--service-mode` 才能启动,否则会直接报错退出。 + +### 常用命令示例 + +```bash +# 指定工作目录与配置文件运行 +clash-rs -d /etc/clash -c config.yaml + +# 严格校验配置文件(排查拼写错误或不支持的字段) +clash-rs -d /etc/clash -c config.yaml -t --strict-config + +# 以 Mihomo 兼容模式启动并开启 Unix Socket 控制接口 +clash-rs --compatibility -d ~/.config/mihomo -f config.yaml --ext-ctl-unix /tmp/clash-rs.sock + +# 将日志同时输出到文件 +clash-rs -d ./data -c config.yaml -l clash.log +``` + +## 运行时环境变量 + +| 环境变量 | 格式 / 取值 | 默认值 | 作用 | +| --- | --- | --- | --- | +| `CLASH_RS_COMPATIBILITY_MODE` | `1` 或 `true`(忽略首尾空白与大小写) | 关闭 | 等同于传入 `--compatibility`,适合命令行固定的启动器。 | +| `SAFE_PATHS` | 绝对目录列表(Unix 用 `:` 分隔,Windows 用 `;` 分隔) | 空 | 允许配置文件在工作目录之外额外访问的根目录(用于 GeoData、Provider、证书、`external-ui`、重载路径等)。**`--service-mode` 下强制忽略。**详见 [安全路径](../guides/compatibility.md#safe-paths)。 | +| `SKIP_SAFE_PATH_CHECK` | `1`、`t`、`T`、`true`、`TRUE`、`True` | 关闭 | 跳过安全路径校验。**`--service-mode` 下强制忽略。** | +| `LISTEN_NAMEDPIPE_SDDL` | Windows SDDL 字符串 | `D:(A;;GRGW;;;BU)(A;;GRGW;;;SY)` | 未传 `--controller-pipe-sddl` 时,为 Windows Named Pipe 控制接口应用的默认 SDDL。 | +| `CLASH_RS_MEM_LIMIT_MB` | ``、`:soft` 或 `:hard`(`MB > 0`) | `0`(不限制) | 启用内存上限管理。若编译启用了 `jemallocator` 且未设置 `MALLOC_CONF`,同时会将 jemalloc arena 的 `dirty_decay_ms` 与 `muzzy_decay_ms` 调低至 `1000` ms 以加速 RSS 回收。 | +| `CLASH_RS_MEM_HARD_RATIO` | 浮点数(`>= 1.0`,设为 `0` 禁用 Hard 驱逐) | `2.0` | 相对 `CLASH_RS_MEM_LIMIT_MB` 的 Hard 模式触发倍率;触发时关闭 20% 活跃连接。 | +| `MALLOC_CONF` | 标准 jemalloc 配置字符串 | 未设置 | 一旦设置,ClashRS 不会在启用 `CLASH_RS_MEM_LIMIT_MB` 时覆盖 jemalloc 回收参数。 | +| `RUST_LOG` | `tracing_subscriber` 过滤指令 | `warn,clash=` | 设置且有效时覆盖默认日志过滤规则。 | +| `CLASH_RS_BACKOFF_ROUNDS` | 正整数 | `12` | 自动健康检查对连续失败 3 次及以上死节点的退避轮数(每 `N` 轮重试一次)。 | +| `CLASH_RS_HEALTHCHECK_CONCURRENCY` | 正整数 | `8` | 代理健康检查最大并发数。 | +| `SSLKEYLOGFILE` | 文件路径 | 未设置 | 设置后启用 `rustls::KeyLogFile` 导出 TLS 密钥日志,便于 Wireshark 抓包调试。 | + +## Linux systemd 服务配置示例 + +```ini title="/etc/systemd/system/clash-rs.service" +[Unit] +Description=ClashRS Proxy Core +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/clash-rs -d /etc/clash -c config.yaml +Restart=on-failure +RestartSec=3 +AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE +CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE +LimitNOFILE=1048576 + +[Install] +WantedBy=multi-user.target +``` + +启用并启动服务: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now clash-rs +``` diff --git a/docs/zh/quick-start/gui.md b/docs/zh/quick-start/gui.md new file mode 100644 index 0000000..65a4ec6 --- /dev/null +++ b/docs/zh/quick-start/gui.md @@ -0,0 +1,60 @@ +# 图形客户端与 Web 面板 + +ClashRS 既可以配合桌面图形客户端与基于 `clash-ffi` 的移动应用使用,也可以通过内置或外置 Web 面板在浏览器中进行可视化管理。 + +## 桌面端客户端 + +### Clash Nyanpasu + +[Clash Nyanpasu](https://github.com/LibNyanpasu/clash-nyanpasu) 在 Windows、macOS 与 Linux 上均直接支持切换使用 ClashRS 内核。 + +### Clash Verge + +ClashRS 已针对 Clash Verge 的配置与 Windows TUN 参数提供兼容支持: + +1. 在 Clash Verge 内核设置中选择 **ClashRS** 内核。 +2. 若使用 **Clash Verge Service**(服务模式),请将配置文件及所有引用的外部文件(GeoData、Provider、证书等)放在服务运行目录内,因为服务模式会强制开启 [安全路径约束](../guides/compatibility.md#safe-paths)。 +3. 在 Windows 上开启 **TUN** 时,无论界面中选择哪种协议栈选项(`system`、`gvisor`、`mixed`),ClashRS 均统一使用内置 Rust 网络协议栈;只要 `wintun.dll` 存在或已内嵌即可直接工作。 + +## 移动端客户端 + +| 平台 | 客户端 | 说明 | +| --- | --- | --- | +| **Android** | [clash-android](https://github.com/rust-proxy/clash-android) | 基于 `clash-ffi`,支持 Android VPN `fd://` TUN 与 TProxy | +| **iOS / iPadOS** | [ChocLite](https://apps.apple.com/app/id6467517938) | 基于 ClashRS 构建的官方 iOS 客户端([TestFlight 测试版](https://testflight.apple.com/join/cLy4Ub5C)) | + +## 内置与外置 Web 面板 + +配置 `external-controller` 后,即可通过 `/ui/` 路径访问 Web 管理界面。 + +### 使用内置面板 + +默认发布版启用了 `dashboard` 编译特性,无需额外下载前端资源: + +```yaml +external-controller: 127.0.0.1:9090 +secret: "change-me" +``` + +启动后在浏览器访问 `http://127.0.0.1:9090/ui/` 即可。 + +### 使用外置面板(`external-ui`) + +如需使用第三方前端面板(如 Metacubexd、Yacd 等),可配置 `external-ui` 与可选的 `external-ui-url`: + +```yaml +external-controller: 127.0.0.1:9090 +secret: "change-me" +external-ui: ui +external-ui-url: "https://github.com/MetaCubeX/metacubexd/archive/refs/heads/gh-pages.zip" +``` + +- `external-ui` 相对于工作目录(`-d`)解析,并受安全路径检查约束。 +- 当目录不存在或为空且配置了 `external-ui-url` 时,ClashRS 会自动下载并解压(支持 `.zip` 与 `.tgz`)。 +- `external-ui-url` 支持以下 URL 片段参数: + - `#force=true`:即使目录非空也强制重新下载。 + - `#_clash_outbound=`:通过指定出站代理下载面板压缩包。 +- 若目录缺失/为空且未下载成功,在启用 `dashboard` 特性时会自动回退到内置面板。 + +!!! warning "对外暴露控制端口的安全要求" + 当 `external-controller` 监听非本机回环地址(如 `0.0.0.0:9090`)时,ClashRS 强制要求同时配置非空 `secret` 和 CORS 允许来源(`external-controller-cors` 或 `cors-allow-origins`),否则控制接口会拒绝启动。详见 [REST API 与外部控制](../guides/api.md)。 diff --git a/docs/zh/quick-start/index.md b/docs/zh/quick-start/index.md new file mode 100644 index 0000000..07a55bf --- /dev/null +++ b/docs/zh/quick-start/index.md @@ -0,0 +1,144 @@ +# 快速开始 + +本节介绍如何安装 ClashRS、编写最小可用配置并验证代理连通性。 + +## 安装方式 + +=== "下载预编译二进制" + + 前往 [GitHub Releases](https://github.com/Watfaq/clash-rs/releases) 下载与操作系统及 CPU 架构匹配的压缩包。 + + 在 Linux / macOS 上赋予可执行权限并检查版本: + + ```bash + chmod +x clash-rs + ./clash-rs -v + ``` + + !!! note "Windows TUN 依赖说明" + 在 Windows 上使用标准构建启用 TUN 时,需以管理员身份运行,并将对应架构的 [`wintun.dll`](https://wintun.net/) 放在 `clash-rs.exe` 同级目录下。若自行通过 MSVC 编译,也可启用 `--features wintun-embed` 将 Wintun 直接内嵌进可执行文件。 + +=== "Docker 运行" + + 官方镜像发布在 GitHub Container Registry: + + ```bash + docker run -d \ + --name clash-rs \ + --restart unless-stopped \ + -p 7890:7890 \ + -p 9090:9090 \ + -v /path/to/clash-config:/etc/clash \ + ghcr.io/watfaq/clash-rs:latest \ + -d /etc/clash -c config.yaml + ``` + + 如在 Linux 容器内启用 TUN,还需附加 `--cap-add NET_ADMIN --device /dev/net/tun`。 + +=== "从源码编译" + + ### 构建依赖 + + - Rust 工具链(Edition 2024) + - `cmake`(3.29 及以上) + - `libclang`(LLVM) + - `protoc`(用于生成 GeoData Protobuf 代码) + - `nasm`(仅 Windows 需要) + + ### 编译命令 + + ```bash + git clone https://github.com/Watfaq/clash-rs.git + cd clash-rs + + # 标准 Release 构建(默认特性:standard、aws-lc-rs、dashboard) + cargo build --release + + # Plus 构建(额外包含 Tor / onion 出站) + cargo build --release --features plus + + # 包含静态 Cronet 的 Naive 出站构建 + cargo build --locked --release -p clash-rs --features naive-static,naive-download + ``` + +### Cargo 特性组合(Features) + +| 特性名 | 包含能力 | +| --- | --- | +| `default`(`clash-bin`) | `standard`、`aws-lc-rs`、`dashboard` | +| `standard` | `shadowsocks`、`tuic`、`ssh`、`shadowquic`、`wireguard`、`tailscale`、`zero_copy`、`tproxy`、`tun`、`redir` | +| `plus` | `standard` 全部能力 + `onion`(Tor) | +| `naive` / `naive-static` / `naive-download` | Naive 出站(基于 Cronet);**默认未启用** | +| `wintun-embed` | Windows MSVC 构建内嵌 `wintun.dll` | +| `telemetry` | OpenTelemetry / Jaeger 链路追踪导出 | + +## 编写最小配置 + +创建一个工作目录并保存 `config.yaml`: + +```yaml +mixed-port: 7890 +allow-lan: false +mode: rule +log-level: info +external-controller: 127.0.0.1:9090 + +proxies: + - name: demo-ss + type: ss + server: proxy.example.com + port: 8388 + cipher: 2022-blake3-aes-128-gcm + password: "YOUR_BASE64_PASSWORD" + udp: true + +proxy-groups: + - name: PROXY + type: select + proxies: + - demo-ss + - DIRECT + +rules: + - DOMAIN-SUFFIX,example.com,PROXY + - MATCH,DIRECT +``` + +!!! tip "自动创建默认模板" + 在非 `--service-mode` 模式下,如果指定的配置文件尚不存在,ClashRS 会自动生成一个仅包含 `port: 7890` 的默认配置文件。 + +## 校验并启动 + +1. **先校验配置文件语法与逻辑**: + + ```bash + clash-rs -d ./clash-data -c config.yaml -t + ``` + + 若希望拒绝配置中的未知字段(而非静默忽略),可同时加上 `--strict-config`: + + ```bash + clash-rs -d ./clash-data -c config.yaml -t --strict-config + ``` + +2. **启动 ClashRS**: + + ```bash + clash-rs -d ./clash-data -c config.yaml + ``` + +3. **验证代理工作正常**: + + ```bash + curl -x http://127.0.0.1:7890 https://example.com + ``` + +4. **打开内置 Web 面板**: + + 配置 `external-controller` 且使用默认 `dashboard` 特性构建时,直接在浏览器访问 `http://127.0.0.1:9090/ui/` 即可管理节点与连接。 + +## 下一步 + +- 查看所有命令行参数与环境变量:[命令行与环境变量](cli.md) +- 配合桌面或移动端客户端使用:[图形客户端与面板](gui.md) +- 深入学习各项配置参数:[配置参考](../config/index.md) diff --git a/shared/full-example.md b/shared/full-example.md index 4703a6f..53d0c8a 100644 --- a/shared/full-example.md +++ b/shared/full-example.md @@ -1,231 +1,238 @@ -```yaml ---- -port: 8888 -socks-port: 8889 -mixed-port: 8899 - -tun: - enable: false - device-id: "dev://utun1989" - -dns: - enable: true - listen: 127.0.0.1:53553 - # udp: 127.0.0.1:53553 - # tcp: 127.0.0.1:53553 - # dot: 127.0.0.1:53554 - # doh: 127.0.0.1:53555 - - # ipv6: false # when the false, response to AAAA questions will be empty - - # These nameservers are used to resolve the DNS nameserver hostnames below. - # Specify IP addresses only - default-nameserver: - - 114.114.114.114 - - 8.8.8.8 - enhanced-mode: fake-ip - fake-ip-range: 198.18.0.2/16 # Fake IP addresses pool CIDR - # use-hosts: true # lookup hosts and return IP record - - # Hostnames in this list will not be resolved with fake IPs - # i.e. questions to these domain names will always be answered with their - # real IP addresses - # fake-ip-filter: - # - '*.lan' - # - localhost.ptlogin2.qq.com - - # Supports UDP, TCP, DoT, DoH. You can specify the port to connect to. - # All DNS questions are sent directly to the nameserver, without proxies - # involved. Clash answers the DNS question with the first result gathered. - nameserver: - - 114.114.114.114 # default value - - 1.1.1.1 # default value - - tls://1.1.1.1:853 # DNS over TLS - - https://1.1.1.1/dns-query # DNS over HTTPS -# - dhcp://en0 # dns from dhcp - -allow-lan: true -mode: rule -log-level: debug -external-controller: 127.0.0.1:9090 -external-ui: "public" -# secret: "clash-rs" -experimental: - ignore-resolve-fail: true - -profile: - store-selected: true - store-fake-ip: false - - -proxy-groups: - - name: "relay" - type: relay - proxies: - - "plain-vmess" - - "ws-vmess" - - "auto" - - "fallback-auto" - - "load-balance" - - "select" - - DIRECT - - - name: "relay-one" - type: relay - use: - - "file-provider" - - - name: "auto" - type: url-test - use: - - "file-provider" - proxies: - - DIRECT - url: "http://www.gstatic.com/generate_204" - interval: 300 - - - name: "fallback-auto" - type: fallback - use: - - "file-provider" - proxies: - - DIRECT - url: "http://www.gstatic.com/generate_204" - interval: 300 - - - name: "load-balance" - type: load-balance - use: - - "file-provider" - proxies: - - DIRECT - strategy: round-robin - url: "http://www.gstatic.com/generate_204" - interval: 300 - - - name: select - type: select - use: - - "file-provider" - - - name: test 🌏 - type: select - use: - - "file-provider" - proxies: - - DIRECT - -proxies: - - name: plain-vmess - type: vmess - server: 10.0.0.13 - port: 16823 - uuid: b831381d-6324-4d53-ad4f-8cda48b30811 - alterId: 0 - cipher: auto - udp: true - skip-cert-verify: true - - name: ws-vmess - type: vmess - server: 10.0.0.13 - port: 16824 - uuid: b831381d-6324-4d53-ad4f-8cda48b30811 - alterId: 0 - cipher: auto - udp: true - skip-cert-verify: true - network: ws - ws-opts: - path: /api/v3/download.getFile - headers: - Host: www.amazon.com - - - name: tls-vmess - type: vmess - server: 10.0.0.13 - port: 8443 - uuid: 23ad6b10-8d1a-40f7-8ad0-e3e35cd38297 - alterId: 0 - cipher: auto - udp: true - skip-cert-verify: true - tls: true - - - name: h2-vmess - type: vmess - server: 10.0.0.13 - port: 8444 - uuid: b831381d-6324-4d53-ad4f-8cda48b30811 - alterId: 0 - cipher: auto - udp: true - skip-cert-verify: true - tls: true - network: h2 - h2-opts: - path: /ray - - - name: vmess-altid - type: vmess - server: tw-1.ac.laowanxiang.com - port: 153 - uuid: 46dd0dd3-2cc0-3f55-907c-d94e54877687 - alterId: 64 - cipher: auto - udp: true - network: ws - ws-opts: - path: /api/v3/download.getFile - headers: - Host: 5607b9d187e655736f563fee87d7283994721.laowanxiang.com - - name: "ss-simple" - type: ss - server: 10.0.0.13 - port: 8388 - cipher: aes-256-gcm - password: "password" - udp: true - - name: "trojan" - type: trojan - server: 10.0.0.13 - port: 9443 - password: password1 - udp: true - # sni: example.com # aka server name - alpn: - - h2 - - http/1.1 - skip-cert-verify: true - -proxy-providers: - file-provider: - type: file - path: ./ss.yaml - interval: 300 - health-check: - enable: true - url: http://www.gstatic.com/generate_204 - interval: 300 - -rule-providers: - file-provider: - type: file - path: ./rule-set.yaml - interval: 300 - behavior: domain - -rules: - - DOMAIN,ipinfo.io,relay - - RULE-SET,file-provider,trojan - - GEOIP,CN,relay - - DOMAIN-SUFFIX,facebook.com,REJECT - - DOMAIN-KEYWORD,google,select - - DOMAIN,google.com,select - - SRC-IP-CIDR,192.168.1.1/24,DIRECT - - GEOIP,CN,DIRECT - - DST-PORT,53,trojan - - SRC-PORT,7777,DIRECT - - MATCH, DIRECT -... - -``` \ No newline at end of file +```yaml +# General +mixed-port: 7890 +allow-lan: false +bind-address: 127.0.0.1 +mode: rule +log-level: info +ipv6: true +unified-delay: true + +# External controller & Web Dashboard +external-controller: 127.0.0.1:9090 +secret: "replace-with-a-strong-secret" +external-ui: ui + +# GeoData (optional; auto-defaulted in --compatibility mode) +mmdb: Country.mmdb +geosite: geosite.dat + +# Persistent caches +profile: + store-selected: true + store-fake-ip: false + store-smart-stats: true + +# Static hosts (active when dns.use-hosts is true) +hosts: + router.lan: 192.168.1.1 + +# Built-in anti-spoofing DNS +dns: + enable: true + ipv6: true + use-hosts: true + listen: + udp: 127.0.0.1:5353 + tcp: 127.0.0.1:5353 + enhanced-mode: fake-ip + fake-ip-range: 198.18.0.1/16 + fake-ip-filter: + - "*.lan" + - "+.local" + - "time.windows.com" + default-nameserver: + - 223.5.5.5 + - 8.8.8.8 + proxy-server-nameserver: + - https://dns.alidns.com/dns-query + nameserver: + - 223.5.5.5 + - 119.29.29.29 + fallback: + - tls://1.1.1.1:853 + - https://dns.google/dns-query + fallback-filter: + geoip: true + geoip-code: CN + ipcidr: + - 240.0.0.0/4 + nameserver-policy: + "+.internal.example.com": 192.168.1.1 + +# TUN (disabled by default; enable as needed) +tun: + enable: false + stack: mixed + auto-route: true + auto-detect-interface: true + strict-route: false + dns-hijack: + - any:53 + route-exclude-address: + - 192.168.0.0/16 + - 10.0.0.0/8 + +# Explicit extra listeners & fixed tunnels +listeners: + - name: local-socks + type: socks + listen: 127.0.0.1 + port: 7891 + allow-lan: false + +tunnels: + - network: [tcp, udp] + address: 127.0.0.1:1053 + target: 1.1.1.1:53 + proxy: PROXY + +# Outbound proxies +proxies: + - name: ss-2022 + type: ss + server: ss.example.com + port: 8388 + cipher: 2022-blake3-aes-128-gcm + password: "REPLACE_WITH_BASE64_PSK" + udp: true + + - name: vless-reality + type: vless + server: reality.example.com + port: 443 + uuid: "00000000-0000-0000-0000-000000000000" + udp: true + tls: true + flow: xtls-rprx-vision + servername: www.example.org + reality-opts: + public-key: "REPLACE_WITH_32BYTE_URLSAFE_BASE64_KEY" + short-id: "0123456789abcdef" + + - name: trojan-grpc + type: trojan + server: trojan.example.com + port: 443 + password: "replace-with-password" + sni: trojan.example.com + udp: true + network: grpc + grpc-opts: + grpc-service-name: "trojan-grpc" + + - name: vmess-ws + type: vmess + server: vmess.example.com + port: 443 + uuid: "00000000-0000-0000-0000-000000000000" + alterId: 0 + cipher: auto + udp: true + tls: true + servername: vmess.example.com + network: ws + ws-opts: + path: /ws + headers: + Host: vmess.example.com + + - name: tuic-v5 + type: tuic + server: tuic.example.com + port: 8443 + uuid: "00000000-0000-0000-0000-000000000000" + password: "replace-with-password" + sni: tuic.example.com + alpn: + - h3 + udp-relay-mode: native + congestion-controller: bbr3 + reduce-rtt: true + + - name: hy2-node + type: hysteria2 + server: hy2.example.com + port: 443 + password: "replace-with-password" + sni: hy2.example.com + skip-cert-verify: false + + - name: anytls-node + type: anytls + server: anytls.example.com + port: 443 + password: "replace-with-password" + sni: anytls.example.com + udp: true + +# Proxy groups +proxy-groups: + - name: PROXY + type: select + proxies: + - AUTO + - SMART + - FALLBACK + - ss-2022 + - vless-reality + - trojan-grpc + - vmess-ws + - tuic-v5 + - hy2-node + - anytls-node + - DIRECT + + - name: AUTO + type: url-test + proxies: + - ss-2022 + - vless-reality + - tuic-v5 + - hy2-node + url: http://www.gstatic.com/generate_204 + interval: 300 + tolerance: 50 + + - name: SMART + type: smart + proxies: + - ss-2022 + - vless-reality + - tuic-v5 + - hy2-node + udp: true + max-retries: 3 + + - name: FALLBACK + type: fallback + proxies: + - vless-reality + - trojan-grpc + - ss-2022 + - DIRECT + url: http://www.gstatic.com/generate_204 + interval: 300 + +# Rule providers (inline example requires no external files) +rule-providers: + private-domains: + type: inline + behavior: domain + payload: + - "+.lan" + - "+.local" + - "localhost" + +# Routing rules +rules: + - RULE-SET,private-domains,DIRECT + - IP-CIDR,127.0.0.0/8,DIRECT,no-resolve + - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve + - IP-CIDR,172.16.0.0/12,DIRECT,no-resolve + - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve + - GEOSITE,cn,DIRECT + - GEOIP,CN,DIRECT,no-resolve + - AND,((NETWORK,UDP),(DST-PORT,443)),REJECT + - MATCH,PROXY +``` diff --git a/zensical.toml b/zensical.toml index e0cd84b..48bec2a 100644 --- a/zensical.toml +++ b/zensical.toml @@ -8,11 +8,42 @@ repo_url = "https://github.com/Watfaq/clash-rs" edit_uri = "https://github.com/Watfaq-legacy/docs/edit/master/docs/en/" nav = [ { "Overview" = "index.md" }, - { "Quick start" = "quick-start.md" }, + { "Quick start" = [ + "quick-start/index.md", + { "CLI & environment" = "quick-start/cli.md" }, + { "GUI & clients" = "quick-start/gui.md" }, + ] }, { "Configuration" = [ - { "Inbounds" = "config/inbounds.md" }, + "config/index.md", + { "Common types & transports" = "config/types.md" }, + { "DNS" = "config/dns.md" }, + { "TUN" = "config/tun.md" }, + { "Inbounds" = [ + "config/inbounds/index.md", + { "HTTP & Mixed" = "config/inbounds/http.md" }, + { "SOCKS5" = "config/inbounds/socks.md" }, + { "Transparent proxy" = "config/inbounds/transparent.md" }, + { "Tunnel" = "config/inbounds/tunnel.md" }, + { "Proxy protocols" = "config/inbounds/protocols.md" }, + ] }, + { "Outbounds" = [ + "config/outbounds/index.md", + { "Shadowsocks" = "config/outbounds/shadowsocks.md" }, + { "Trojan, VMess & VLESS" = "config/outbounds/v2ray.md" }, + { "TUIC" = "config/outbounds/tuic.md" }, + { "Hysteria2 & ShadowQUIC" = "config/outbounds/quic.md" }, + { "AnyTLS, Naive & SOCKS5" = "config/outbounds/tls-socks.md" }, + { "WireGuard, SSH, Tailscale & Tor" = "config/outbounds/vpn.md" }, + ] }, + { "Proxy groups" = "config/proxy-groups.md" }, + { "Routing rules" = "config/rules.md" }, + { "Providers" = "config/providers.md" }, { "Full example" = "config/full.md" }, ] }, + { "Guides" = [ + { "Mihomo compatibility & safe paths" = "guides/compatibility.md" }, + { "REST API & controller" = "guides/api.md" }, + ] }, ] [project.theme] @@ -21,8 +52,9 @@ custom_dir = "overrides" logo = "assets/images/clashrs.png" favicon = "assets/images/clashrs.png" features = [ - "navigation.tracking", "navigation.path", "navigation.top", "navigation.tabs", - "navigation.sections", "search.highlight", "content.action.edit", + "navigation.tracking", "navigation.path", "navigation.indexes", + "navigation.top", "navigation.tabs", "navigation.sections", + "search.suggest", "search.highlight", "content.action.edit", "content.code.copy", "content.code.annotate", "content.tabs.link", ] @@ -40,8 +72,15 @@ toggle = { icon = "lucide/sun", name = "Switch to light mode" } [project.markdown_extensions.tables] [project.markdown_extensions.admonition] +[project.markdown_extensions.attr_list] +[project.markdown_extensions.def_list] +[project.markdown_extensions.toc] +permalink = true [project.markdown_extensions."pymdownx.details"] [project.markdown_extensions."pymdownx.superfences"] +[project.markdown_extensions."pymdownx.inlinehilite"] +[project.markdown_extensions."pymdownx.tabbed"] +alternate_style = true [project.markdown_extensions."pymdownx.highlight"] anchor_linenums = true line_spans = "__span" diff --git a/zensical.zh.toml b/zensical.zh.toml index 3991870..b0f1ecf 100644 --- a/zensical.zh.toml +++ b/zensical.zh.toml @@ -8,11 +8,42 @@ repo_url = "https://github.com/Watfaq/clash-rs" edit_uri = "https://github.com/Watfaq-legacy/docs/edit/master/docs/zh/" nav = [ { "概览" = "index.md" }, - { "快速开始" = "quick-start.md" }, + { "快速开始" = [ + "quick-start/index.md", + { "命令行与环境变量" = "quick-start/cli.md" }, + { "图形客户端与面板" = "quick-start/gui.md" }, + ] }, { "配置" = [ - { "入站监听" = "config/inbounds.md" }, + "config/index.md", + { "通用类型与传输层" = "config/types.md" }, + { "DNS 解析与服务" = "config/dns.md" }, + { "TUN 虚拟网卡" = "config/tun.md" }, + { "入站监听" = [ + "config/inbounds/index.md", + { "HTTP 与 Mixed" = "config/inbounds/http.md" }, + { "SOCKS5" = "config/inbounds/socks.md" }, + { "透明代理(TProxy / Redir)" = "config/inbounds/transparent.md" }, + { "端口转发(Tunnel)" = "config/inbounds/tunnel.md" }, + { "协议入站(SS / AnyTLS / Hysteria2)" = "config/inbounds/protocols.md" }, + ] }, + { "出站代理" = [ + "config/outbounds/index.md", + { "Shadowsocks" = "config/outbounds/shadowsocks.md" }, + { "Trojan / VMess / VLESS" = "config/outbounds/v2ray.md" }, + { "TUIC" = "config/outbounds/tuic.md" }, + { "Hysteria2 与 ShadowQUIC" = "config/outbounds/quic.md" }, + { "AnyTLS / Naive / SOCKS5" = "config/outbounds/tls-socks.md" }, + { "WireGuard / SSH / Tailscale / Tor" = "config/outbounds/vpn.md" }, + ] }, + { "代理组" = "config/proxy-groups.md" }, + { "路由规则" = "config/rules.md" }, + { "提供者(Providers)" = "config/providers.md" }, { "完整示例" = "config/full.md" }, ] }, + { "进阶指南" = [ + { "Mihomo 兼容与安全路径" = "guides/compatibility.md" }, + { "REST API 与外部控制" = "guides/api.md" }, + ] }, ] [project.theme] @@ -21,8 +52,9 @@ custom_dir = "overrides" logo = "assets/images/clashrs.png" favicon = "assets/images/clashrs.png" features = [ - "navigation.tracking", "navigation.path", "navigation.top", "navigation.tabs", - "navigation.sections", "search.highlight", "content.action.edit", + "navigation.tracking", "navigation.path", "navigation.indexes", + "navigation.top", "navigation.tabs", "navigation.sections", + "search.suggest", "search.highlight", "content.action.edit", "content.code.copy", "content.code.annotate", "content.tabs.link", ] @@ -40,8 +72,15 @@ toggle = { icon = "lucide/sun", name = "切换到浅色模式" } [project.markdown_extensions.tables] [project.markdown_extensions.admonition] +[project.markdown_extensions.attr_list] +[project.markdown_extensions.def_list] +[project.markdown_extensions.toc] +permalink = true [project.markdown_extensions."pymdownx.details"] [project.markdown_extensions."pymdownx.superfences"] +[project.markdown_extensions."pymdownx.inlinehilite"] +[project.markdown_extensions."pymdownx.tabbed"] +alternate_style = true [project.markdown_extensions."pymdownx.highlight"] anchor_linenums = true line_spans = "__span"