transport_internet.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 int32 `json:"mark"`
  351. TFO *bool `json:"tcpFastOpen"`
  352. TProxy string `json:"tproxy"`
  353. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  354. TCPKeepAliveInterval int32 `json:"tcpKeepAliveInterval"`
  355. }
  356. // Build implements Buildable.
  357. func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
  358. var tfoSettings internet.SocketConfig_TCPFastOpenState
  359. if c.TFO != nil {
  360. if *c.TFO {
  361. tfoSettings = internet.SocketConfig_Enable
  362. } else {
  363. tfoSettings = internet.SocketConfig_Disable
  364. }
  365. }
  366. var tproxy internet.SocketConfig_TProxyMode
  367. switch strings.ToLower(c.TProxy) {
  368. case "tproxy":
  369. tproxy = internet.SocketConfig_TProxy
  370. case "redirect":
  371. tproxy = internet.SocketConfig_Redirect
  372. default:
  373. tproxy = internet.SocketConfig_Off
  374. }
  375. return &internet.SocketConfig{
  376. Mark: c.Mark,
  377. Tfo: tfoSettings,
  378. Tproxy: tproxy,
  379. AcceptProxyProtocol: c.AcceptProxyProtocol,
  380. TcpKeepAliveInterval: c.TCPKeepAliveInterval,
  381. }, nil
  382. }
  383. type StreamConfig struct {
  384. Network *TransportProtocol `json:"network"`
  385. Security string `json:"security"`
  386. TLSSettings *TLSConfig `json:"tlsSettings"`
  387. TCPSettings *TCPConfig `json:"tcpSettings"`
  388. KCPSettings *KCPConfig `json:"kcpSettings"`
  389. WSSettings *WebSocketConfig `json:"wsSettings"`
  390. HTTPSettings *HTTPConfig `json:"httpSettings"`
  391. DSSettings *DomainSocketConfig `json:"dsSettings"`
  392. QUICSettings *QUICConfig `json:"quicSettings"`
  393. GunSettings *GunConfig `json:"gunSettings"`
  394. GRPCSettings *GunConfig `json:"grpcSettings"`
  395. SocketSettings *SocketConfig `json:"sockopt"`
  396. }
  397. // Build implements Buildable.
  398. func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
  399. config := &internet.StreamConfig{
  400. ProtocolName: "tcp",
  401. }
  402. if c.Network != nil {
  403. protocol, err := c.Network.Build()
  404. if err != nil {
  405. return nil, err
  406. }
  407. config.ProtocolName = protocol
  408. }
  409. if strings.EqualFold(c.Security, "tls") {
  410. tlsSettings := c.TLSSettings
  411. if tlsSettings == nil {
  412. tlsSettings = &TLSConfig{}
  413. }
  414. ts, err := tlsSettings.Build()
  415. if err != nil {
  416. return nil, newError("Failed to build TLS config.").Base(err)
  417. }
  418. tm := serial.ToTypedMessage(ts)
  419. config.SecuritySettings = append(config.SecuritySettings, tm)
  420. config.SecurityType = tm.Type
  421. }
  422. if c.TCPSettings != nil {
  423. ts, err := c.TCPSettings.Build()
  424. if err != nil {
  425. return nil, newError("Failed to build TCP config.").Base(err)
  426. }
  427. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  428. ProtocolName: "tcp",
  429. Settings: serial.ToTypedMessage(ts),
  430. })
  431. }
  432. if c.KCPSettings != nil {
  433. ts, err := c.KCPSettings.Build()
  434. if err != nil {
  435. return nil, newError("Failed to build mKCP config.").Base(err)
  436. }
  437. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  438. ProtocolName: "mkcp",
  439. Settings: serial.ToTypedMessage(ts),
  440. })
  441. }
  442. if c.WSSettings != nil {
  443. ts, err := c.WSSettings.Build()
  444. if err != nil {
  445. return nil, newError("Failed to build WebSocket config.").Base(err)
  446. }
  447. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  448. ProtocolName: "websocket",
  449. Settings: serial.ToTypedMessage(ts),
  450. })
  451. }
  452. if c.HTTPSettings != nil {
  453. ts, err := c.HTTPSettings.Build()
  454. if err != nil {
  455. return nil, newError("Failed to build HTTP config.").Base(err)
  456. }
  457. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  458. ProtocolName: "http",
  459. Settings: serial.ToTypedMessage(ts),
  460. })
  461. }
  462. if c.DSSettings != nil {
  463. ds, err := c.DSSettings.Build()
  464. if err != nil {
  465. return nil, newError("Failed to build DomainSocket config.").Base(err)
  466. }
  467. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  468. ProtocolName: "domainsocket",
  469. Settings: serial.ToTypedMessage(ds),
  470. })
  471. }
  472. if c.QUICSettings != nil {
  473. qs, err := c.QUICSettings.Build()
  474. if err != nil {
  475. return nil, newError("Failed to build QUIC config.").Base(err)
  476. }
  477. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  478. ProtocolName: "quic",
  479. Settings: serial.ToTypedMessage(qs),
  480. })
  481. }
  482. if c.GunSettings == nil {
  483. c.GunSettings = c.GRPCSettings
  484. }
  485. if c.GunSettings != nil {
  486. gs, err := c.GunSettings.Build()
  487. if err != nil {
  488. return nil, newError("Failed to build Gun config.").Base(err)
  489. }
  490. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  491. ProtocolName: "gun",
  492. Settings: serial.ToTypedMessage(gs),
  493. })
  494. }
  495. if c.SocketSettings != nil {
  496. ss, err := c.SocketSettings.Build()
  497. if err != nil {
  498. return nil, newError("Failed to build sockopt.").Base(err)
  499. }
  500. config.SocketSettings = ss
  501. }
  502. return config, nil
  503. }
  504. type ProxyConfig struct {
  505. Tag string `json:"tag"`
  506. TransportLayerProxy bool `json:"transportLayer"`
  507. }
  508. // Build implements Buildable.
  509. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) {
  510. if v.Tag == "" {
  511. return nil, newError("Proxy tag is not set.")
  512. }
  513. return &internet.ProxyConfig{
  514. Tag: v.Tag,
  515. TransportLayerProxy: v.TransportLayerProxy,
  516. }, nil
  517. }