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(HTTPAuthenticator) },
  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. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  207. }
  208. // Build implements Buildable.
  209. func (c *DomainSocketConfig) Build() (proto.Message, error) {
  210. return &domainsocket.Config{
  211. Path: c.Path,
  212. Abstract: c.Abstract,
  213. Padding: c.Padding,
  214. AcceptProxyProtocol: c.AcceptProxyProtocol,
  215. }, nil
  216. }
  217. func readFileOrString(f string, s []string) ([]byte, error) {
  218. if len(f) > 0 {
  219. return filesystem.ReadFile(f)
  220. }
  221. if len(s) > 0 {
  222. return []byte(strings.Join(s, "\n")), nil
  223. }
  224. return nil, newError("both file and bytes are empty.")
  225. }
  226. type TLSCertConfig struct {
  227. CertFile string `json:"certificateFile"`
  228. CertStr []string `json:"certificate"`
  229. KeyFile string `json:"keyFile"`
  230. KeyStr []string `json:"key"`
  231. Usage string `json:"usage"`
  232. }
  233. // Build implements Buildable.
  234. func (c *TLSCertConfig) Build() (*tls.Certificate, error) {
  235. certificate := new(tls.Certificate)
  236. cert, err := readFileOrString(c.CertFile, c.CertStr)
  237. if err != nil {
  238. return nil, newError("failed to parse certificate").Base(err)
  239. }
  240. certificate.Certificate = cert
  241. if len(c.KeyFile) > 0 || len(c.KeyStr) > 0 {
  242. key, err := readFileOrString(c.KeyFile, c.KeyStr)
  243. if err != nil {
  244. return nil, newError("failed to parse key").Base(err)
  245. }
  246. certificate.Key = key
  247. }
  248. switch strings.ToLower(c.Usage) {
  249. case "encipherment":
  250. certificate.Usage = tls.Certificate_ENCIPHERMENT
  251. case "verify":
  252. certificate.Usage = tls.Certificate_AUTHORITY_VERIFY
  253. case "issue":
  254. certificate.Usage = tls.Certificate_AUTHORITY_ISSUE
  255. default:
  256. certificate.Usage = tls.Certificate_ENCIPHERMENT
  257. }
  258. return certificate, nil
  259. }
  260. type TLSConfig struct {
  261. Insecure bool `json:"allowInsecure"`
  262. InsecureCiphers bool `json:"allowInsecureCiphers"`
  263. Certs []*TLSCertConfig `json:"certificates"`
  264. ServerName string `json:"serverName"`
  265. ALPN *StringList `json:"alpn"`
  266. DisableSessionResumption bool `json:"disableSessionResumption"`
  267. DisableSystemRoot bool `json:"disableSystemRoot"`
  268. }
  269. // Build implements Buildable.
  270. func (c *TLSConfig) Build() (proto.Message, error) {
  271. config := new(tls.Config)
  272. config.Certificate = make([]*tls.Certificate, len(c.Certs))
  273. for idx, certConf := range c.Certs {
  274. cert, err := certConf.Build()
  275. if err != nil {
  276. return nil, err
  277. }
  278. config.Certificate[idx] = cert
  279. }
  280. serverName := c.ServerName
  281. config.AllowInsecure = c.Insecure
  282. config.AllowInsecureCiphers = c.InsecureCiphers
  283. if len(c.ServerName) > 0 {
  284. config.ServerName = serverName
  285. }
  286. if c.ALPN != nil && len(*c.ALPN) > 0 {
  287. config.NextProtocol = []string(*c.ALPN)
  288. }
  289. config.DisableSessionResumption = c.DisableSessionResumption
  290. config.DisableSystemRoot = c.DisableSystemRoot
  291. return config, nil
  292. }
  293. type XTLSCertConfig struct {
  294. CertFile string `json:"certificateFile"`
  295. CertStr []string `json:"certificate"`
  296. KeyFile string `json:"keyFile"`
  297. KeyStr []string `json:"key"`
  298. Usage string `json:"usage"`
  299. }
  300. // Build implements Buildable.
  301. func (c *XTLSCertConfig) Build() (*xtls.Certificate, error) {
  302. certificate := new(xtls.Certificate)
  303. cert, err := readFileOrString(c.CertFile, c.CertStr)
  304. if err != nil {
  305. return nil, newError("failed to parse certificate").Base(err)
  306. }
  307. certificate.Certificate = cert
  308. if len(c.KeyFile) > 0 || len(c.KeyStr) > 0 {
  309. key, err := readFileOrString(c.KeyFile, c.KeyStr)
  310. if err != nil {
  311. return nil, newError("failed to parse key").Base(err)
  312. }
  313. certificate.Key = key
  314. }
  315. switch strings.ToLower(c.Usage) {
  316. case "encipherment":
  317. certificate.Usage = xtls.Certificate_ENCIPHERMENT
  318. case "verify":
  319. certificate.Usage = xtls.Certificate_AUTHORITY_VERIFY
  320. case "issue":
  321. certificate.Usage = xtls.Certificate_AUTHORITY_ISSUE
  322. default:
  323. certificate.Usage = xtls.Certificate_ENCIPHERMENT
  324. }
  325. return certificate, nil
  326. }
  327. type XTLSConfig struct {
  328. Insecure bool `json:"allowInsecure"`
  329. InsecureCiphers bool `json:"allowInsecureCiphers"`
  330. Certs []*XTLSCertConfig `json:"certificates"`
  331. ServerName string `json:"serverName"`
  332. ALPN *StringList `json:"alpn"`
  333. DisableSessionResumption bool `json:"disableSessionResumption"`
  334. DisableSystemRoot bool `json:"disableSystemRoot"`
  335. }
  336. // Build implements Buildable.
  337. func (c *XTLSConfig) Build() (proto.Message, error) {
  338. config := new(xtls.Config)
  339. config.Certificate = make([]*xtls.Certificate, len(c.Certs))
  340. for idx, certConf := range c.Certs {
  341. cert, err := certConf.Build()
  342. if err != nil {
  343. return nil, err
  344. }
  345. config.Certificate[idx] = cert
  346. }
  347. serverName := c.ServerName
  348. config.AllowInsecure = c.Insecure
  349. config.AllowInsecureCiphers = c.InsecureCiphers
  350. if len(c.ServerName) > 0 {
  351. config.ServerName = serverName
  352. }
  353. if c.ALPN != nil && len(*c.ALPN) > 0 {
  354. config.NextProtocol = []string(*c.ALPN)
  355. }
  356. config.DisableSessionResumption = c.DisableSessionResumption
  357. config.DisableSystemRoot = c.DisableSystemRoot
  358. return config, nil
  359. }
  360. type TransportProtocol string
  361. // Build implements Buildable.
  362. func (p TransportProtocol) Build() (string, error) {
  363. switch strings.ToLower(string(p)) {
  364. case "tcp":
  365. return "tcp", nil
  366. case "kcp", "mkcp":
  367. return "mkcp", nil
  368. case "ws", "websocket":
  369. return "websocket", nil
  370. case "h2", "http":
  371. return "http", nil
  372. case "ds", "domainsocket":
  373. return "domainsocket", nil
  374. case "quic":
  375. return "quic", nil
  376. default:
  377. return "", newError("Config: unknown transport protocol: ", p)
  378. }
  379. }
  380. type SocketConfig struct {
  381. Mark int32 `json:"mark"`
  382. TFO *bool `json:"tcpFastOpen"`
  383. TProxy string `json:"tproxy"`
  384. }
  385. // Build implements Buildable.
  386. func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
  387. var tfoSettings internet.SocketConfig_TCPFastOpenState
  388. if c.TFO != nil {
  389. if *c.TFO {
  390. tfoSettings = internet.SocketConfig_Enable
  391. } else {
  392. tfoSettings = internet.SocketConfig_Disable
  393. }
  394. }
  395. var tproxy internet.SocketConfig_TProxyMode
  396. switch strings.ToLower(c.TProxy) {
  397. case "tproxy":
  398. tproxy = internet.SocketConfig_TProxy
  399. case "redirect":
  400. tproxy = internet.SocketConfig_Redirect
  401. default:
  402. tproxy = internet.SocketConfig_Off
  403. }
  404. return &internet.SocketConfig{
  405. Mark: c.Mark,
  406. Tfo: tfoSettings,
  407. Tproxy: tproxy,
  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" {
  453. return nil, newError("XTLS only supports TCP 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. }