transport_internet.go 15 KB

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