transport_internet.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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/transport/internet"
  11. "github.com/v2fly/v2ray-core/v4/transport/internet/domainsocket"
  12. "github.com/v2fly/v2ray-core/v4/transport/internet/http"
  13. "github.com/v2fly/v2ray-core/v4/transport/internet/kcp"
  14. "github.com/v2fly/v2ray-core/v4/transport/internet/quic"
  15. "github.com/v2fly/v2ray-core/v4/transport/internet/tcp"
  16. "github.com/v2fly/v2ray-core/v4/transport/internet/tls"
  17. "github.com/v2fly/v2ray-core/v4/transport/internet/websocket"
  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. MaxEarlyData int32 `json:"maxEarlyData"`
  131. UseBrowserForwarding bool `json:"useBrowserForwarding"`
  132. EarlyDataHeaderName string `json:"earlyDataHeaderName"`
  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. EarlyDataHeaderName: c.EarlyDataHeaderName,
  153. }
  154. if c.AcceptProxyProtocol {
  155. config.AcceptProxyProtocol = c.AcceptProxyProtocol
  156. }
  157. return config, nil
  158. }
  159. type HTTPConfig struct {
  160. Host *StringList `json:"host"`
  161. Path string `json:"path"`
  162. }
  163. // Build implements Buildable.
  164. func (c *HTTPConfig) Build() (proto.Message, error) {
  165. config := &http.Config{
  166. Path: c.Path,
  167. }
  168. if c.Host != nil {
  169. config.Host = []string(*c.Host)
  170. }
  171. return config, nil
  172. }
  173. type QUICConfig struct {
  174. Header json.RawMessage `json:"header"`
  175. Security string `json:"security"`
  176. Key string `json:"key"`
  177. }
  178. // Build implements Buildable.
  179. func (c *QUICConfig) Build() (proto.Message, error) {
  180. config := &quic.Config{
  181. Key: c.Key,
  182. }
  183. if len(c.Header) > 0 {
  184. headerConfig, _, err := kcpHeaderLoader.Load(c.Header)
  185. if err != nil {
  186. return nil, newError("invalid QUIC header config.").Base(err).AtError()
  187. }
  188. ts, err := headerConfig.(Buildable).Build()
  189. if err != nil {
  190. return nil, newError("invalid QUIC header config").Base(err).AtError()
  191. }
  192. config.Header = serial.ToTypedMessage(ts)
  193. }
  194. var st protocol.SecurityType
  195. switch strings.ToLower(c.Security) {
  196. case "aes-128-gcm":
  197. st = protocol.SecurityType_AES128_GCM
  198. case "chacha20-poly1305":
  199. st = protocol.SecurityType_CHACHA20_POLY1305
  200. default:
  201. st = protocol.SecurityType_NONE
  202. }
  203. config.Security = &protocol.SecurityConfig{
  204. Type: st,
  205. }
  206. return config, nil
  207. }
  208. type DomainSocketConfig struct {
  209. Path string `json:"path"`
  210. Abstract bool `json:"abstract"`
  211. Padding bool `json:"padding"`
  212. }
  213. // Build implements Buildable.
  214. func (c *DomainSocketConfig) Build() (proto.Message, error) {
  215. return &domainsocket.Config{
  216. Path: c.Path,
  217. Abstract: c.Abstract,
  218. Padding: c.Padding,
  219. }, nil
  220. }
  221. func readFileOrString(f string, s []string) ([]byte, error) {
  222. if len(f) > 0 {
  223. return filesystem.ReadFile(f)
  224. }
  225. if len(s) > 0 {
  226. return []byte(strings.Join(s, "\n")), nil
  227. }
  228. return nil, newError("both file and bytes are empty.")
  229. }
  230. type TLSCertConfig struct {
  231. CertFile string `json:"certificateFile"`
  232. CertStr []string `json:"certificate"`
  233. KeyFile string `json:"keyFile"`
  234. KeyStr []string `json:"key"`
  235. Usage string `json:"usage"`
  236. }
  237. // Build implements Buildable.
  238. func (c *TLSCertConfig) Build() (*tls.Certificate, error) {
  239. certificate := new(tls.Certificate)
  240. cert, err := readFileOrString(c.CertFile, c.CertStr)
  241. if err != nil {
  242. return nil, newError("failed to parse certificate").Base(err)
  243. }
  244. certificate.Certificate = cert
  245. if len(c.KeyFile) > 0 || len(c.KeyStr) > 0 {
  246. key, err := readFileOrString(c.KeyFile, c.KeyStr)
  247. if err != nil {
  248. return nil, newError("failed to parse key").Base(err)
  249. }
  250. certificate.Key = key
  251. }
  252. switch strings.ToLower(c.Usage) {
  253. case "encipherment":
  254. certificate.Usage = tls.Certificate_ENCIPHERMENT
  255. case "verify":
  256. certificate.Usage = tls.Certificate_AUTHORITY_VERIFY
  257. case "issue":
  258. certificate.Usage = tls.Certificate_AUTHORITY_ISSUE
  259. default:
  260. certificate.Usage = tls.Certificate_ENCIPHERMENT
  261. }
  262. return certificate, nil
  263. }
  264. type TLSConfig struct {
  265. Insecure bool `json:"allowInsecure"`
  266. Certs []*TLSCertConfig `json:"certificates"`
  267. ServerName string `json:"serverName"`
  268. ALPN *StringList `json:"alpn"`
  269. EnableSessionResumption bool `json:"enableSessionResumption"`
  270. DisableSystemRoot bool `json:"disableSystemRoot"`
  271. PinnedPeerCertificateChainSha256 *[]string `json:"pinnedPeerCertificateChainSha256"`
  272. }
  273. // Build implements Buildable.
  274. func (c *TLSConfig) Build() (proto.Message, error) {
  275. config := new(tls.Config)
  276. config.Certificate = make([]*tls.Certificate, len(c.Certs))
  277. for idx, certConf := range c.Certs {
  278. cert, err := certConf.Build()
  279. if err != nil {
  280. return nil, err
  281. }
  282. config.Certificate[idx] = cert
  283. }
  284. serverName := c.ServerName
  285. config.AllowInsecure = c.Insecure
  286. if len(c.ServerName) > 0 {
  287. config.ServerName = serverName
  288. }
  289. if c.ALPN != nil && len(*c.ALPN) > 0 {
  290. config.NextProtocol = []string(*c.ALPN)
  291. }
  292. config.EnableSessionResumption = c.EnableSessionResumption
  293. config.DisableSystemRoot = c.DisableSystemRoot
  294. if c.PinnedPeerCertificateChainSha256 != nil {
  295. config.PinnedPeerCertificateChainSha256 = [][]byte{}
  296. for _, v := range *c.PinnedPeerCertificateChainSha256 {
  297. hashValue, err := base64.StdEncoding.DecodeString(v)
  298. if err != nil {
  299. return nil, err
  300. }
  301. config.PinnedPeerCertificateChainSha256 = append(config.PinnedPeerCertificateChainSha256, hashValue)
  302. }
  303. }
  304. return config, nil
  305. }
  306. type TransportProtocol string
  307. // Build implements Buildable.
  308. func (p TransportProtocol) Build() (string, error) {
  309. switch strings.ToLower(string(p)) {
  310. case "tcp":
  311. return "tcp", nil
  312. case "kcp", "mkcp":
  313. return "mkcp", nil
  314. case "ws", "websocket":
  315. return "websocket", nil
  316. case "h2", "http":
  317. return "http", nil
  318. case "ds", "domainsocket":
  319. return "domainsocket", nil
  320. case "quic":
  321. return "quic", nil
  322. case "gun", "grpc":
  323. return "gun", nil
  324. default:
  325. return "", newError("Config: unknown transport protocol: ", p)
  326. }
  327. }
  328. type SocketConfig struct {
  329. Mark int32 `json:"mark"`
  330. TFO *bool `json:"tcpFastOpen"`
  331. TProxy string `json:"tproxy"`
  332. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  333. }
  334. // Build implements Buildable.
  335. func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
  336. var tfoSettings internet.SocketConfig_TCPFastOpenState
  337. if c.TFO != nil {
  338. if *c.TFO {
  339. tfoSettings = internet.SocketConfig_Enable
  340. } else {
  341. tfoSettings = internet.SocketConfig_Disable
  342. }
  343. }
  344. var tproxy internet.SocketConfig_TProxyMode
  345. switch strings.ToLower(c.TProxy) {
  346. case "tproxy":
  347. tproxy = internet.SocketConfig_TProxy
  348. case "redirect":
  349. tproxy = internet.SocketConfig_Redirect
  350. default:
  351. tproxy = internet.SocketConfig_Off
  352. }
  353. return &internet.SocketConfig{
  354. Mark: c.Mark,
  355. Tfo: tfoSettings,
  356. Tproxy: tproxy,
  357. AcceptProxyProtocol: c.AcceptProxyProtocol,
  358. }, nil
  359. }
  360. type StreamConfig struct {
  361. Network *TransportProtocol `json:"network"`
  362. Security string `json:"security"`
  363. TLSSettings *TLSConfig `json:"tlsSettings"`
  364. TCPSettings *TCPConfig `json:"tcpSettings"`
  365. KCPSettings *KCPConfig `json:"kcpSettings"`
  366. WSSettings *WebSocketConfig `json:"wsSettings"`
  367. HTTPSettings *HTTPConfig `json:"httpSettings"`
  368. DSSettings *DomainSocketConfig `json:"dsSettings"`
  369. QUICSettings *QUICConfig `json:"quicSettings"`
  370. GunSettings *GunConfig `json:"gunSettings"`
  371. GRPCSettings *GunConfig `json:"grpcSettings"`
  372. SocketSettings *SocketConfig `json:"sockopt"`
  373. }
  374. // Build implements Buildable.
  375. func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
  376. config := &internet.StreamConfig{
  377. ProtocolName: "tcp",
  378. }
  379. if c.Network != nil {
  380. protocol, err := c.Network.Build()
  381. if err != nil {
  382. return nil, err
  383. }
  384. config.ProtocolName = protocol
  385. }
  386. if strings.EqualFold(c.Security, "tls") {
  387. tlsSettings := c.TLSSettings
  388. if tlsSettings == nil {
  389. tlsSettings = &TLSConfig{}
  390. }
  391. ts, err := tlsSettings.Build()
  392. if err != nil {
  393. return nil, newError("Failed to build TLS config.").Base(err)
  394. }
  395. tm := serial.ToTypedMessage(ts)
  396. config.SecuritySettings = append(config.SecuritySettings, tm)
  397. config.SecurityType = tm.Type
  398. }
  399. if c.TCPSettings != nil {
  400. ts, err := c.TCPSettings.Build()
  401. if err != nil {
  402. return nil, newError("Failed to build TCP config.").Base(err)
  403. }
  404. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  405. ProtocolName: "tcp",
  406. Settings: serial.ToTypedMessage(ts),
  407. })
  408. }
  409. if c.KCPSettings != nil {
  410. ts, err := c.KCPSettings.Build()
  411. if err != nil {
  412. return nil, newError("Failed to build mKCP config.").Base(err)
  413. }
  414. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  415. ProtocolName: "mkcp",
  416. Settings: serial.ToTypedMessage(ts),
  417. })
  418. }
  419. if c.WSSettings != nil {
  420. ts, err := c.WSSettings.Build()
  421. if err != nil {
  422. return nil, newError("Failed to build WebSocket config.").Base(err)
  423. }
  424. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  425. ProtocolName: "websocket",
  426. Settings: serial.ToTypedMessage(ts),
  427. })
  428. }
  429. if c.HTTPSettings != nil {
  430. ts, err := c.HTTPSettings.Build()
  431. if err != nil {
  432. return nil, newError("Failed to build HTTP config.").Base(err)
  433. }
  434. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  435. ProtocolName: "http",
  436. Settings: serial.ToTypedMessage(ts),
  437. })
  438. }
  439. if c.DSSettings != nil {
  440. ds, err := c.DSSettings.Build()
  441. if err != nil {
  442. return nil, newError("Failed to build DomainSocket config.").Base(err)
  443. }
  444. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  445. ProtocolName: "domainsocket",
  446. Settings: serial.ToTypedMessage(ds),
  447. })
  448. }
  449. if c.QUICSettings != nil {
  450. qs, err := c.QUICSettings.Build()
  451. if err != nil {
  452. return nil, newError("Failed to build QUIC config.").Base(err)
  453. }
  454. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  455. ProtocolName: "quic",
  456. Settings: serial.ToTypedMessage(qs),
  457. })
  458. }
  459. if c.GunSettings == nil {
  460. c.GunSettings = c.GRPCSettings
  461. }
  462. if c.GunSettings != nil {
  463. gs, err := c.GunSettings.Build()
  464. if err != nil {
  465. return nil, newError("Failed to build Gun config.").Base(err)
  466. }
  467. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  468. ProtocolName: "gun",
  469. Settings: serial.ToTypedMessage(gs),
  470. })
  471. }
  472. if c.SocketSettings != nil {
  473. ss, err := c.SocketSettings.Build()
  474. if err != nil {
  475. return nil, newError("Failed to build sockopt.").Base(err)
  476. }
  477. config.SocketSettings = ss
  478. }
  479. return config, nil
  480. }
  481. type ProxyConfig struct {
  482. Tag string `json:"tag"`
  483. TransportLayerProxy bool `json:"transportLayer"`
  484. }
  485. // Build implements Buildable.
  486. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) {
  487. if v.Tag == "" {
  488. return nil, newError("Proxy tag is not set.")
  489. }
  490. return &internet.ProxyConfig{
  491. Tag: v.Tag,
  492. TransportLayerProxy: v.TransportLayerProxy,
  493. }, nil
  494. }