transport_internet.go 15 KB

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