transport_internet.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. package conf
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "strings"
  6. "github.com/golang/protobuf/proto"
  7. "github.com/v2fly/v2ray-core/v4/common/platform/filesystem"
  8. "github.com/v2fly/v2ray-core/v4/common/protocol"
  9. "github.com/v2fly/v2ray-core/v4/common/serial"
  10. "github.com/v2fly/v2ray-core/v4/infra/conf/cfgcommon"
  11. "github.com/v2fly/v2ray-core/v4/transport/internet"
  12. "github.com/v2fly/v2ray-core/v4/transport/internet/domainsocket"
  13. httpheader "github.com/v2fly/v2ray-core/v4/transport/internet/headers/http"
  14. "github.com/v2fly/v2ray-core/v4/transport/internet/http"
  15. "github.com/v2fly/v2ray-core/v4/transport/internet/kcp"
  16. "github.com/v2fly/v2ray-core/v4/transport/internet/quic"
  17. "github.com/v2fly/v2ray-core/v4/transport/internet/tcp"
  18. "github.com/v2fly/v2ray-core/v4/transport/internet/tls"
  19. "github.com/v2fly/v2ray-core/v4/transport/internet/websocket"
  20. )
  21. var (
  22. kcpHeaderLoader = NewJSONConfigLoader(ConfigCreatorCache{
  23. "none": func() interface{} { return new(NoOpAuthenticator) },
  24. "srtp": func() interface{} { return new(SRTPAuthenticator) },
  25. "utp": func() interface{} { return new(UTPAuthenticator) },
  26. "wechat-video": func() interface{} { return new(WechatVideoAuthenticator) },
  27. "dtls": func() interface{} { return new(DTLSAuthenticator) },
  28. "wireguard": func() interface{} { return new(WireguardAuthenticator) },
  29. }, "type", "")
  30. tcpHeaderLoader = NewJSONConfigLoader(ConfigCreatorCache{
  31. "none": func() interface{} { return new(NoOpConnectionAuthenticator) },
  32. "http": func() interface{} { return new(Authenticator) },
  33. }, "type", "")
  34. )
  35. type KCPConfig struct {
  36. Mtu *uint32 `json:"mtu"`
  37. Tti *uint32 `json:"tti"`
  38. UpCap *uint32 `json:"uplinkCapacity"`
  39. DownCap *uint32 `json:"downlinkCapacity"`
  40. Congestion *bool `json:"congestion"`
  41. ReadBufferSize *uint32 `json:"readBufferSize"`
  42. WriteBufferSize *uint32 `json:"writeBufferSize"`
  43. HeaderConfig json.RawMessage `json:"header"`
  44. Seed *string `json:"seed"`
  45. }
  46. // Build implements Buildable.
  47. func (c *KCPConfig) Build() (proto.Message, error) {
  48. config := new(kcp.Config)
  49. if c.Mtu != nil {
  50. mtu := *c.Mtu
  51. if mtu < 576 || mtu > 1460 {
  52. return nil, newError("invalid mKCP MTU size: ", mtu).AtError()
  53. }
  54. config.Mtu = &kcp.MTU{Value: mtu}
  55. }
  56. if c.Tti != nil {
  57. tti := *c.Tti
  58. if tti < 10 || tti > 100 {
  59. return nil, newError("invalid mKCP TTI: ", tti).AtError()
  60. }
  61. config.Tti = &kcp.TTI{Value: tti}
  62. }
  63. if c.UpCap != nil {
  64. config.UplinkCapacity = &kcp.UplinkCapacity{Value: *c.UpCap}
  65. }
  66. if c.DownCap != nil {
  67. config.DownlinkCapacity = &kcp.DownlinkCapacity{Value: *c.DownCap}
  68. }
  69. if c.Congestion != nil {
  70. config.Congestion = *c.Congestion
  71. }
  72. if c.ReadBufferSize != nil {
  73. size := *c.ReadBufferSize
  74. if size > 0 {
  75. config.ReadBuffer = &kcp.ReadBuffer{Size: size * 1024 * 1024}
  76. } else {
  77. config.ReadBuffer = &kcp.ReadBuffer{Size: 512 * 1024}
  78. }
  79. }
  80. if c.WriteBufferSize != nil {
  81. size := *c.WriteBufferSize
  82. if size > 0 {
  83. config.WriteBuffer = &kcp.WriteBuffer{Size: size * 1024 * 1024}
  84. } else {
  85. config.WriteBuffer = &kcp.WriteBuffer{Size: 512 * 1024}
  86. }
  87. }
  88. if len(c.HeaderConfig) > 0 {
  89. headerConfig, _, err := kcpHeaderLoader.Load(c.HeaderConfig)
  90. if err != nil {
  91. return nil, newError("invalid mKCP header config.").Base(err).AtError()
  92. }
  93. ts, err := headerConfig.(Buildable).Build()
  94. if err != nil {
  95. return nil, newError("invalid mKCP header config").Base(err).AtError()
  96. }
  97. config.HeaderConfig = serial.ToTypedMessage(ts)
  98. }
  99. if c.Seed != nil {
  100. config.Seed = &kcp.EncryptionSeed{Seed: *c.Seed}
  101. }
  102. return config, nil
  103. }
  104. type TCPConfig struct {
  105. HeaderConfig json.RawMessage `json:"header"`
  106. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  107. }
  108. // Build implements Buildable.
  109. func (c *TCPConfig) Build() (proto.Message, error) {
  110. config := new(tcp.Config)
  111. if len(c.HeaderConfig) > 0 {
  112. headerConfig, _, err := tcpHeaderLoader.Load(c.HeaderConfig)
  113. if err != nil {
  114. return nil, newError("invalid TCP header config").Base(err).AtError()
  115. }
  116. ts, err := headerConfig.(Buildable).Build()
  117. if err != nil {
  118. return nil, newError("invalid TCP header config").Base(err).AtError()
  119. }
  120. config.HeaderSettings = serial.ToTypedMessage(ts)
  121. }
  122. if c.AcceptProxyProtocol {
  123. config.AcceptProxyProtocol = c.AcceptProxyProtocol
  124. }
  125. return config, nil
  126. }
  127. type WebSocketConfig struct {
  128. Path string `json:"path"`
  129. Headers map[string]string `json:"headers"`
  130. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  131. MaxEarlyData int32 `json:"maxEarlyData"`
  132. UseBrowserForwarding bool `json:"useBrowserForwarding"`
  133. EarlyDataHeaderName string `json:"earlyDataHeaderName"`
  134. }
  135. // Build implements Buildable.
  136. func (c *WebSocketConfig) Build() (proto.Message, error) {
  137. path := c.Path
  138. header := make([]*websocket.Header, 0, 32)
  139. for key, value := range c.Headers {
  140. header = append(header, &websocket.Header{
  141. Key: key,
  142. Value: value,
  143. })
  144. }
  145. config := &websocket.Config{
  146. Path: path,
  147. Header: header,
  148. MaxEarlyData: c.MaxEarlyData,
  149. UseBrowserForwarding: c.UseBrowserForwarding,
  150. EarlyDataHeaderName: c.EarlyDataHeaderName,
  151. }
  152. if c.AcceptProxyProtocol {
  153. config.AcceptProxyProtocol = c.AcceptProxyProtocol
  154. }
  155. return config, nil
  156. }
  157. type HTTPConfig struct {
  158. Host *cfgcommon.StringList `json:"host"`
  159. Path string `json:"path"`
  160. Method string `json:"method"`
  161. Headers map[string]*cfgcommon.StringList `json:"headers"`
  162. }
  163. // Build implements Buildable.
  164. func (c *HTTPConfig) Build() (proto.Message, error) {
  165. config := &http.Config{
  166. Path: c.Path,
  167. }
  168. if c.Host != nil {
  169. config.Host = []string(*c.Host)
  170. }
  171. if c.Method != "" {
  172. config.Method = c.Method
  173. }
  174. if len(c.Headers) > 0 {
  175. config.Header = make([]*httpheader.Header, 0, len(c.Headers))
  176. headerNames := sortMapKeys(c.Headers)
  177. for _, key := range headerNames {
  178. value := c.Headers[key]
  179. if value == nil {
  180. return nil, newError("empty HTTP header value: " + key).AtError()
  181. }
  182. config.Header = append(config.Header, &httpheader.Header{
  183. Name: key,
  184. Value: append([]string(nil), (*value)...),
  185. })
  186. }
  187. }
  188. return config, nil
  189. }
  190. type QUICConfig struct {
  191. Header json.RawMessage `json:"header"`
  192. Security string `json:"security"`
  193. Key string `json:"key"`
  194. }
  195. // Build implements Buildable.
  196. func (c *QUICConfig) Build() (proto.Message, error) {
  197. config := &quic.Config{
  198. Key: c.Key,
  199. }
  200. if len(c.Header) > 0 {
  201. headerConfig, _, err := kcpHeaderLoader.Load(c.Header)
  202. if err != nil {
  203. return nil, newError("invalid QUIC header config.").Base(err).AtError()
  204. }
  205. ts, err := headerConfig.(Buildable).Build()
  206. if err != nil {
  207. return nil, newError("invalid QUIC header config").Base(err).AtError()
  208. }
  209. config.Header = serial.ToTypedMessage(ts)
  210. }
  211. var st protocol.SecurityType
  212. switch strings.ToLower(c.Security) {
  213. case "aes-128-gcm":
  214. st = protocol.SecurityType_AES128_GCM
  215. case "chacha20-poly1305":
  216. st = protocol.SecurityType_CHACHA20_POLY1305
  217. default:
  218. st = protocol.SecurityType_NONE
  219. }
  220. config.Security = &protocol.SecurityConfig{
  221. Type: st,
  222. }
  223. return config, nil
  224. }
  225. type DomainSocketConfig struct {
  226. Path string `json:"path"`
  227. Abstract bool `json:"abstract"`
  228. Padding bool `json:"padding"`
  229. }
  230. // Build implements Buildable.
  231. func (c *DomainSocketConfig) Build() (proto.Message, error) {
  232. return &domainsocket.Config{
  233. Path: c.Path,
  234. Abstract: c.Abstract,
  235. Padding: c.Padding,
  236. }, nil
  237. }
  238. func readFileOrString(f string, s []string) ([]byte, error) {
  239. if len(f) > 0 {
  240. return filesystem.ReadFile(f)
  241. }
  242. if len(s) > 0 {
  243. return []byte(strings.Join(s, "\n")), nil
  244. }
  245. return nil, newError("both file and bytes are empty.")
  246. }
  247. type TLSCertConfig struct {
  248. CertFile string `json:"certificateFile"`
  249. CertStr []string `json:"certificate"`
  250. KeyFile string `json:"keyFile"`
  251. KeyStr []string `json:"key"`
  252. Usage string `json:"usage"`
  253. }
  254. // Build implements Buildable.
  255. func (c *TLSCertConfig) Build() (*tls.Certificate, error) {
  256. certificate := new(tls.Certificate)
  257. cert, err := readFileOrString(c.CertFile, c.CertStr)
  258. if err != nil {
  259. return nil, newError("failed to parse certificate").Base(err)
  260. }
  261. certificate.Certificate = cert
  262. if len(c.KeyFile) > 0 || len(c.KeyStr) > 0 {
  263. key, err := readFileOrString(c.KeyFile, c.KeyStr)
  264. if err != nil {
  265. return nil, newError("failed to parse key").Base(err)
  266. }
  267. certificate.Key = key
  268. }
  269. switch strings.ToLower(c.Usage) {
  270. case "encipherment":
  271. certificate.Usage = tls.Certificate_ENCIPHERMENT
  272. case "verify":
  273. certificate.Usage = tls.Certificate_AUTHORITY_VERIFY
  274. case "issue":
  275. certificate.Usage = tls.Certificate_AUTHORITY_ISSUE
  276. default:
  277. certificate.Usage = tls.Certificate_ENCIPHERMENT
  278. }
  279. return certificate, nil
  280. }
  281. type TLSConfig struct {
  282. Insecure bool `json:"allowInsecure"`
  283. Certs []*TLSCertConfig `json:"certificates"`
  284. ServerName string `json:"serverName"`
  285. ALPN *cfgcommon.StringList `json:"alpn"`
  286. EnableSessionResumption bool `json:"enableSessionResumption"`
  287. DisableSystemRoot bool `json:"disableSystemRoot"`
  288. PinnedPeerCertificateChainSha256 *[]string `json:"pinnedPeerCertificateChainSha256"`
  289. ClientVerify bool `json:"clientVerify"`
  290. }
  291. // Build implements Buildable.
  292. func (c *TLSConfig) Build() (proto.Message, error) {
  293. config := new(tls.Config)
  294. config.Certificate = make([]*tls.Certificate, len(c.Certs))
  295. for idx, certConf := range c.Certs {
  296. cert, err := certConf.Build()
  297. if err != nil {
  298. return nil, err
  299. }
  300. config.Certificate[idx] = cert
  301. }
  302. serverName := c.ServerName
  303. config.AllowInsecure = c.Insecure
  304. config.ClientVerify = c.ClientVerify
  305. if len(c.ServerName) > 0 {
  306. config.ServerName = serverName
  307. }
  308. if c.ALPN != nil && len(*c.ALPN) > 0 {
  309. config.NextProtocol = []string(*c.ALPN)
  310. }
  311. config.EnableSessionResumption = c.EnableSessionResumption
  312. config.DisableSystemRoot = c.DisableSystemRoot
  313. if c.PinnedPeerCertificateChainSha256 != nil {
  314. config.PinnedPeerCertificateChainSha256 = [][]byte{}
  315. for _, v := range *c.PinnedPeerCertificateChainSha256 {
  316. hashValue, err := base64.StdEncoding.DecodeString(v)
  317. if err != nil {
  318. return nil, err
  319. }
  320. config.PinnedPeerCertificateChainSha256 = append(config.PinnedPeerCertificateChainSha256, hashValue)
  321. }
  322. }
  323. return config, nil
  324. }
  325. type TransportProtocol string
  326. // Build implements Buildable.
  327. func (p TransportProtocol) Build() (string, error) {
  328. switch strings.ToLower(string(p)) {
  329. case "tcp":
  330. return "tcp", nil
  331. case "kcp", "mkcp":
  332. return "mkcp", nil
  333. case "ws", "websocket":
  334. return "websocket", nil
  335. case "h2", "http":
  336. return "http", nil
  337. case "ds", "domainsocket":
  338. return "domainsocket", nil
  339. case "quic":
  340. return "quic", nil
  341. case "gun", "grpc":
  342. return "gun", nil
  343. default:
  344. return "", newError("Config: unknown transport protocol: ", p)
  345. }
  346. }
  347. type SocketConfig struct {
  348. Mark int32 `json:"mark"`
  349. TFO *bool `json:"tcpFastOpen"`
  350. TProxy string `json:"tproxy"`
  351. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  352. TCPKeepAliveInterval int32 `json:"tcpKeepAliveInterval"`
  353. }
  354. // Build implements Buildable.
  355. func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
  356. var tfoSettings internet.SocketConfig_TCPFastOpenState
  357. if c.TFO != nil {
  358. if *c.TFO {
  359. tfoSettings = internet.SocketConfig_Enable
  360. } else {
  361. tfoSettings = internet.SocketConfig_Disable
  362. }
  363. }
  364. var tproxy internet.SocketConfig_TProxyMode
  365. switch strings.ToLower(c.TProxy) {
  366. case "tproxy":
  367. tproxy = internet.SocketConfig_TProxy
  368. case "redirect":
  369. tproxy = internet.SocketConfig_Redirect
  370. default:
  371. tproxy = internet.SocketConfig_Off
  372. }
  373. return &internet.SocketConfig{
  374. Mark: c.Mark,
  375. Tfo: tfoSettings,
  376. Tproxy: tproxy,
  377. AcceptProxyProtocol: c.AcceptProxyProtocol,
  378. TcpKeepAliveInterval: c.TCPKeepAliveInterval,
  379. }, nil
  380. }
  381. type StreamConfig struct {
  382. Network *TransportProtocol `json:"network"`
  383. Security string `json:"security"`
  384. TLSSettings *TLSConfig `json:"tlsSettings"`
  385. TCPSettings *TCPConfig `json:"tcpSettings"`
  386. KCPSettings *KCPConfig `json:"kcpSettings"`
  387. WSSettings *WebSocketConfig `json:"wsSettings"`
  388. HTTPSettings *HTTPConfig `json:"httpSettings"`
  389. DSSettings *DomainSocketConfig `json:"dsSettings"`
  390. QUICSettings *QUICConfig `json:"quicSettings"`
  391. GunSettings *GunConfig `json:"gunSettings"`
  392. GRPCSettings *GunConfig `json:"grpcSettings"`
  393. SocketSettings *SocketConfig `json:"sockopt"`
  394. }
  395. // Build implements Buildable.
  396. func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
  397. config := &internet.StreamConfig{
  398. ProtocolName: "tcp",
  399. }
  400. if c.Network != nil {
  401. protocol, err := c.Network.Build()
  402. if err != nil {
  403. return nil, err
  404. }
  405. config.ProtocolName = protocol
  406. }
  407. if strings.EqualFold(c.Security, "tls") {
  408. tlsSettings := c.TLSSettings
  409. if tlsSettings == nil {
  410. tlsSettings = &TLSConfig{}
  411. }
  412. ts, err := tlsSettings.Build()
  413. if err != nil {
  414. return nil, newError("Failed to build TLS config.").Base(err)
  415. }
  416. tm := serial.ToTypedMessage(ts)
  417. config.SecuritySettings = append(config.SecuritySettings, tm)
  418. config.SecurityType = tm.Type
  419. }
  420. if c.TCPSettings != nil {
  421. ts, err := c.TCPSettings.Build()
  422. if err != nil {
  423. return nil, newError("Failed to build TCP config.").Base(err)
  424. }
  425. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  426. ProtocolName: "tcp",
  427. Settings: serial.ToTypedMessage(ts),
  428. })
  429. }
  430. if c.KCPSettings != nil {
  431. ts, err := c.KCPSettings.Build()
  432. if err != nil {
  433. return nil, newError("Failed to build mKCP config.").Base(err)
  434. }
  435. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  436. ProtocolName: "mkcp",
  437. Settings: serial.ToTypedMessage(ts),
  438. })
  439. }
  440. if c.WSSettings != nil {
  441. ts, err := c.WSSettings.Build()
  442. if err != nil {
  443. return nil, newError("Failed to build WebSocket config.").Base(err)
  444. }
  445. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  446. ProtocolName: "websocket",
  447. Settings: serial.ToTypedMessage(ts),
  448. })
  449. }
  450. if c.HTTPSettings != nil {
  451. ts, err := c.HTTPSettings.Build()
  452. if err != nil {
  453. return nil, newError("Failed to build HTTP config.").Base(err)
  454. }
  455. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  456. ProtocolName: "http",
  457. Settings: serial.ToTypedMessage(ts),
  458. })
  459. }
  460. if c.DSSettings != nil {
  461. ds, err := c.DSSettings.Build()
  462. if err != nil {
  463. return nil, newError("Failed to build DomainSocket config.").Base(err)
  464. }
  465. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  466. ProtocolName: "domainsocket",
  467. Settings: serial.ToTypedMessage(ds),
  468. })
  469. }
  470. if c.QUICSettings != nil {
  471. qs, err := c.QUICSettings.Build()
  472. if err != nil {
  473. return nil, newError("Failed to build QUIC config.").Base(err)
  474. }
  475. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  476. ProtocolName: "quic",
  477. Settings: serial.ToTypedMessage(qs),
  478. })
  479. }
  480. if c.GunSettings == nil {
  481. c.GunSettings = c.GRPCSettings
  482. }
  483. if c.GunSettings != nil {
  484. gs, err := c.GunSettings.Build()
  485. if err != nil {
  486. return nil, newError("Failed to build Gun config.").Base(err)
  487. }
  488. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  489. ProtocolName: "gun",
  490. Settings: serial.ToTypedMessage(gs),
  491. })
  492. }
  493. if c.SocketSettings != nil {
  494. ss, err := c.SocketSettings.Build()
  495. if err != nil {
  496. return nil, newError("Failed to build sockopt.").Base(err)
  497. }
  498. config.SocketSettings = ss
  499. }
  500. return config, nil
  501. }
  502. type ProxyConfig struct {
  503. Tag string `json:"tag"`
  504. TransportLayerProxy bool `json:"transportLayer"`
  505. }
  506. // Build implements Buildable.
  507. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) {
  508. if v.Tag == "" {
  509. return nil, newError("Proxy tag is not set.")
  510. }
  511. return &internet.ProxyConfig{
  512. Tag: v.Tag,
  513. TransportLayerProxy: v.TransportLayerProxy,
  514. }, nil
  515. }