transport_internet.go 17 KB

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