transport_internet.go 17 KB

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