1
0
mirror of https://github.com/XTLS/Xray-docs-next.git synced 2025-02-21 17:03:15 +03:00

XHTTP: Beyond REALITY

https://github.com/XTLS/Xray-core/discussions/4113
This commit is contained in:
RPRX 2024-12-13 10:47:12 +00:00
parent dcc39472dd
commit a6af837cb5
39 changed files with 300 additions and 1243 deletions

@ -63,13 +63,12 @@ export const sidebarEn: SidebarConfig = {
{
text: 'transport',
children: [
'/en/config/transports/grpc.md',
'/en/config/transports/h2.md',
'/en/config/transports/raw.md',
'/en/config/transports/xhttp.md',
'/en/config/transports/mkcp.md',
'/en/config/transports/tcp.md',
'/en/config/transports/grpc.md',
'/en/config/transports/websocket.md',
'/en/config/transports/httpupgrade.md',
'/en/config/transports/splithttp.md'
],
},
],

@ -63,13 +63,12 @@ export const sidebarRu: SidebarConfig = {
{
text: 'Транспортный уровень',
children: [
'/ru/config/transports/grpc.md',
'/ru/config/transports/http.md',
'/ru/config/transports/mkcp.md',
'/ru/config/transports/raw.md',
'/ru/config/transports/xhttp.md',
'/ru/config/transports/mkcp.md',
'/ru/config/transports/grpc.md',
'/ru/config/transports/websocket.md',
'/ru/config/transports/httpupgrade.md',
'/ru/config/transports/splithttp.md'
],
},
],

@ -63,13 +63,12 @@ export const sidebarZh: SidebarConfig = {
{
text: '底层传输',
children: [
'/config/transports/grpc.md',
'/config/transports/http.md',
'/config/transports/mkcp.md',
'/config/transports/raw.md',
'/config/transports/xhttp.md',
'/config/transports/mkcp.md',
'/config/transports/grpc.md',
'/config/transports/websocket.md',
'/config/transports/httpupgrade.md',
'/config/transports/splithttp.md'
],
},
],

