transport_internet.go 14 KB

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