transport_internet.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. Path2 string `json:"Path"` // The key was misspelled. For backward compatibility, we have to keep track the old key.
  130. Headers map[string]string `json:"headers"`
  131. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  132. MaxEarlyData int32 `json:"maxEarlyData"`
  133. UseBrowserForwarding bool `json:"useBrowserForwarding"`
  134. }
  135. // Build implements Buildable.
  136. func (c *WebSocketConfig) Build() (proto.Message, error) {
  137. path := c.Path
  138. if path == "" && c.Path2 != "" {
  139. path = c.Path2
  140. }
  141. header := make([]*websocket.Header, 0, 32)
  142. for key, value := range c.Headers {
  143. header = append(header, &websocket.Header{
  144. Key: key,
  145. Value: value,
  146. })
  147. }
  148. config := &websocket.Config{
  149. Path: path,
  150. Header: header,
  151. MaxEarlyData: c.MaxEarlyData,
  152. UseBrowserForwarding: c.UseBrowserForwarding,
  153. }
  154. if c.AcceptProxyProtocol {
  155. config.AcceptProxyProtocol = c.AcceptProxyProtocol
  156. }
  157. return config, nil
  158. }
  159. type HTTPConfig struct {
  160. Host *cfgcommon.StringList `json:"host"`
  161. Path string `json:"path"`
  162. Method string `json:"method"`
  163. Headers map[string]*cfgcommon.StringList `json:"headers"`
  164. }
  165. // Build implements Buildable.
  166. func (c *HTTPConfig) Build() (proto.Message, error) {
  167. config := &http.Config{
  168. Path: c.Path,
  169. }
  170. if c.Host != nil {
  171. config.Host = []string(*c.Host)
  172. }
  173. if c.Method != "" {
  174. config.Method = c.Method
  175. }
  176. if len(c.Headers) > 0 {
  177. config.Header = make([]*httpheader.Header, 0, len(c.Headers))
  178. headerNames := sortMapKeys(c.Headers)
  179. for _, key := range headerNames {
  180. value := c.Headers[key]
  181. if value == nil {
  182. return nil, newError("empty HTTP header value: " + key).AtError()
  183. }
  184. config.Header = append(config.Header, &httpheader.Header{
  185. Name: key,
  186. Value: append([]string(nil), (*value)...),
  187. })
  188. }
  189. }
  190. return config, nil
  191. }
  192. type QUICConfig struct {
  193. Header json.RawMessage `json:"header"`
  194. Security string `json:"security"`
  195. Key string `json:"key"`
  196. }
  197. // Build implements Buildable.
  198. func (c *QUICConfig) Build() (proto.Message, error) {
  199. config := &quic.Config{
  200. Key: c.Key,
  201. }
  202. if len(c.Header) > 0 {
  203. headerConfig, _, err := kcpHeaderLoader.Load(c.Header)
  204. if err != nil {
  205. return nil, newError("invalid QUIC header config.").Base(err).AtError()
  206. }
  207. ts, err := headerConfig.(Buildable).Build()
  208. if err != nil {
  209. return nil, newError("invalid QUIC header config").Base(err).AtError()
  210. }
  211. config.Header = serial.ToTypedMessage(ts)
  212. }
  213. var st protocol.SecurityType
  214. switch strings.ToLower(c.Security) {
  215. case "aes-128-gcm":
  216. st = protocol.SecurityType_AES128_GCM
  217. case "chacha20-poly1305":
  218. st = protocol.SecurityType_CHACHA20_POLY1305
  219. default:
  220. st = protocol.SecurityType_NONE
  221. }
  222. config.Security = &protocol.SecurityConfig{
  223. Type: st,
  224. }
  225. return config, nil
  226. }
  227. type DomainSocketConfig struct {
  228. Path string `json:"path"`
  229. Abstract bool `json:"abstract"`
  230. Padding bool `json:"padding"`
  231. }
  232. // Build implements Buildable.
  233. func (c *DomainSocketConfig) Build() (proto.Message, error) {
  234. return &domainsocket.Config{
  235. Path: c.Path,
  236. Abstract: c.Abstract,
  237. Padding: c.Padding,
  238. }, nil
  239. }
  240. func readFileOrString(f string, s []string) ([]byte, error) {
  241. if len(f) > 0 {
  242. return filesystem.ReadFile(f)
  243. }
  244. if len(s) > 0 {
  245. return []byte(strings.Join(s, "\n")), nil
  246. }
  247. return nil, newError("both file and bytes are empty.")
  248. }
  249. type TLSCertConfig struct {
  250. CertFile string `json:"certificateFile"`
  251. CertStr []string `json:"certificate"`
  252. KeyFile string `json:"keyFile"`
  253. KeyStr []string `json:"key"`
  254. Usage string `json:"usage"`
  255. }
  256. // Build implements Buildable.
  257. func (c *TLSCertConfig) Build() (*tls.Certificate, error) {
  258. certificate := new(tls.Certificate)
  259. cert, err := readFileOrString(c.CertFile, c.CertStr)
  260. if err != nil {
  261. return nil, newError("failed to parse certificate").Base(err)
  262. }
  263. certificate.Certificate = cert
  264. if len(c.KeyFile) > 0 || len(c.KeyStr) > 0 {
  265. key, err := readFileOrString(c.KeyFile, c.KeyStr)
  266. if err != nil {
  267. return nil, newError("failed to parse key").Base(err)
  268. }
  269. certificate.Key = key
  270. }
  271. switch strings.ToLower(c.Usage) {
  272. case "encipherment":
  273. certificate.Usage = tls.Certificate_ENCIPHERMENT
  274. case "verify":
  275. certificate.Usage = tls.Certificate_AUTHORITY_VERIFY
  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. }
  292. // Build implements Buildable.
  293. func (c *TLSConfig) Build() (proto.Message, error) {
  294. config := new(tls.Config)
  295. config.Certificate = make([]*tls.Certificate, len(c.Certs))
  296. for idx, certConf := range c.Certs {
  297. cert, err := certConf.Build()
  298. if err != nil {
  299. return nil, err
  300. }
  301. config.Certificate[idx] = cert
  302. }
  303. serverName := c.ServerName
  304. config.AllowInsecure = c.Insecure
  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. }
  353. // Build implements Buildable.
  354. func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
  355. var tfoSettings internet.SocketConfig_TCPFastOpenState
  356. if c.TFO != nil {
  357. if *c.TFO {
  358. tfoSettings = internet.SocketConfig_Enable
  359. } else {
  360. tfoSettings = internet.SocketConfig_Disable
  361. }
  362. }
  363. var tproxy internet.SocketConfig_TProxyMode
  364. switch strings.ToLower(c.TProxy) {
  365. case "tproxy":
  366. tproxy = internet.SocketConfig_TProxy
  367. case "redirect":
  368. tproxy = internet.SocketConfig_Redirect
  369. default:
  370. tproxy = internet.SocketConfig_Off
  371. }
  372. return &internet.SocketConfig{
  373. Mark: c.Mark,
  374. Tfo: tfoSettings,
  375. Tproxy: tproxy,
  376. AcceptProxyProtocol: c.AcceptProxyProtocol,
  377. }, nil
  378. }
  379. type StreamConfig struct {
  380. Network *TransportProtocol `json:"network"`
  381. Security string `json:"security"`
  382. TLSSettings *TLSConfig `json:"tlsSettings"`
  383. TCPSettings *TCPConfig `json:"tcpSettings"`
  384. KCPSettings *KCPConfig `json:"kcpSettings"`
  385. WSSettings *WebSocketConfig `json:"wsSettings"`
  386. HTTPSettings *HTTPConfig `json:"httpSettings"`
  387. DSSettings *DomainSocketConfig `json:"dsSettings"`
  388. QUICSettings *QUICConfig `json:"quicSettings"`
  389. GunSettings *GunConfig `json:"gunSettings"`
  390. GRPCSettings *GunConfig `json:"grpcSettings"`
  391. SocketSettings *SocketConfig `json:"sockopt"`
  392. }
  393. // Build implements Buildable.
  394. func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
  395. config := &internet.StreamConfig{
  396. ProtocolName: "tcp",
  397. }
  398. if c.Network != nil {
  399. protocol, err := c.Network.Build()
  400. if err != nil {
  401. return nil, err
  402. }
  403. config.ProtocolName = protocol
  404. }
  405. if strings.EqualFold(c.Security, "tls") {
  406. tlsSettings := c.TLSSettings
  407. if tlsSettings == nil {
  408. tlsSettings = &TLSConfig{}
  409. }
  410. ts, err := tlsSettings.Build()
  411. if err != nil {
  412. return nil, newError("Failed to build TLS config.").Base(err)
  413. }
  414. tm := serial.ToTypedMessage(ts)
  415. config.SecuritySettings = append(config.SecuritySettings, tm)
  416. config.SecurityType = tm.Type
  417. }
  418. if c.TCPSettings != nil {
  419. ts, err := c.TCPSettings.Build()
  420. if err != nil {
  421. return nil, newError("Failed to build TCP config.").Base(err)
  422. }
  423. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  424. ProtocolName: "tcp",
  425. Settings: serial.ToTypedMessage(ts),
  426. })
  427. }
  428. if c.KCPSettings != nil {
  429. ts, err := c.KCPSettings.Build()
  430. if err != nil {
  431. return nil, newError("Failed to build mKCP config.").Base(err)
  432. }
  433. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  434. ProtocolName: "mkcp",
  435. Settings: serial.ToTypedMessage(ts),
  436. })
  437. }
  438. if c.WSSettings != nil {
  439. ts, err := c.WSSettings.Build()
  440. if err != nil {
  441. return nil, newError("Failed to build WebSocket config.").Base(err)
  442. }
  443. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  444. ProtocolName: "websocket",
  445. Settings: serial.ToTypedMessage(ts),
  446. })
  447. }
  448. if c.HTTPSettings != nil {
  449. ts, err := c.HTTPSettings.Build()
  450. if err != nil {
  451. return nil, newError("Failed to build HTTP config.").Base(err)
  452. }
  453. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  454. ProtocolName: "http",
  455. Settings: serial.ToTypedMessage(ts),
  456. })
  457. }
  458. if c.DSSettings != nil {
  459. ds, err := c.DSSettings.Build()
  460. if err != nil {
  461. return nil, newError("Failed to build DomainSocket config.").Base(err)
  462. }
  463. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  464. ProtocolName: "domainsocket",
  465. Settings: serial.ToTypedMessage(ds),
  466. })
  467. }
  468. if c.QUICSettings != nil {
  469. qs, err := c.QUICSettings.Build()
  470. if err != nil {
  471. return nil, newError("Failed to build QUIC config.").Base(err)
  472. }
  473. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  474. ProtocolName: "quic",
  475. Settings: serial.ToTypedMessage(qs),
  476. })
  477. }
  478. if c.GunSettings == nil {
  479. c.GunSettings = c.GRPCSettings
  480. }
  481. if c.GunSettings != nil {
  482. gs, err := c.GunSettings.Build()
  483. if err != nil {
  484. return nil, newError("Failed to build Gun config.").Base(err)
  485. }
  486. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  487. ProtocolName: "gun",
  488. Settings: serial.ToTypedMessage(gs),
  489. })
  490. }
  491. if c.SocketSettings != nil {
  492. ss, err := c.SocketSettings.Build()
  493. if err != nil {
  494. return nil, newError("Failed to build sockopt.").Base(err)
  495. }
  496. config.SocketSettings = ss
  497. }
  498. return config, nil
  499. }
  500. type ProxyConfig struct {
  501. Tag string `json:"tag"`
  502. TransportLayerProxy bool `json:"transportLayer"`
  503. }
  504. // Build implements Buildable.
  505. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) {
  506. if v.Tag == "" {
  507. return nil, newError("Proxy tag is not set.")
  508. }
  509. return &internet.ProxyConfig{
  510. Tag: v.Tag,
  511. TransportLayerProxy: v.TransportLayerProxy,
  512. }, nil
  513. }