@ -11,7 +11,7 @@
不过目前的浏览器转发有以下缺点:
* 用户需要手动开浏览器
* 浏览器发出的连接必须直连 使用 tun 的用户需要特别注意容易形成死循环
* 浏览器只能发出 HTTP 连接 所以目前仅支持 [WebSocket](../../transports/websocket.md) 与 [XHTTP](../../transports/splithttp.md) 传输方式
* 浏览器只能发出 HTTP 连接 所以目前仅支持 [WebSocket](../../transports/websocket.md) 与 [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113) 传输方式
* 当浏览器从 `localhost:8080` 页面连接至代理服务端,需要考虑 [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
* 因为中间经过 JS 处理数据,会有一些性能损耗
* 不能使用自定义 SNI 或者 Host也就是说 `SNI == host == address`。自定义 HTTP 头以及其它 `tlsSettings` 项会被忽略
@ -44,6 +44,6 @@
<Badge text="v1.8.19+" type="warning"/>
XHTTP 本身支持 QUIC如果想使用浏览器自己的 QUIC 网络栈Chrome 可以在 `chrome://flags` 中设定。其它浏览器也有相关选项。
[XHTTP](https://github.com/XTLS/Xray-core/discussions/4113) 本身支持 QUIC如果想使用浏览器自己的 QUIC 网络栈Chrome 可以在 `chrome://flags` 中设定。其它浏览器也有相关选项。
原理上说 `tlsSettings` 项会被忽略,使用哪个 HTTP 版本将完全由浏览器决定。

@ -10,17 +10,16 @@
```json
{
"network": "tcp",
"network": "raw",
"security": "none",
"tlsSettings": {},
"realitySettings": {},
"tcpSettings": {},
"kcpSettings": {},
"wsSettings": {},
"httpSettings": {},
"grpcSettings": {},
"httpupgradeSettings": {},
"rawSettings": {},
"xhttpSettings": {},
"kcpSettings": {},
"grpcSettings": {},
"wsSettings": {},
"httpupgradeSettings": {},
"sockopt": {
"mark": 0,
"tcpMaxSeg": 1440,
@ -42,16 +41,12 @@
}
```
> `network`: "raw" | "ws" | "h2" | "grpc" | "kcp" | "httpupgrade" | "xhttp"
> `network`: "raw" | "xhttp" | "kcp" | "grpc" | "ws" | "httpupgrade"
连接的数据流所使用的传输方式类型,默认值为 `"raw"`
连接的数据流所使用的传输方式类型,默认值为 `"raw"`
::: tip
v24.9.30 版本后为了更贴近实际行为tcp传输方式已更名为raw, 为了兼容性,`"network": "raw"` 和 "network": "tcp", `rawSettings``tcpSettings` 互为别名
:::
::: tip
"h2" 可以写成 "http""grpc" 可以写成 "gun""kcp" 可以写成 "mkcp"。
v24.9.30 版本后为了更贴近实际行为TCP 传输方式已更名为 RAW。为了兼容性`"network": "raw"``"network": "tcp"``rawSettings``tcpSettings` 互为别名。
:::
> `security`: "none" | "tls" | "reality"
@ -75,34 +70,30 @@ Reality 是目前最安全的传输加密方案, 且外部看来流量类型和
达到数倍甚至十几倍的性能提升。
:::
> `rawSettings`: [TcpObject](./transports/raw.md)
> `rawSettings`: [RawObject](./transports/raw.md)
当前连接的 raw 配置,仅当此连接使用 raw 时有效。
当前连接的 RAW 配置,仅当此连接使用 RAW 时有效。
> `xhttpSettings`: [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)
当前连接的 XHTTP 配置,仅当此连接使用 XHTTP 时有效。
> `kcpSettings`: [KcpObject](./transports/mkcp.md)
当前连接的 mKCP 配置,仅当此连接使用 mKCP 时有效。
> `grpcSettings`: [GRPCObject](./transports/grpc.md)
当前连接的 gRPC 配置,仅当此连接使用 gRPC 时有效。
> `wsSettings`: [WebSocketObject](./transports/websocket.md)
当前连接的 WebSocket 配置,仅当此连接使用 WebSocket 时有效。
> `httpSettings`: [HttpObject](./transports/http.md)
当前连接的 HTTP 配置,仅当此连接使用 HTTP 时有效。
> `grpcSettings`: [GRPCObject](./transports/grpc.md)
当前连接的 gRPC 配置,仅当此连接使用 gRPC 时有效。。
> `httpupgradeSettings`: [HttpUpgradeObject](./transports/httpupgrade.md)
当前连接的 HTTPUpgrade 配置,仅当此连接使用 HTTPUpgrade 时有效。
> `xhttpSettings`: [XHttpObject](./transports/splithttp.md)
当前连接的 XHTTP 配置,仅当此连接使用 XHTTP 时有效。
> `sockopt`: [SockoptObject](#sockoptobject)
透明代理相关的具体配置。

@ -5,6 +5,10 @@
它基于 HTTP/2 协议,理论上可以通过其它支持 HTTP/2 的服务器(如 Nginx进行中转。
gRPCHTTP/2内置多路复用不建议使用 gRPC 与 HTTP/2 时启用 mux.cool。
::: danger
**推荐换用 [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113),其相较于 gRPC 的优势已在 STREAM-UP/ONE 小节中注明。**
:::
::: warning ⚠⚠⚠
- gRPC 不支持指定 Host。请在出站代理地址中填写 **正确的域名** ,或在 `(x)tlsSettings` 中填写 `ServerName`,否则无法连接。

@ -0,0 +1,3 @@
# HTTP/2
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -1,87 +1,3 @@
# HTTP
基于 HTTP/2 或 HTTP/3 的传输方式。
它完整按照 HTTP 标准实现,可以通过其它的 HTTP 服务器(如 Nginx进行中转。
客户端必须开启 TLS 才可以正常使用这个传输方式。
HTTP/2和3 内置多路复用,不建议使用时启用 mux.cool。
::: tip
当前版本的 HTTP/2 的传输方式并不强制要求**入站****服务端**)有 TLS 配置.
这使得可以在特殊用途的分流部署环境中,由外部网关组件完成 TLS 层对话Xray 作为后端应用,网关和 Xray 间使用明文HTTP进行通讯。
:::
::: tip
当alpn有且仅有 `h3`该传输才会工作在h3模式。
:::
::: warning
- HTTP/2 和 HTTP/3 无法通过xray的回落 Path 进行分流,不建议使用回落分流。
:::
## HttpObject
`HttpObject` 对应传输配置的 `httpSettings` 项。
```json
{
"host": ["xray.com"],
"path": "/random/path",
"read_idle_timeout": 10,
"health_check_timeout": 15,
"method": "PUT",
"headers": {
"Header": ["value"]
}
}
```
> `host`: \[string\]
一个字符串数组,每一个元素是一个域名。
客户端会随机从列表中选出一个域名进行通信,服务器会验证域名是否在列表中。
::: tip
若不写 `"httpSettings"``"host": []` 值留空时,会使用默认值 `"www.example.com"`,需要两端 `"host"` 值一致才能连接成功。`"host": [""]` 不是值留空。
:::
> `path`: string
HTTP 路径,由 `/` 开头, 客户端和服务器必须一致。
默认值为 `"/"`
> `read_idle_timeout`: number
单位秒,当这段时间内没有接收到数据时,将会进行健康检查。
健康检查默认**不启用**。
::: tip
**只需**在**出站****客户端**)配置。
:::
::: tip
可能会解决一些“断流”问题。
:::
> `health_check_timeout`: number
单位秒,健康检查的超时时间。如果在这段时间内没有完成健康检查,即认为健康检查失败。默认值为 `15`
::: tip
**只需**在**出站****客户端**)配置。
:::
> `method`: string
HTTP 方法。默认值为 `"PUT"`
设置时应参照[此处](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)列出值。
> `headers`: map{ string: \[string\] }
仅客户端,自定义 HTTP 头,一个键值对,每个键表示一个 HTTP 头名称,对应值为一个数组。
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -3,6 +3,10 @@
一个实现了类似于 WebSocket 进行 HTTP 1.1 升级请求和响应的协议,这使得它可以像 WebSocket 一样可以被CDN或者Nginx进行反代但无需实现 WebSocket 协议的其他部分,所以具有更高的效率。
其设计不推荐单独使用而是和TLS等安全协议一起工作。
::: danger
**推荐换用 [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113),以避免 HTTPUpgrade “ALPN 是 http/1.1” 等显著流量特征。**
:::
## HttpUpgradeObject
`HttpUpgradeObject` 对应传输配置的 `httpupgradeSettings` 项。

@ -0,0 +1,3 @@
# QUIC
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -1,8 +1,8 @@
# RAW
更名自曾经的tcp传输(原名称稍有歧义) RAW传输出站发送的原始数据核心不使用其他协议(如 websocket)承载其流量。
更名自曾经的 TCP 传输层(原名称有歧义),出站 RAW 传输层直接发送经代理协议包装后产生的 TCP、UDP 数据,核心不使用其它传输层(如 [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113)承载其流量。
可以和各种协议有多种组合模式.
可以和各种协议有多种组合模式
## RawObject

@ -1,265 +1,3 @@
# XHTTP (SplitHTTP)
# SplitHTTP
<Badge text="v1.8.16+" type="warning"/>
使用HTTP分块传输编码流式响应处理下载使用多个 HTTP POST 请求(或者流式)进行上传。
可以通过不支持WebSocket的CDN上但仍有一些要求
- CDN必须支持HTTP分块传输且支持流式响应而不会缓冲核心将会发送各种信息以告知CDN但是需要CDN遵守。如果中间盒不支持流式响应而导致连接被挂起则该传输很可能无法工作。
目的与V2fly Meek相同由于使用了流式响应处理下载下行速率更为优秀上行也经过优化但仍非常有限也因此对 HTTP 中间盒要求更高(见上)。
`XHTTP` 也接受 `X-Forwarded-For` header。
## XHttpObject
The `XHttpObject` 对应传输配置的 `xhttpSettings` 项。
```json
{
"mode": "auto",
"path": "/",
"host": "xray.com",
"headers": {
"key": "value"
},
"scMaxEachPostBytes": 1000000,
"scMaxConcurrentPosts": 100,
"scMinPostsIntervalMs": 30,
"noSSEHeader": false,
"xPaddingBytes": "100-1000",
"keepAlivePeriod": 45,
"xmux": {
"maxConcurrency": 0,
"maxConnections": 0,
"cMaxReuseTimes": 0,
"cMaxLifetimeMs": 0
},
"downloadSettings": {
"address": "example.com",
"port": 443,
"network": "xhttp",
"security": "none",
"tlsSettings": {},
"realitySettings": {},
"xhttpSettings": {
"path": "/" // must be the same
},
"sockopt": {
"dialerProxy": "" // just for example
}
},
"extra": {}
}
```
> `mode`: string
XHTTP 上行所使用的模式。默认值为 `"auto"`,客户端与 REALITY 搭配时采用流式上行,否则采用分包上行。服务端同时兼容两种模式。
`"packet-up"`:两端使用分包上行。即将数据包包装为单个 HTTP POST 请求,在服务端重组。可以兼容任意 HTTP 中间盒。
`"stream-up"`:两端使用流式上行。开启一个 HTTP 长连接发送上行数据包,与现有的 H2 / H3 / gRPC 类似。速度快但兼容性低。
> `path`: string
XHTTP 所使用的 HTTP 协议路径,默认值为 `"/"`
> `host`: string
XHTTP 的HTTP请求中所发送的host默认值为空。若服务端值为空时不验证客户端发送来的host值。
当在服务端指定该值,或在 ```headers``` 中指定host将会校验与客户端请求host是否一致。
客户端选择发送的host优先级 ```host``` > ```headers``` > ```address```
> `headers`: map \{string: string\}
仅客户端,自定义 HTTP 头,一个键值对,每个键表示一个 HTTP 头的名称,对应的值是字符串。
> `scMaxEachPostBytes`: int | string
上传分块的最大大小,单位为字节,默认值为 1000000, 即 1MB.
客户端设置的大小必须低于该值,否则当发送的 POST 请求大于服务端设置的值时,请求会被拒绝。
这个值应该小于CDN或其他HTTP反向代理所允许的最大请求体否则将抛出 HTTP 413 错误。
也可以是字符串 "500000-1000000" 的形式,核心每次会在范围内随机选择一个值,以减少指纹。
> `scMaxConcurrentPosts`: int | string
单个连接上传post的最大并发数默认为100.
上传并发同时也受(也主要受) `scMinPostsIntervalMs` 控制,故该值仅做保险。
客户端实际发起的数量必须低于服务端。(实际情况下由于上述很难达到上限,所以事实上客户端设置的值可以超过服务端,但不建议这么做)
也可以是字符串 "50-100" 的形式,核心每次会在范围内随机选择一个值,以减少指纹。
> `scMinPostsIntervalMs`: int | string
仅客户端发起POST上传请求的最小间隔。默认值为 30.
也可以是字符串 "10-50" 的形式,核心每次会在范围内随机选择一个值,以减少指纹。
> `noSSEHeader`: bool
仅服务端,不发送 `Content-Type: text/event-stream` 响应头,默认 `false` (即会发送)
> `xPaddingBytes` int | string
设置请求出站和响应入站的填充大小用于减少请求指纹。单位byte, 默认为 `"100-1000"` 每次会在该范围中随机选择一个数字。为 [Int32Range](../../development/intro/guide.md#int32range) 类型
设置为 `-1` 将完全禁用填充
> `keepAlivePeriod` int
发送保活请求的时间间隔,单位秒,设置为 `-1` 代表禁用该功能。
当使用 H2 和 H3 时分别对应 h2 ping 帧和 QUIC ping 帧。
默认值为:使用 H2 时 45 秒(Chrome 默认值), 使用 H3 时 10 秒(quic-go 默认值)
> `xmux`: [XmuxObject](#xmuxobject)
## XmuxObject
<Badge text="v24.9.19+" type="warning"/>
仅客户端,允许用户对 XHTTP 在 h2 与 h3 中的多路复用行为进行控制。使用该功能时不要启用 mux.cool。
```json
{
"maxConcurrency": "16-32",
"maxConnections": 0,
"cMaxReuseTimes": "64-128",
"cMaxLifetimeMs": 0
}
```
上为全设置为0或者不设置时核心会填入的默认值
术语解释:
- 流会复用物理连接,像这样 连接1(流1,流2,流3) 连接2(流4,流5,流6) .. 以此类推 在其他地方你可能看到 连接-子连接 这样的描述,都是一样的东西。
- 下述所有字段类型均为 为 [Int32Range](../../development/intro/guide.md#int32range) 类型
> `maxConcurrency`: int/string
默认值为 0(即无限) 每个连接中复用的流的最大数量,连接中流的数量达到该值后核心会新建更多连接以容纳更多的流,类似于 mux.cool 的 concurrency.
> `maxConnections`: int/string
默认值为 0(即无限) 要打开的最大连接数,连接达到此值前核心会积极打开连接,对每一条流都新建一个连接,直到达到该值。然后核心会开始复用已经建立的连接。 与 `maxConcurrency` 冲突。
> `cMaxReuseTimes`: int/string
默认值为 0(即无限) 一个连接最多被复用几次,当达到该值后核心不会向该连接再分配流,其将在内部最后一条流关闭后断开。
> `cMaxLifetimeMs`: int/string
默认值为 0(即无限) 一个连接最多可以“存活”多久,当连接打开的时间超过该值后核心不会向该连接再分配流,其将在内部最后一条流关闭后断开。
## downloadSettings
用于拆分 XHTTP 下行所使用的连接(可选项,注意拆分的流量必须抵达服务端的同一个入站)
`downloadSettings` 里面是嵌套的 [StreamSettingsObject](../transport.md#streamsettingsobject) ,可以使用 TLS 或者 REALITY 或者 `sockopt` 等各种选项。除此以外独有以下两个选项:
> `address`: address
下行服务端地址支持域名、IPv4、IPv6。
> `port`: number
下行服务端端口。
## extra
```json
{
"extra": {
"headers": {
"key": "value"
},
"scMaxEachPostBytes": 1000000,
"scMaxConcurrentPosts": 100,
"scMinPostsIntervalMs": 30,
"noSSEHeader": false,
"xPaddingBytes": "100-1000",
"xmux": {
"maxConcurrency": 0,
"maxConnections": 0,
"cMaxReuseTimes": 0,
"cMaxLifetimeMs": 0
},
"downloadSettings": {
"address": "example.com",
"port": 443,
"network": "xhttp",
"security": "none",
"tlsSettings": {},
"realitySettings": {},
"xhttpSettings": {
"path": "/" // must be the same
}
}
}
}
```
`extra` 是嵌套的 `XHttpObject`,用来实现分享原始 Json。`extra` 里面的配置会覆盖外面的配置。
目前以下选项在 `extra` 里面**不生效**:
`host` `path` `mode` `downloadSettings->sockopt` `extra`
## HTTP 版本
### 客户端行为
默认情况下,客户端将会默认在未启用 TLS 时使用 http/1.1, 启用 TLS 时,使用 h2.
当启用 TLS 时,允许在 TLS 设置的 alpn 数组内设置 http/1.1 h2 h3 来指定具体的http版本(仅当该数组只有一个元素时生效,若填入多个元素则返回默认行为)
### 服务端行为
默认情况下,服务端将会默认监听 TCP, 此时可以处理 http/1.1 和 h2 流量。
当启用 TLS 时,允许在 TLS 设置的 alpn 数组内设置 h3, 此时服务端将改为监听 UDP 端口, 处理 h3 流量。
### 小提示
由于该协议为标准的 HTTP 请求,所以对于 HTTP 版本的转换并不敏感,各种中间盒都可能转换 HTTP 版本。
列如:你希望使用 h3 连接 Cloudflare, 但是Cloudflare 不会使用 h3 回源, 而是使用 http/1.1 或 h2 回源,此时客户端 alpn 应为 h3, 而服务端就不应为 h3, 因为发往服务端的请求不是 h3.
## Browser Dialer
如果使用HTTPS该传输还支持 [Browser Dialer](../features/browser_dialer.md)
## 协议细节
讨论详见 [#3412](https://github.com/XTLS/Xray-core/pull/3412) 和 [#3462](https://github.com/XTLS/Xray-core/pull/3462) 以下是简述和简要兼容实现要求
1. 使用 `GET /<UUID>` 开始下载。服务器立即回复 `200 OK``Transfer Encoding:chunked` , 并立即发送一个两字节的有效负载以强制HTTP中间盒刷新标头。
现阶段服务器会发送以下标头
* `X-Accel-Buffering: no` 禁用缓冲
* `Content-Type: text/event-stream` 在部分中间盒中禁用缓冲,可以使用 `"noSSEHeader"` 选项关闭
* `Transfer-Encoding: chunked` 分块传输,仅在 HTTP/1.1 中使用
* `Cache-Control: no-store` to disable any potential response caching. 禁用CDN的缓存
2. 使用 `POST /<UUID>/<seq>` 开始发送上行数据. `seq` 作用类似于 TCP 序列号从0开始数据包可以被同时发送服务端必须按序列号将数据重组。序列号不应重置。
客户端可以以任意决定打开上行与下行请求的顺序任何一种都可以启动会话但是必须要在30秒内打开 `GET` 连接,否则会话将被终止。
3. `GET` 请求将一直保持在打开状态直到连接被终止服务端和客户端都可以关闭连接。具体行为取决于HTTP版本。
建议:
* 不要期望CDN会正确传输所有标头这个协议的目的是为了穿透不支持WS的CDN而这些CDN的行为通常不怎么友好。
* 应当假设所有HTTP连接都不支持流式请求所以上行连接发送的的每个包的大小应该基于延迟、吞吐量以及中间盒本身的限制考虑(类似TCP的MTU与纳格算法)。
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -1,3 +1,3 @@
# TCP
v24.9.30 版本后为了更贴近实际行为tcp传输方式已更名为[raw](./raw.md), 为了兼容性,`"network": "raw"` 和 "network": "tcp", `rawSettings``tcpSettings` 互为别名
See [RAW](./raw.md)

@ -4,6 +4,10 @@
WebSocket 连接可以被其它 HTTP 服务器(如 Nginx分流也可以被 VLESS fallbacks path 分流。
::: danger
**推荐换用 [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113),以避免 WebSocket “ALPN 是 http/1.1” 等显著流量特征。**
:::
::: tip
Websocket 会识别 HTTP 请求的 X-Forwarded-For 头来覆写流量的源地址,优先级高于 PROXY protocol。
:::

@ -0,0 +1,3 @@
# XHTTP: Beyond REALITY
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -14,7 +14,7 @@ However, there are many drawbacks:
* The user has to launch a browser next to the Xray client just for opening the proxy connection.
* The browser dialer must not be tunneled through the proxy itself, otherwise there is a loop. TUN users should be cautious.
* The browser can only speak standard HTTP, which means that only [WebSocket](../../transports/websocket.md) and [XHTTP](../../transports/splithttp.md) are supported
* The browser can only speak standard HTTP, which means that only [WebSocket](../../transports/websocket.md) and [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113) are supported
* [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) needs to be considered when making requests from one website (`localhost:8080`) to another (`proxy.example.com:443`)
* The browser tunnels your traffic using JavaScript, so there is a significant performance penalty (or, battery drain)
* The configuration to be used with browser dialer cannot use custom SNI or host headers. `SNI == host == address`. Custom HTTP headers and `tlsSettings` are ignored entirely.
@ -48,6 +48,6 @@ According to the browser's needs, the early data mechanism has been adjusted as
<Badge text="v1.8.19+" type="warning"/>
XHTTP supports QUIC, but the browser's own QUIC stack may be used as well. In Chrome this can be done through `chrome://flags`, in other browsers it may already be enabled or need a different flag.
[XHTTP](https://github.com/XTLS/Xray-core/discussions/4113) supports QUIC, but the browser's own QUIC stack may be used as well. In Chrome this can be done through `chrome://flags`, in other browsers it may already be enabled or need a different flag.
In general, `tlsSettings` are completely ignored when Browser Dialer is used. Xray does not have any control over which HTTP version the browser selects.

@ -10,17 +10,16 @@ Transports specify how to achieve stable data transmission. Both ends of a conne
```json
{
"network": "tcp",
"network": "raw",
"security": "none",
"tlsSettings": {},
"realitySettings": {},
"tcpSettings": {},
"kcpSettings": {},
"wsSettings": {},
"httpSettings": {},
"grpcSettings": {},
"httpupgradeSettings": {},
"rawSettings": {},
"xhttpSettings": {},
"kcpSettings": {},
"grpcSettings": {},
"wsSettings": {},
"httpupgradeSettings": {},
"sockopt": {
"mark": 0,
"tcpMaxSeg": 1440,
@ -42,9 +41,13 @@ Transports specify how to achieve stable data transmission. Both ends of a conne
}
```
> `network`: "tcp" | "kcp" | "ws" | "http" | "grpc" | "httpupgrade" | "xhttp"
> `network`: "raw" | "xhttp" | "kcp" | "grpc" | "ws" | "httpupgrade"
The underlying protocol of the transport used by the data stream of the connection, defaulting to `"tcp"`.
The underlying protocol of the transport used by the data stream of the connection, defaulting to `"raw"`.
::: tip
After v24.9.30, the TCP transport has been renamed to RAW to more closely match actual behavior. `"network": "raw"` and `"network": "tcp"`, `rawSettings` and `tcpSettings` are aliases for each other for compatibility.
:::
> `security`: "none" | "tls" | "reality"
@ -66,34 +69,30 @@ Configures REALITY. REALITY is a piece of advanced encryption technology develop
REALITY is by far the most secure transport encryption solution, perfectly mimicking normal web browsing when observed. Enabling REALITY with appropriate XTLS Vision flow control schemes has the potential of reaching magnitudes of performance boosts.
:::
> `tcpSettings`: [TcpObject](./transports/tcp.md)
> `rawSettings`: [RawObject](./transports/raw.md)
Configures the current TCP connection. Valid only when TCP is used. Same schema as global.
Configures the current RAW connection. Valid only when RAW is used. Same schema as global.
> `xhttpSettings`: [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)
Configures XHTTP connections. Valid only when XHTTP is used. Same schema as global.
> `kcpSettings`: [KcpObject](./transports/mkcp.md)
Configures the current mKCP connection. Valid only when mKCP is used. Same schema as global.
> `wsSettings`: [WebSocketObject](./transports/websocket.md)
Configures the current WebSocket connection. Valid only when WebSocket is used. Same schema as global.
> `httpSettings`: [HttpObject](./transports/h2.md)
Configures the current HTTP/2 connection. Valid only when HTTP/2 is used. Same schema as global.
> `grpcSettings`: [GRPCObject](./transports/grpc.md)
Configures the current gRPC connection. Valid only when gRPC is used. Same schema as global.
> `wsSettings`: [WebSocketObject](./transports/websocket.md)
Configures the current WebSocket connection. Valid only when WebSocket is used. Same schema as global.
> `httpupgradeSettings`: [HttpUpgradeObject](./transports/httpupgrade.md)
Configures the current HTTPUpgrade connection. Valid only when HTTPUpgrade is used. Same schema as global.
> `xhttpSettings`: [XHttpObject](./transports/splithttp.md)
Configures XHTTP connections. Valid only when XHTTP is used. Same schema as global.
> `sockopt`: [SockoptObject](#sockoptobject)
Configures transparent proxies.

@ -6,6 +6,10 @@ gRPC is based on the HTTP/2 protocol and can theoretically be relayed by other s
gRPC and HTTP/2 has built-in multiplexing, so it is not recommended to enable `mux.cool` when using gRPC or HTTP/2.
::: danger
**It is recommended to switch to [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113), whose advantages over gRPC are noted in the STREAM-UP/ONE section.**
:::
::: warning ⚠⚠⚠
- gRPC doesn't support specifying the Host. Please enter the **correct domain name** in the outbound proxy address, or fill in `ServerName` in `(x)tlsSettings`, otherwise connection cannot be established.

@ -1,82 +1,3 @@
# HTTP/2
The transmission mode based on HTTP/2 fully implements the HTTP/2 standard and can be relayed by other HTTP servers (such as Nginx).
Based on the recommendations of HTTP/2, both the client and server must enable TLS to use this transmission mode normally.
HTTP/2 has built-in multiplexing, so it is not recommended to enable mux.cool when using HTTP/2.
::: tip
The current version of the transmission mode based on HTTP/2 does not require TLS configuration for inbound (server-side).
This makes it possible to use a plaintext HTTP/2 protocol called h2c for communication between the gateway and Xray, with external gateway components handling the TLS layer conversation in special-purpose load-balancing deployment environments.
:::
::: warning
⚠️ If you are using fallback, please note the following:
- Please make sure that `h2` is included in `(x)tlsSettings.alpn`, otherwise HTTP/2 cannot complete TLS handshake.
- HTTP/2 cannot perform path-based routing, so it is recommended to use SNI-based routing.
:::
## HttpObject
`HttpObject` corresponds to the `httpSettings` in the [Transport Protocol](../transport.md),
```json
{
"host": ["xray.com"],
"path": "/random/path",
"read_idle_timeout": 10,
"health_check_timeout": 15,
"method": "PUT",
"headers": {
"Header": ["value"]
}
}
```
> `host`: \[string\]
A string array, where each element is a domain name.
The client will randomly select a domain name from the list for communication, and the server will verify whether the domain name is in the list.
> `path`: string
The HTTP path starts with `/` and must be the same value between the client and server.
The default value is `/`
> `read_idle_timeout`: number
The connection health check is performed when no data has been received for a certain period of time, measured in seconds.
By default, the health check is **disabled**.
::: tip
**Only need to be configured** in **`outbound`** (**client**).
:::
::: tip
Enabling health checks may help solve some "connection drop" issues.
:::
> `health_check_timeout`: number
The timeout for the health check, measured in seconds. If the health check is not completed within this time period, it is considered to have failed.
The default value is `15`
::: tip
**Only need to be configured** in `outbound` **(client)**.
:::
> `method`: string
HTTP request method. The default value is `PUT`
Please refer this [this](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) when configure.
> `headers`: map{ string: \[string\] }
Custom HTTP headers, defined as key-value pairs. Each key represents an HTTP header name and its corresponding value is an array.
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -0,0 +1,3 @@
# HTTP
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -4,6 +4,10 @@ A WebSocket-like transport protocol implementing the HTTP/1.1 upgrade and respon
Standalone usage is not recommended, but rather in conjunction with other security protocols like TLS.
::: danger
**It is recommended to switch to [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113) to avoid significant traffic characteristics such as HTTPUpgrade "ALPN is http/1.1".**
:::
## HttpUpgradeObject
The `HttpUpgradeObject` corresponds to the `httpupgradeSettings` section under transport configurations.

@ -0,0 +1,3 @@
# QUIC
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -0,0 +1,148 @@
# RAW
Renamed from what was once the TCP transport layer (the original name was ambiguous), the outbound RAW transport layer sends TCP and UDP data generated by proxy protocol wrappers directly, and the core doesn't use other transport layers (e.g., [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113)) to carry its traffic.
It can be combined with various protocols in multiple ways.
## RawObject
`RawObject` corresponds to the `rawSettings` item in the Transport Protocol.
```json
{
"acceptProxyProtocol": false,
"header": {
"type": "none"
}
}
```
> `acceptProxyProtocol`: true | false
Only used for inbound, indicating whether to accept the PROXY protocol.
The [PROXY protocol](https://www.haproxy.org/download/2.2/doc/proxy-protocol.txt) is used to transmit the real source IP and port of the request. **If you are not familiar with it, please ignore this item.**
Common reverse proxy software (such as HAProxy and Nginx) can be configured to send it, and VLESS fallbacks xver can also send it.
When filled in as `true`, after the underlying TCP connection is established, the requesting party must first send PROXY protocol v1 or v2, otherwise the connection will be closed.
The default value is `false`
> `header`: [NoneHeaderObject](#noneheaderobject) | [HttpHeaderobject](#httpheaderobject)
Packet header obfuscation settings, the default value is `NoneHeaderObject`
::: tip
HTTP obfuscation cannot be proxied by other HTTP servers (such as Nginx), but it can be proxied by VLESS fallbacks path.
:::
### NoneHeaderObject
No header obfuscation
```json
{
"type": "none"
}
```
> `type`: "none"
Disable header obfuscation.
### HttpHeaderObject
HTTP header obfuscation. The configuration must be the same between connecting inbound and outbound.
```json
{
"type": "http",
"request": {},
"response": {}
}
```
> `type`: "http"
Enable HTTP header obfuscation.
> `request`: [HTTPRequestObject](#httprequestobject)
HTTP request template.
> `response`: [HTTPResponseObject](#httpresponseobject)
HTTP response template.
#### HTTPRequestObject
```json
{
"version": "1.1",
"method": "GET",
"path": ["/"],
"headers": {
"Host": ["www.baidu.com", "www.bing.com"],
"User-Agent": [
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/53.0.2785.109 Mobile/14A456 Safari/601.1.46"
],
"Accept-Encoding": ["gzip, deflate"],
"Connection": ["keep-alive"],
"Pragma": "no-cache"
}
}
```
> `version`: string
HTTP version, the default value is `"1.1"`
> `method`: string
The HTTP method, the default value is `"GET"`
> `path`: \[ string \]
paths, an array of strings. The default value is `["/"]`. When there are multiple values, a value is chosen randomly for each request.
> `headers`: map{ string, \[ string \]}
HTTP header, a key-value pair, each key represents the name of an HTTP header, and the corresponding value is an array.
Each request will include all the keys and randomly select a corresponding value. Please refer to the **default values** shown in the example above.
#### HTTPResponseObject
```json
{
"version": "1.1",
"status": "200",
"reason": "OK",
"headers": {
"Content-Type": ["application/octet-stream", "video/mpeg"],
"Transfer-Encoding": ["chunked"],
"Connection": ["keep-alive"],
"Pragma": "no-cache"
}
}
```
> `version`: string
HTTP version, default is `"1.1"`
> `status`: string
HTTP status, default is `"200"`
> `reason`: string
HTTP status description, default value is `"OK"`
> `headers`: map {string, \[ string \]}
HTTP header, a key-value pair, each key represents the name of an HTTP header, and the corresponding value is an array.
Each request will include all the keys and randomly select a corresponding value. Please refer to the **default values** shown in the example above.

@ -1,234 +1,3 @@
# XHTTP (SplitHTTP)
# SplitHTTP
<Badge text="v1.8.16+" type="warning"/>
Uses HTTP chunked-transfer encoding for download, and multiple HTTP requests for upload.
Can be deployed on CDNs that do not support WebSocket. However, **the CDN must
support HTTP chunked transfer encoding in a streaming fashion**, no response
buffering.
This transport serves the same purpose as Meek (support non-WS CDN). It has the
above streaming requirement to the CDN so that download can be much faster than
(v2fly) Meek, close to WebSocket performance. The upload is also optimized, but
still much more limited than WebSocket.
Like WebSocket transport, XHTTP parses the `X-Forwarded-For` header for logging.
## XHttpObject
The `XHttpObject` corresponds to the `xhttpSettings` section under transport configurations.
```json
{
"path": "/",
"host": "xray.com",
"headers": {
"key": "value"
},
"scMaxEachPostBytes": 1000000,
"scMaxConcurrentPosts": 100,
"scMinPostsIntervalMs": 30,
"noSSEHeader": false,
"xPaddingBytes": "100-1000",
"xmux": {
"maxConcurrency": 0,
"maxConnections": 0,
"cMaxReuseTimes": 0,
"cMaxLifetimeMs": 0
}
}
```
> `path`: string
HTTP path used by the connection. Defaults to `"/"`.
> `host`: string
HTTP Host sent by the connection. Empty by default. If this value is empty on the server, the host header sent by clients will not be validated.
If the `Host` header has been defined on the server in any way, the server will validate if the `Host` header matches.
The current priority of the `Host` header sent by clients: `host` > `headers` > `address`
> `headers`: map \{string: string\}
Customized HTTP headers defined in key-value pairs. Defaults to empty.
> `scMaxEachPostBytes`: int | string
The maximum size of upload chunks, in bytes. Defaults to 1MB.
The size set by the client must be lower than this value, otherwise when the
POST request is sent larger than the value set by the server, the request will
be rejected.
This value should be smaller than the maximum request body allowed by the CDN
or other HTTP reverse proxy, otherwise an HTTP 413 error will be thrown.
It can also be in the form of a string `"1000000-2000000"`. The core will
randomly select a value within the range each time to reduce fingerprints.
> `scMaxConcurrentPosts`: int | string
The number of concurrent uploads to run. Defaults to 100 on the client, and
200 on the server.
The value on the client must not be higher than on the server. Otherwise,
connectivity issues will occur. In practice, the upload concurrency is also
limited by `minUploadIntervalMs`, so the actual concurrency on the client side
will be much lower.
It can also be in the form of a string `"100-200"`, and the core will randomly
select a value within the range each time to reduce fingerprints.
> `scMinPostsIntervalMs`: int | string
(Client-only) How much time to pass between upload requests at a minimum.
Defaults to `30` (milliseconds).
It can also be in the form of a string `"10-50"`, and the core will randomly
select a value within the range each time to reduce fingerprints.
> `noSSEHeader`
(Server-only) Do not send the `Content-Type: text/event-stream` response
header. Defaults to false (the header will be sent)
> `xPaddingBytes`
*Added in 1.8.24*
Control the padding of requests and responses. Defaults to `"100-1000"`,
meaning that each GET and POST will be padded with a random amount of bytes in
that range.
A value of `-1` disables padding entirely.
You can lower this to save bandwidth or increase it to improve censorship
resistance. Too much padding may cause the CDN to reject traffic.
> `xmux`: [XmuxObject](#xmuxobject)
## XmuxObject
<Badge text="v24.9.19+" type="warning"/>
Allows users to control the multiplexing behavior in h2 and h3. If not set, the default behavior is to multiplex all requests to one TCP/QUIC connection.
```json
{
"maxConcurrency": 0,
"maxConnections": 0,
"cMaxReuseTimes": 0,
"cMaxLifetimeMs": 0
}
```
Since the default is unlimited reuse, `xmux` actually limits this. It's not recommended to enable `mux.cool` at the same time.
Terminology: *Streams* will reuse physical connections, as in, one connection can hold many streams. In other places, streams are called sub-connections, they are the same thing.
> `maxConcurrency`: int | string
Default 0 = infinite. The maximum number of streams reused in each connection. After the number of streams in the connection reaches this value, the core will create more connections to accommodate more streams, similar to the concurrency of mux.cool. Mutually exclusive with `maxConnections`.
> `maxConnections`: int | string
Default 0 = infinite. The maximum number of connections to open. Every stream will open a new connection until this value is reached, only then connections will be reused. Mutually exclusive with `maxConcurrency`.
> `cMaxReuseTimes`: int | string
Default 0 = infinite. A connection can be reused at most several times. When this value is reached, the core will not allocate streams to the connection. It will be disconnected after the last internal stream is closed.
> `cMaxLifetimeMs`: int | string
Default 0 = infinite. How long can a connection "survive" at most? When the connection is open for more than this value, the core will not redistribute streams to the connection, and it will be disconnected after the last internal stream is closed.
## HTTP versions
*Added in 1.8.21: HTTP/3 support*
XHTTP supports `http/1.1`, `h2` and `h3` ALPN values. If the value is not
set, `h2` (prior-knowledge) is assumed when TLS is enabled, and `http/1.1`
without TLS. If the value is set to `h3`, the client will attempt to connect as
HTTP/3, so UDP instead of TCP.
The server listens to HTTP/1.1 and h2 by default, but if `h3` ALPN is set on
the server, it will listen as HTTP/3.
Please note that nginx, Caddy and all CDN will almost certainly translate
client requests to a different HTTP version for forwarding, and so the server
may have to be configured with a different ALPN value than the client. If you
use a CDN, it is very unlikely that `h3` is a correct value for the server,
even if the client speaks `h3`.
## Troubleshooting
* If a connection hangs, the CDN may not support streaming downloads. You can
use `curl -Nv https://example.com/abcdef` to initiate a download and see for
yourself (see protocol details).
If you do not see `200 OK` and a response body of `ok`, then the CDN is
buffering the response body. Please ensure that all HTTP middleboxes along
the path between client and server observe `X-Accel-Buffering: no` from their
origin server. If your chain is `xray -> nginx -> CDN -> xray`, nginx may
strip this response header and you have to re-add it.
## Browser Dialer
<Badge text="v1.8.17+" type="warning"/>
If uTLS is not enough, XHTTP's TLS can be handled by a browser using [Browser Dialer](../features/browser_dialer.md)
## Protocol details
See [#3412](https://github.com/XTLS/Xray-core/pull/3412) and
[#3462](https://github.com/XTLS/Xray-core/pull/3462) for extensive discussion
and revision of the protocol. Here is a summary, and the minimum needed to be
compatible:
1. `GET /<UUID>` opens the download. The server immediately responds with `200
OK`, and immediately sends the string `ok`
(arbitrary length, such as `ooook`) to force HTTP middleboxes into flushing
headers.
The server will send these headers:
* `X-Accel-Buffering: no` to prevent response buffering in nginx and CDN
* `Content-Type: text/event-stream` to prevent response buffering in some
CDN, can be disabled with `noSSEHeader`
* `Transfer-Encoding: chunked` in HTTP/1.1 only
* `Cache-Control: no-store` to disable any potential response caching.
2. Client uploads using `POST /<UUID>/<seq>`. `seq` starts at `0` and can be
used like TCP seq number, and multiple "packets" may be sent concurrently.
The server has to reassemble the "packets" live. The sequence number never
resets for simplicity reasons.
The client may open upload and download in any order, either one starts a
session. However, eventually `GET` needs to be opened (current deadline is
hardcoded to 30 seconds) If not, the session will be terminated.
3. The `GET` request is kept open until the tunneled connection has to be
terminated. Either server or client can close.
How this actually works depends on the HTTP version. For example, in
HTTP/1.1 it is only possible to disrupt chunked-transfer by closing the TCP
connection, in other versions the stream is closed or aborted.
Recommendations:
* Do not assume any custom headers are transferred correctly by the CDN. This
transport is built for CDN who do not support WebSocket, these CDN tend to
not be very modern (or good).
* It should be assumed there is no streaming upload within a HTTP request, so
the size of a packet should be chosen to optimize between latency,
throughput, and any size limits imposed by the CDN (just like TCP, nagle's
algorithm and MTU...)
* HTTP/1.1 and h2 should be supported by server and client, and it should be
expected that the CDN will translate arbitrarily between versions. A HTTP/1.1
server may indirectly end up talking to a h2 client, and vice versa.
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -1,148 +1,3 @@
# TCP
TCP (Transmission Control Protocol) is currently one of the recommended transport protocols
It can be combined with various protocols in multiple ways.
## TcpObject
`TcpObject` corresponds to the `tcpSettings` item in the Transport Protocol.
```json
{
"acceptProxyProtocol": false,
"header": {
"type": "none"
}
}
```
> `acceptProxyProtocol`: true | false
Only used for inbound, indicating whether to accept the PROXY protocol.
The [PROXY protocol](https://www.haproxy.org/download/2.2/doc/proxy-protocol.txt) is used to transmit the real source IP and port of the request. **If you are not familiar with it, please ignore this item.**
Common reverse proxy software (such as HAProxy and Nginx) can be configured to send it, and VLESS fallbacks xver can also send it.
When filled in as `true`, after the underlying TCP connection is established, the requesting party must first send PROXY protocol v1 or v2, otherwise the connection will be closed.
The default value is `false`
> `header`: [NoneHeaderObject](#noneheaderobject) | [HttpHeaderobject](#httpheaderobject)
Packet header obfuscation settings, the default value is `NoneHeaderObject`
::: tip
HTTP obfuscation cannot be proxied by other HTTP servers (such as Nginx), but it can be proxied by VLESS fallbacks path.
:::
### NoneHeaderObject
No header obfuscation
```json
{
"type": "none"
}
```
> `type`: "none"
Disable header obfuscation.
### HttpHeaderObject
HTTP header obfuscation. The configuration must be the same between connecting inbound and outbound.
```json
{
"type": "http",
"request": {},
"response": {}
}
```
> `type`: "http"
Enable HTTP header obfuscation.
> `request`: [HTTPRequestObject](#httprequestobject)
HTTP request template.
> `response`: [HTTPResponseObject](#httpresponseobject)
HTTP response template.
#### HTTPRequestObject
```json
{
"version": "1.1",
"method": "GET",
"path": ["/"],
"headers": {
"Host": ["www.baidu.com", "www.bing.com"],
"User-Agent": [
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/53.0.2785.109 Mobile/14A456 Safari/601.1.46"
],
"Accept-Encoding": ["gzip, deflate"],
"Connection": ["keep-alive"],
"Pragma": "no-cache"
}
}
```
> `version`: string
HTTP version, the default value is `"1.1"`
> `method`: string
The HTTP method, the default value is `"GET"`
> `path`: \[ string \]
paths, an array of strings. The default value is `["/"]`. When there are multiple values, a value is chosen randomly for each request.
> `headers`: map{ string, \[ string \]}
HTTP header, a key-value pair, each key represents the name of an HTTP header, and the corresponding value is an array.
Each request will include all the keys and randomly select a corresponding value. Please refer to the **default values** shown in the example above.
#### HTTPResponseObject
```json
{
"version": "1.1",
"status": "200",
"reason": "OK",
"headers": {
"Content-Type": ["application/octet-stream", "video/mpeg"],
"Transfer-Encoding": ["chunked"],
"Connection": ["keep-alive"],
"Pragma": "no-cache"
}
}
```
> `version`: string
HTTP version, default is `"1.1"`
> `status`: string
HTTP status, default is `"200"`
> `reason`: string
HTTP status description, default value is `"OK"`
> `headers`: map {string, \[ string \]}
HTTP header, a key-value pair, each key represents the name of an HTTP header, and the corresponding value is an array.
Each request will include all the keys and randomly select a corresponding value. Please refer to the **default values** shown in the example above.
See [RAW](./raw.md)

@ -4,6 +4,10 @@ Uses standard WebSocket for data transmission.
WebSocket connections can be proxied by other web servers (like NGINX) or by VLESS fallback paths.
::: danger
**It is recommended to switch to [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113) to avoid significant traffic characteristics such as WebSocket "ALPN is http/1.1".**
:::
::: tip
WebSocket inbounds will parse the `X-Forwarded-For` header received, overriding the source address with a higher priority than the source address got from PROXY protocol.
:::

@ -0,0 +1,3 @@
# XHTTP: Beyond REALITY
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -14,7 +14,7 @@ Xray обычно использует uTLS для имитации поведе
* Пользователь должен запускать браузер рядом с клиентом Xray только для открытия прокси-соединения.
* Browser Dialer не должен быть туннелирован через сам прокси, иначе возникнет петля. Пользователи TUN должны быть осторожны.
* Браузер может работать только со стандартным HTTP, что означает, что поддерживаются только [WebSocket](../../transports/websocket.md) и [XHTTP](../../transports/splithttp.md).
* Браузер может работать только со стандартным HTTP, что означает, что поддерживаются только [WebSocket](../../transports/websocket.md) и [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113).
* [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) необходимо учитывать при выполнении запросов с одного веб-сайта (`localhost:8080`) на другой (`proxy.example.com:443`).
* Браузер туннелирует ваш трафик с помощью JavaScript, поэтому наблюдается значительное снижение производительности (или разрядка аккумулятора).
* Конфигурация, используемая с Browser Dialer, не может использовать собственные заголовки SNI или хоста. `SNI == host == address`. Пользовательские заголовки HTTP и `tlsSettings` игнорируются полностью.
@ -48,7 +48,7 @@ Xray обычно использует uTLS для имитации поведе
<Badge text="v1.8.19+" type="warning"/>
XHTTP поддерживает QUIC, но также может использоваться собственный стек QUIC браузера. В Chrome это можно сделать через `chrome://flags`, в других браузерах он может быть уже включен или для него может потребоваться другой флаг.
[XHTTP](https://github.com/XTLS/Xray-core/discussions/4113) поддерживает QUIC, но также может использоваться собственный стек QUIC браузера. В Chrome это можно сделать через `chrome://flags`, в других браузерах он может быть уже включен или для него может потребоваться другой флаг.
В общем, `tlsSettings` полностью игнорируются при использовании Browser Dialer. Xray никак не контролирует, какую версию HTTP выбирает браузер.

@ -17,12 +17,11 @@
"tlsSettings": {},
"realitySettings": {},
"rawSettings": {},
"kcpSettings": {},
"wsSettings": {},
"httpSettings": {},
"grpcSettings": {},
"httpupgradeSettings": {},
"xhttpSettings": {},
"kcpSettings": {},
"grpcSettings": {},
"wsSettings": {},
"httpupgradeSettings": {},
"sockopt": {
"mark": 0,
"tcpMaxSeg": 1440,
@ -44,17 +43,14 @@
}
```
> `network`: "raw" | "ws" | "h2" | "grpc" | "kcp" | "httpupgrade" | "xhttp"
> `network`: "raw" | "xhttp" | "kcp" | "grpc" | "ws" | "httpupgrade"
Тип способа передачи, используемого потоком данных соединения, по умолчанию `"raw"`.
Тип способа передачи, используемого потоком данных соединения, по умолчанию `"raw"`
::: tip
**Начиная с версии v24.9.30**, для более точного отражения фактического поведения, тип передачи `tcp` был переименован в `raw`. Для обеспечения совместимости `"network": "raw"` и `"network": "tcp"`, `rawSettings` и `tcpSettings` являются синонимами.
:::
::: tip
"h2" можно записать как "http", "grpc" можно записать как "gun", "kcp" можно записать как "mkcp".
:::
> `security`: "none" | "tls" | "reality"
Включено ли шифрование транспортного уровня, поддерживаемые опции:
@ -77,32 +73,28 @@ Reality — это самое безопасное на данный момен
> `rawSettings`: [RawObject](./transports/raw.md)
Конфигурация TCP для текущего соединения, действительна только если это соединение использует TCP.
Конфигурация RAW для текущего соединения, действительна только если это соединение использует RAW.
> `xhttpSettings`: [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)
Конфигурация XHTTP для текущего соединения, действительна только если это соединение использует XHTTP.
> `kcpSettings`: [KcpObject](./transports/mkcp.md)
Конфигурация mKCP для текущего соединения, действительна только если это соединение использует mKCP.
> `wsSettings`: [WebSocketObject](./transports/websocket.md)
Конфигурация WebSocket для текущего соединения, действительна только если это соединение использует WebSocket.
> `httpSettings`: [HttpObject](./transports/http.md)
Конфигурация HTTP для текущего соединения, действительна только если это соединение использует HTTP.
> `grpcSettings`: [GRPCObject](./transports/grpc.md)
Конфигурация gRPC для текущего соединения, действительна только если это соединение использует gRPC.
> `wsSettings`: [WebSocketObject](./transports/websocket.md)
Конфигурация WebSocket для текущего соединения, действительна только если это соединение использует WebSocket.
> `httpupgradeSettings`: [HttpUpgradeObject](./transports/httpupgrade.md)
Конфигурация HTTPUpgrade для текущего соединения, действительна только если это соединение использует HTTPUpgrade.
> `xhttpSettings`: [XHttpObject](./transports/splithttp.md)
Конфигурация XHTTP для текущего соединения, действительна только если это соединение использует XHTTP.
> `sockopt`: [SockoptObject](#sockoptobject)
Конкретные настройки, связанные с прозрачным проксированием.

@ -4,6 +4,10 @@
gRPC (HTTP/2) имеет встроенное мультиплексирование, не рекомендуется включать mux.cool при использовании gRPC и HTTP/2.
::: danger
**Рекомендуется перейти на [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113), преимущества которого перед gRPC отмечены в разделе STREAM-UP/ONE.**
:::
::: warning ⚠⚠⚠
- gRPC не поддерживает указание Host. Пожалуйста, укажите **правильное доменное имя** в адресе исходящего прокси или укажите `ServerName` в `(x)tlsSettings`, иначе подключение не будет установлено.

@ -0,0 +1,3 @@
# HTTP/2
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -1,88 +1,3 @@
# HTTP
Тип транспорта, основанный на HTTP/2 или HTTP/3.
Он полностью реализован в соответствии со стандартом HTTP и может быть проксирован через другие HTTP-серверы (например, Nginx).
Клиент должен включить TLS для корректной работы этого типа транспорта.
HTTP/2 и 3 имеют встроенное мультиплексирование, поэтому не рекомендуется включать mux.cool при их использовании.
::: tip
**В текущей версии для транспорта HTTP/2 не требуется обязательная настройка TLS на стороне сервера.**
Это позволяет использовать Xray в качестве бэкенд-приложения в специальных сценариях развертывания с разделением трафика, где внешний шлюз обрабатывает TLS-соединение, а связь между шлюзом и Xray осуществляется по протоколу HTTP без шифрования.
:::
::: tip
Этот транспорт будет работать в режиме h3, только если alpn содержит только `h3`.
:::
::: warning
- HTTP/2 и HTTP/3 не могут быть разделены по путям отката Xray. Использование разделения по путям отката не рекомендуется.
:::
## HttpObject
`HttpObject` соответствует элементу `httpSettings` в конфигурации транспорта.
```json
{
"host": ["xray.com"],
"path": "/random/path",
"read_idle_timeout": 10,
"health_check_timeout": 15,
"method": "PUT",
"headers": {
"Header": ["value"]
}
}
```
> `host`: \[string\]
Массив строк, каждый элемент которого является доменным именем.
Клиент случайным образом выбирает доменное имя из списка для связи, а сервер проверяет, находится ли доменное имя в списке.
::: tip
Если не указывать `"httpSettings"` или оставить `"host": []` пустым, будет использоваться значение по умолчанию `"www.example.com"`. Для успешного подключения необходимо, чтобы значения `"host"` на обеих сторонах совпадали. `"host": [""]` не является пустым значением.
:::
> `path`: string
Путь HTTP, начинающийся с `/`. Должен совпадать на клиенте и сервере.
Значение по умолчанию: `"/"`.
> `read_idle_timeout`: number
Время ожидания чтения в секундах. Если в течение этого времени не получено никаких данных, будет выполнена проверка работоспособности.
По умолчанию проверка работоспособности **отключена**.
::: tip
Настраивается **только** на стороне **клиента**.
:::
::: tip
Может помочь решить некоторые проблемы с "обрывом соединения".
:::
> `health_check_timeout`: number
Время ожидания проверки работоспособности в секундах. Если проверка работоспособности не будет завершена в течение этого времени, она считается неудачной. Значение по умолчанию: `15`.
::: tip
Настраивается **только** на стороне **клиента**.
:::
> `method`: string
HTTP-метод. Значение по умолчанию: `"PUT"`.
При настройке следует руководствоваться значениями, перечисленными [здесь](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods).
> `headers`: map{ string: \[string\] }
**Только для клиента.** Пользовательские HTTP-заголовки. Представляет собой пару ключ-значение, где каждый ключ является именем HTTP-заголовка, а значением является массив.
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -4,6 +4,10 @@
Его дизайн не рекомендуется для самостоятельного использования, а лучше всего работает в сочетании с TLS.
::: danger
**Рекомендуется переключиться на [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113), чтобы избежать значительных характеристик трафика, таких как HTTPUpgrade «ALPN is http/1.1».**
:::
## HttpUpgradeObject
`HttpUpgradeObject` соответствует пункту `httpupgradeSettings` в настройках передачи.

@ -0,0 +1,3 @@
# QUIC
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -1,6 +1,6 @@
# RAW
Режим транспорта RAW — один из рекомендуемых в настоящее время режимов транспорта.
Переименованный из транспортного уровня TCP (первоначальное название было неоднозначным), исходящий транспортный уровень RAW отправляет данные TCP и UDP, сгенерированные обертками прокси-протоколов, напрямую, и ядро не использует другие транспортные уровни (такие как [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113)) для передачи своего трафика. трафика.
Может использоваться в различных комбинациях с различными протоколами.

@ -1,253 +1,3 @@
# XHTTP (SplitHTTP)
# SplitHTTP
<Badge text="v1.8.16+" type="warning"/>
Используется для загрузки с помощью HTTP-фрагментированной передачи, загрузка осуществляется с помощью нескольких HTTP POST-запросов (или потоковых запросов).
Может использоваться через CDN, не поддерживающие WebSocket, но есть несколько требований:
- CDN должен поддерживать HTTP-фрагментированную передачу и потоковые ответы без буферизации. Ядро будет отправлять различную информацию, чтобы сообщить CDN об этом, но CDN должна ее соблюдать. Если промежуточный узел не поддерживает потоковые ответы и зависает, этот транспорт, скорее всего, не будет работать.
Цель та же, что и у V2fly Meek, но благодаря использованию фрагментированной загрузки скорость загрузки выше, а скорость отдачи оптимизирована, но все еще очень ограничена, поэтому к HTTP-прокси предъявляются более высокие требования (см. выше).
`XHTTP` также принимает заголовок `X-Forwarded-For`.
## XHttpObject
`XHttpObject` соответствует элементу `xhttpSettings` в конфигурации транспорта.
```json
{
"mode": "auto",
"path": "/",
"host": "xray.com",
"headers": {
"key": "value"
},
"scMaxEachPostBytes": 1000000,
"scMaxConcurrentPosts": 100,
"scMinPostsIntervalMs": 30,
"noSSEHeader": false,
"xPaddingBytes": "100-1000",
"xmux": {
"maxConcurrency": 0,
"maxConnections": 0,
"cMaxReuseTimes": 0,
"cMaxLifetimeMs": 0
},
"downloadSettings": {
"address": "example.com",
"port": 443,
"network": "xhttp",
"security": "none",
"tlsSettings": {},
"realitySettings": {},
"xhttpSettings": {
"path": "/" // должен быть одинаковым
},
"sockopt": {
"dialerProxy": "" // просто пример
}
},
"extra": {}
}
```
> `mode`: string
Режим, используемый для передачи данных по XHTTP. Значение по умолчанию — `"auto"`. В этом режиме клиент при работе с REALITY использует потоковую передачу, в противном случае применяется передача с разбивкой на пакеты. Сервер поддерживает оба режима одновременно.
- `"packet-up"`: используется передача данных с разбивкой на пакеты. Каждое сообщение упаковывается в отдельный HTTP POST-запрос и собирается обратно на стороне сервера. Подходит для работы с любыми HTTP-проксирующими устройствами.
- `"stream-up"`: используется потоковая передача данных. Открывается долгоживущее HTTP-соединение для отправки пакетов, аналогично существующим методам H2 / H3 / gRPC. Этот способ быстрее, но имеет меньшую совместимость.
> `path`: string
Путь HTTP-протокола, используемый XHTTP. Значение по умолчанию — `"/"`.
> `host`: string
Хост, отправляемый в HTTP-запросе XHTTP. Значение по умолчанию пустое. Если значение на сервере пустое, значение хоста, отправляемое клиентом, не проверяется.
Если значение указано на сервере или в `headers`, оно будет сравниваться со значением хоста в запросе клиента.
Приоритет выбора хоста для отправки клиентом: `host` > `headers` > `address`.
> `headers`: map \{string: string\}
Только для клиента. Пользовательские HTTP-заголовки. Пара «ключ-значение», где каждый ключ представляет собой имя HTTP-заголовка, а соответствующее значение — строка.
> `scMaxEachPostBytes`: int | string
Максимальный размер блока выгрузки в байтах. Значение по умолчанию — 1000000 (1 МБ).
Размер, установленный на клиенте, должен быть меньше этого значения, иначе запрос POST, размер которого превышает значение, установленное на сервере, будет отклонен.
Это значение должно быть меньше максимального размера тела запроса, разрешенного CDN или другим обратным прокси-сервером HTTP, иначе будет выдаваться ошибка HTTP 413.
Также может быть строкой в формате "500000-1000000", и ядро будет случайным образом выбирать значение из этого диапазона для уменьшения цифрового следа.
> `scMaxConcurrentPosts`: int | string
Максимальное количество одновременных запросов POST на одно соединение. Значение по умолчанию — 100.
Параллельная выгрузка также (и в основном) контролируется параметром `scMinPostsIntervalMs`, поэтому это значение является лишь страховкой.
Фактическое количество запросов, отправляемых клиентом, должно быть меньше, чем на сервере. (На практике, поскольку указанного выше ограничения трудно достичь, клиент может фактически установить значение, превышающее значение на сервере, но это не рекомендуется).
Также может быть строкой в формате "50-100", и ядро будет случайным образом выбирать значение из этого диапазона для уменьшения цифрового следа.
> `scMinPostsIntervalMs`: int | string
Только для клиента. Минимальный интервал между запросами POST на выгрузку. Значение по умолчанию — 30.
Также может быть строкой в формате "10-50", и ядро будет случайным образом выбирать значение из этого диапазона для уменьшения цифрового следа.
> `noSSEHeader`: bool
Только для сервера. Не отправлять заголовок ответа `Content-Type: text/event-stream`. Значение по умолчанию — `false` (то есть заголовок будет отправлен).
> `xPaddingBytes`: int | string
Задает размер заполнения для запросов (исходящих) и ответов (входящих), используемый для уменьшения отпечатка запроса. Единица измерения: байты. Значение по умолчанию: `"100-1000"`. При каждом запросе случайным образом выбирается число из этого диапазона. Тип: [Int32Range](../../development/intro/guide.md#int32range)
Значение `-1` полностью отключает заполнение.
> `xmux`: [XmuxObject](#xmuxobject)
## XmuxObject
<Badge text="v24.9.19+" type="warning"/>
Только для клиента. Позволяет пользователю контролировать поведение многопоточности XHTTP в h2 и h3. Не используйте данную функцию вместе с mux.cool.
```json
{
"maxConcurrency": "16-32",
"maxConnections": 0,
"cMaxReuseTimes": "64-128",
"cMaxLifetimeMs": 0
}
```
При установке всех значений в 0 или их отсутствии, ядро заполнит их значениями по умолчанию.
Объяснение терминов:
- Потоки будут мультиплексироваться в физические соединения, например: Соединение 1 (Поток 1, Поток 2, Поток 3) Соединение 2 (Поток 4, Поток 5, Поток 6) ... и так далее. В других источниках вы можете встретить описание "соединение-подключение", это то же самое.
- Все следующие поля имеют тип [Int32Range](../../development/intro/guide.md#int32range):
> `maxConcurrency`: int/string
Значение по умолчанию — 0 (неограниченно). Максимальное количество потоков, мультиплексируемых в одном соединении. Когда количество потоков в соединении достигает этого значения, ядро создает дополнительные соединения для размещения новых потоков, аналогично параметру `concurrency` в mux.cool.
> `maxConnections`: int/string
Значение по умолчанию — 0 (неограниченно). Максимальное количество открытых соединений. Ядро будет активно открывать новые соединения для каждого потока до тех пор, пока не будет достигнуто это значение. Затем ядро начнет мультиплексировать потоки в уже установленные соединения. Конфликтует с `maxConcurrency`.
> `cMaxReuseTimes`: int/string
Значение по умолчанию — 0 (неограниченно). Максимальное количество раз, которое соединение может быть использовано повторно. По достижении этого значения ядро больше не будет назначать потоки этому соединению, и оно будет разорвано после закрытия последнего внутреннего потока.
> `cMaxLifetimeMs`: int/string
Значение по умолчанию — 0 (неограниченно). Максимальное время "жизни" соединения. По истечении этого времени ядро больше не будет назначать потоки этому соединению, и оно будет разорвано после закрытия последнего внутреннего потока.
## downloadSettings
Используется для настройки разделения соединений при загрузке данных по XHTTP (опционально). Важно: разделенный трафик должен достигать одного и того же входа на стороне сервера.
Внутри `downloadSettings` находится вложенный объект [StreamSettingsObject](../transport.md#streamsettingsobject), который может включать такие опции, как TLS, REALITY, `sockopt` и другие. Помимо этого, есть два уникальных параметра:
> `address`: address
Адрес сервера для загрузки данных. Поддерживает доменные имена, IPv4 и IPv6.
> `port`: number
Порт сервера для загрузки данных.
## extra
```json
{
"extra": {
"headers": {
"key": "value"
},
"scMaxEachPostBytes": 1000000,
"scMaxConcurrentPosts": 100,
"scMinPostsIntervalMs": 30,
"noSSEHeader": false,
"xPaddingBytes": "100-1000",
"xmux": {
"maxConcurrency": 0,
"maxConnections": 0,
"cMaxReuseTimes": 0,
"cMaxLifetimeMs": 0
},
"downloadSettings": {
"address": "example.com",
"port": 443,
"network": "xhttp",
"security": "none",
"tlsSettings": {},
"realitySettings": {},
"xhttpSettings": {
"path": "/" // должно совпадать
}
}
}
}
```
`extra` — это вложенный объект `XHttpObject`, используемый для предоставления исходного JSON в общий доступ. Настройки, указанные внутри `extra`, переопределяют соответствующие настройки, заданные снаружи.
В настоящее время следующие параметры внутри `extra` **не работают**:
`host`, `path`, `mode`, `downloadSettings->sockopt`, `extra`.
## Версия HTTP
### Поведение клиента
По умолчанию клиент будет использовать http/1.1, если TLS не включен, и h2, если TLS включен.
Если TLS включен, можно указать конкретную версию HTTP (http/1.1, h2, h3) в массиве `alpn` в настройках TLS (работает только в том случае, если массив содержит только один элемент, если указано несколько элементов, будет использоваться поведение по умолчанию).
### Поведение сервера
По умолчанию сервер будет прослушивать TCP-порт и обрабатывать трафик http/1.1 и h2.
Если TLS включен, можно указать `h3` в массиве `alpn` в настройках TLS. В этом случае сервер будет прослушивать UDP-порт и обрабатывать трафик h3.
### Советы
Поскольку этот протокол основан на стандартных HTTP-запросах, он нечувствителен к преобразованию версий HTTP, и различные промежуточные узлы могут преобразовывать версии HTTP.
Например, если вы хотите использовать h3 для подключения к Cloudflare, но Cloudflare не будет использовать h3 для обратного подключения, а будет использовать http/1.1 или h2, то на клиенте `alpn` должен быть установлен в `h3`, а на сервере — нет, поскольку запросы, отправляемые на сервер, не будут использовать h3.
## Browser Dialer
При использовании HTTPS этот транспорт также поддерживает [Browser Dialer](../features/browser_dialer.md).
## Подробности протокола
Подробное обсуждение см. в [#3412](https://github.com/XTLS/Xray-core/pull/3412) и [#3462](https://github.com/XTLS/Xray-core/pull/3462). Ниже приведено краткое описание и требования к совместимости реализации:
1. Загрузка начинается с запроса `GET /<UUID>`. Сервер немедленно отвечает `200 OK` и `Transfer Encoding:chunked` и сразу же отправляет двухбайтовую полезную нагрузку, чтобы заставить HTTP-промежуточные узлы сбросить заголовки.
На данный момент сервер отправляет следующие заголовки:
* `X-Accel-Buffering: no` — отключает буферизацию.
* `Content-Type: text/event-stream` — отключает буферизацию на некоторых промежуточных узлах, можно отключить с помощью опции `"noSSEHeader"`.
* `Transfer-Encoding: chunked` — кодировка передачи данных, используется только в HTTP/1.1.
* `Cache-Control: no-store` — отключает любое возможное кэширование ответов.
2. Выгрузка начинается с запроса `POST /<UUID>/<seq>`. `seq` работает аналогично порядковому номеру TCP, начиная с 0. Пакеты данных могут отправляться одновременно, сервер должен пересобрать данные в соответствии с порядковым номером. Порядковый номер не должен сбрасываться.
Клиент может открывать запросы на выгрузку и загрузку в любом порядке, любой из них может инициировать сеанс, но соединение `GET` должно быть открыто в течение 30 секунд, иначе сеанс будет разорван.
3. Запрос `GET` будет оставаться открытым до тех пор, пока соединение не будет разорвано. Как сервер, так и клиент могут закрыть соединение. Конкретное поведение зависит от версии HTTP.
Рекомендации:
* Не ожидайте, что CDN будет правильно передавать все заголовки. Цель этого протокола — обойти CDN, которые не поддерживают WS, а такие CDN обычно ведут себя не очень хорошо.
* Следует предполагать, что все HTTP-соединения не поддерживают потоковые запросы, поэтому размер каждого пакета, отправляемого по исходящему соединению, должен основываться на задержке, пропускной способности и ограничениях самого промежуточного узла (аналогично MTU и алгоритму Нейгла в TCP).
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)

@ -0,0 +1,3 @@
# TCP
See [RAW](./raw.md)

@ -4,6 +4,10 @@
Подключение WebSocket может быть проксировано другими HTTP-серверами (например, Nginx) и VLESS fallbacks path.
::: danger
**Рекомендуется переключиться на [XHTTP](https://github.com/XTLS/Xray-core/discussions/4113), чтобы избежать значительных характеристик трафика, таких как WebSocket «ALPN is http/1.1».**
:::
::: tip
WebSocket распознает заголовок X-Forwarded-For в HTTP-запросе для перезаписи исходного адреса трафика, приоритет выше, чем у PROXY protocol.
:::

@ -0,0 +1,3 @@
# XHTTP: Beyond REALITY
See [XHTTP: Beyond REALITY](https://github.com/XTLS/Xray-core/discussions/4113)