transport_internet.go 14 KB

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