transport_internet.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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 "verifyclient":
  275. certificate.Usage = tls.Certificate_AUTHORITY_VERIFY_CLIENT
  276. case "issue":
  277. certificate.Usage = tls.Certificate_AUTHORITY_ISSUE
  278. default:
  279. certificate.Usage = tls.Certificate_ENCIPHERMENT
  280. }
  281. return certificate, nil
  282. }
  283. type TLSConfig struct {
  284. Insecure bool `json:"allowInsecure"`
  285. Certs []*TLSCertConfig `json:"certificates"`
  286. ServerName string `json:"serverName"`
  287. ALPN *cfgcommon.StringList `json:"alpn"`
  288. EnableSessionResumption bool `json:"enableSessionResumption"`
  289. DisableSystemRoot bool `json:"disableSystemRoot"`
  290. PinnedPeerCertificateChainSha256 *[]string `json:"pinnedPeerCertificateChainSha256"`
  291. VerifyClientCertificate bool `json:"verifyClientCertificate"`
  292. }
  293. // Build implements Buildable.
  294. func (c *TLSConfig) Build() (proto.Message, error) {
  295. config := new(tls.Config)
  296. config.Certificate = make([]*tls.Certificate, len(c.Certs))
  297. for idx, certConf := range c.Certs {
  298. cert, err := certConf.Build()
  299. if err != nil {
  300. return nil, err
  301. }
  302. config.Certificate[idx] = cert
  303. }
  304. serverName := c.ServerName
  305. config.AllowInsecure = c.Insecure
  306. config.VerifyClientCertificate = c.VerifyClientCertificate
  307. if len(c.ServerName) > 0 {
  308. config.ServerName = serverName
  309. }
  310. if c.ALPN != nil && len(*c.ALPN) > 0 {
  311. config.NextProtocol = []string(*c.ALPN)
  312. }
  313. config.EnableSessionResumption = c.EnableSessionResumption
  314. config.DisableSystemRoot = c.DisableSystemRoot
  315. if c.PinnedPeerCertificateChainSha256 != nil {
  316. config.PinnedPeerCertificateChainSha256 = [][]byte{}
  317. for _, v := range *c.PinnedPeerCertificateChainSha256 {
  318. hashValue, err := base64.StdEncoding.DecodeString(v)
  319. if err != nil {
  320. return nil, err
  321. }
  322. config.PinnedPeerCertificateChainSha256 = append(config.PinnedPeerCertificateChainSha256, hashValue)
  323. }
  324. }
  325. return config, nil
  326. }
  327. type TransportProtocol string
  328. // Build implements Buildable.
  329. func (p TransportProtocol) Build() (string, error) {
  330. switch strings.ToLower(string(p)) {
  331. case "tcp":
  332. return "tcp", nil
  333. case "kcp", "mkcp":
  334. return "mkcp", nil
  335. case "ws", "websocket":
  336. return "websocket", nil
  337. case "h2", "http":
  338. return "http", nil
  339. case "ds", "domainsocket":
  340. return "domainsocket", nil
  341. case "quic":
  342. return "quic", nil
  343. case "gun", "grpc":
  344. return "gun", nil
  345. default:
  346. return "", newError("Config: unknown transport protocol: ", p)
  347. }
  348. }
  349. type SocketConfig struct {
  350. Mark uint32 `json:"mark"`
  351. TFO *bool `json:"tcpFastOpen"`
  352. TFOQueueLength uint32 `json:"tcpFastOpenQueueLength"`
  353. TProxy string `json:"tproxy"`
  354. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  355. TCPKeepAliveInterval int32 `json:"tcpKeepAliveInterval"`
  356. }
  357. // Build implements Buildable.
  358. func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
  359. var tfoSettings internet.SocketConfig_TCPFastOpenState
  360. if c.TFO != nil {
  361. if *c.TFO {
  362. tfoSettings = internet.SocketConfig_Enable
  363. } else {
  364. tfoSettings = internet.SocketConfig_Disable
  365. }
  366. }
  367. tfoQueueLength := c.TFOQueueLength
  368. if tfoQueueLength == 0 {
  369. tfoQueueLength = 4096
  370. }
  371. var tproxy internet.SocketConfig_TProxyMode
  372. switch strings.ToLower(c.TProxy) {
  373. case "tproxy":
  374. tproxy = internet.SocketConfig_TProxy
  375. case "redirect":
  376. tproxy = internet.SocketConfig_Redirect
  377. default:
  378. tproxy = internet.SocketConfig_Off
  379. }
  380. return &internet.SocketConfig{
  381. Mark: c.Mark,
  382. Tfo: tfoSettings,
  383. TfoQueueLength: tfoQueueLength,
  384. Tproxy: tproxy,
  385. AcceptProxyProtocol: c.AcceptProxyProtocol,
  386. TcpKeepAliveInterval: c.TCPKeepAliveInterval,
  387. }, nil
  388. }
  389. type StreamConfig struct {
  390. Network *TransportProtocol `json:"network"`
  391. Security string `json:"security"`
  392. TLSSettings *TLSConfig `json:"tlsSettings"`
  393. TCPSettings *TCPConfig `json:"tcpSettings"`
  394. KCPSettings *KCPConfig `json:"kcpSettings"`
  395. WSSettings *WebSocketConfig `json:"wsSettings"`
  396. HTTPSettings *HTTPConfig `json:"httpSettings"`
  397. DSSettings *DomainSocketConfig `json:"dsSettings"`
  398. QUICSettings *QUICConfig `json:"quicSettings"`
  399. GunSettings *GunConfig `json:"gunSettings"`
  400. GRPCSettings *GunConfig `json:"grpcSettings"`
  401. SocketSettings *SocketConfig `json:"sockopt"`
  402. }
  403. // Build implements Buildable.
  404. func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
  405. config := &internet.StreamConfig{
  406. ProtocolName: "tcp",
  407. }
  408. if c.Network != nil {
  409. protocol, err := c.Network.Build()
  410. if err != nil {
  411. return nil, err
  412. }
  413. config.ProtocolName = protocol
  414. }
  415. if strings.EqualFold(c.Security, "tls") {
  416. tlsSettings := c.TLSSettings
  417. if tlsSettings == nil {
  418. tlsSettings = &TLSConfig{}
  419. }
  420. ts, err := tlsSettings.Build()
  421. if err != nil {
  422. return nil, newError("Failed to build TLS config.").Base(err)
  423. }
  424. tm := serial.ToTypedMessage(ts)
  425. config.SecuritySettings = append(config.SecuritySettings, tm)
  426. config.SecurityType = tm.Type
  427. }
  428. if c.TCPSettings != nil {
  429. ts, err := c.TCPSettings.Build()
  430. if err != nil {
  431. return nil, newError("Failed to build TCP config.").Base(err)
  432. }
  433. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  434. ProtocolName: "tcp",
  435. Settings: serial.ToTypedMessage(ts),
  436. })
  437. }
  438. if c.KCPSettings != nil {
  439. ts, err := c.KCPSettings.Build()
  440. if err != nil {
  441. return nil, newError("Failed to build mKCP config.").Base(err)
  442. }
  443. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  444. ProtocolName: "mkcp",
  445. Settings: serial.ToTypedMessage(ts),
  446. })
  447. }
  448. if c.WSSettings != nil {
  449. ts, err := c.WSSettings.Build()
  450. if err != nil {
  451. return nil, newError("Failed to build WebSocket config.").Base(err)
  452. }
  453. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  454. ProtocolName: "websocket",
  455. Settings: serial.ToTypedMessage(ts),
  456. })
  457. }
  458. if c.HTTPSettings != nil {
  459. ts, err := c.HTTPSettings.Build()
  460. if err != nil {
  461. return nil, newError("Failed to build HTTP config.").Base(err)
  462. }
  463. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  464. ProtocolName: "http",
  465. Settings: serial.ToTypedMessage(ts),
  466. })
  467. }
  468. if c.DSSettings != nil {
  469. ds, err := c.DSSettings.Build()
  470. if err != nil {
  471. return nil, newError("Failed to build DomainSocket config.").Base(err)
  472. }
  473. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  474. ProtocolName: "domainsocket",
  475. Settings: serial.ToTypedMessage(ds),
  476. })
  477. }
  478. if c.QUICSettings != nil {
  479. qs, err := c.QUICSettings.Build()
  480. if err != nil {
  481. return nil, newError("Failed to build QUIC config.").Base(err)
  482. }
  483. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  484. ProtocolName: "quic",
  485. Settings: serial.ToTypedMessage(qs),
  486. })
  487. }
  488. if c.GunSettings == nil {
  489. c.GunSettings = c.GRPCSettings
  490. }
  491. if c.GunSettings != nil {
  492. gs, err := c.GunSettings.Build()
  493. if err != nil {
  494. return nil, newError("Failed to build Gun config.").Base(err)
  495. }
  496. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  497. ProtocolName: "gun",
  498. Settings: serial.ToTypedMessage(gs),
  499. })
  500. }
  501. if c.SocketSettings != nil {
  502. ss, err := c.SocketSettings.Build()
  503. if err != nil {
  504. return nil, newError("Failed to build sockopt.").Base(err)
  505. }
  506. config.SocketSettings = ss
  507. }
  508. return config, nil
  509. }
  510. type ProxyConfig struct {
  511. Tag string `json:"tag"`
  512. TransportLayerProxy bool `json:"transportLayer"`
  513. }
  514. // Build implements Buildable.
  515. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) {
  516. if v.Tag == "" {
  517. return nil, newError("Proxy tag is not set.")
  518. }
  519. return &internet.ProxyConfig{
  520. Tag: v.Tag,
  521. TransportLayerProxy: v.TransportLayerProxy,
  522. }, nil
  523. }