transport_internet.go 15 KB

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