transport_internet.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. Padding bool `json:"padding"`
  203. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  204. }
  205. func (c *DomainSocketConfig) Build() (proto.Message, error) {
  206. return &domainsocket.Config{
  207. Path: c.Path,
  208. Abstract: c.Abstract,
  209. Padding: c.Padding,
  210. AcceptProxyProtocol: c.AcceptProxyProtocol,
  211. }, nil
  212. }
  213. type TLSCertConfig struct {
  214. CertFile string `json:"certificateFile"`
  215. CertStr []string `json:"certificate"`
  216. KeyFile string `json:"keyFile"`
  217. KeyStr []string `json:"key"`
  218. Usage string `json:"usage"`
  219. }
  220. func readFileOrString(f string, s []string) ([]byte, error) {
  221. if len(f) > 0 {
  222. return filesystem.ReadFile(f)
  223. }
  224. if len(s) > 0 {
  225. return []byte(strings.Join(s, "\n")), nil
  226. }
  227. return nil, newError("both file and bytes are empty.")
  228. }
  229. func (c *TLSCertConfig) Build() (*tls.Certificate, error) {
  230. certificate := new(tls.Certificate)
  231. cert, err := readFileOrString(c.CertFile, c.CertStr)
  232. if err != nil {
  233. return nil, newError("failed to parse certificate").Base(err)
  234. }
  235. certificate.Certificate = cert
  236. if len(c.KeyFile) > 0 || len(c.KeyStr) > 0 {
  237. key, err := readFileOrString(c.KeyFile, c.KeyStr)
  238. if err != nil {
  239. return nil, newError("failed to parse key").Base(err)
  240. }
  241. certificate.Key = key
  242. }
  243. switch strings.ToLower(c.Usage) {
  244. case "encipherment":
  245. certificate.Usage = tls.Certificate_ENCIPHERMENT
  246. case "verify":
  247. certificate.Usage = tls.Certificate_AUTHORITY_VERIFY
  248. case "issue":
  249. certificate.Usage = tls.Certificate_AUTHORITY_ISSUE
  250. default:
  251. certificate.Usage = tls.Certificate_ENCIPHERMENT
  252. }
  253. return certificate, nil
  254. }
  255. type TLSConfig struct {
  256. Insecure bool `json:"allowInsecure"`
  257. InsecureCiphers bool `json:"allowInsecureCiphers"`
  258. Certs []*TLSCertConfig `json:"certificates"`
  259. ServerName string `json:"serverName"`
  260. ALPN *StringList `json:"alpn"`
  261. DisableSessionResumption bool `json:"disableSessionResumption"`
  262. DisableSystemRoot bool `json:"disableSystemRoot"`
  263. }
  264. // Build implements Buildable.
  265. func (c *TLSConfig) Build() (proto.Message, error) {
  266. config := new(tls.Config)
  267. config.Certificate = make([]*tls.Certificate, len(c.Certs))
  268. for idx, certConf := range c.Certs {
  269. cert, err := certConf.Build()
  270. if err != nil {
  271. return nil, err
  272. }
  273. config.Certificate[idx] = cert
  274. }
  275. serverName := c.ServerName
  276. config.AllowInsecure = c.Insecure
  277. config.AllowInsecureCiphers = c.InsecureCiphers
  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.DisableSessionResumption = c.DisableSessionResumption
  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. }
  313. func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
  314. var tfoSettings internet.SocketConfig_TCPFastOpenState
  315. if c.TFO != nil {
  316. if *c.TFO {
  317. tfoSettings = internet.SocketConfig_Enable
  318. } else {
  319. tfoSettings = internet.SocketConfig_Disable
  320. }
  321. }
  322. var tproxy internet.SocketConfig_TProxyMode
  323. switch strings.ToLower(c.TProxy) {
  324. case "tproxy":
  325. tproxy = internet.SocketConfig_TProxy
  326. case "redirect":
  327. tproxy = internet.SocketConfig_Redirect
  328. default:
  329. tproxy = internet.SocketConfig_Off
  330. }
  331. return &internet.SocketConfig{
  332. Mark: c.Mark,
  333. Tfo: tfoSettings,
  334. Tproxy: tproxy,
  335. }, nil
  336. }
  337. type StreamConfig struct {
  338. Network *TransportProtocol `json:"network"`
  339. Security string `json:"security"`
  340. TLSSettings *TLSConfig `json:"tlsSettings"`
  341. TCPSettings *TCPConfig `json:"tcpSettings"`
  342. KCPSettings *KCPConfig `json:"kcpSettings"`
  343. WSSettings *WebSocketConfig `json:"wsSettings"`
  344. HTTPSettings *HTTPConfig `json:"httpSettings"`
  345. DSSettings *DomainSocketConfig `json:"dsSettings"`
  346. QUICSettings *QUICConfig `json:"quicSettings"`
  347. SocketSettings *SocketConfig `json:"sockopt"`
  348. }
  349. // Build implements Buildable.
  350. func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
  351. config := &internet.StreamConfig{
  352. ProtocolName: "tcp",
  353. }
  354. if c.Network != nil {
  355. protocol, err := (*c.Network).Build()
  356. if err != nil {
  357. return nil, err
  358. }
  359. config.ProtocolName = protocol
  360. }
  361. if strings.EqualFold(c.Security, "tls") {
  362. tlsSettings := c.TLSSettings
  363. if tlsSettings == nil {
  364. tlsSettings = &TLSConfig{}
  365. }
  366. ts, err := tlsSettings.Build()
  367. if err != nil {
  368. return nil, newError("Failed to build TLS config.").Base(err)
  369. }
  370. tm := serial.ToTypedMessage(ts)
  371. config.SecuritySettings = append(config.SecuritySettings, tm)
  372. config.SecurityType = tm.Type
  373. }
  374. if c.TCPSettings != nil {
  375. ts, err := c.TCPSettings.Build()
  376. if err != nil {
  377. return nil, newError("Failed to build TCP config.").Base(err)
  378. }
  379. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  380. ProtocolName: "tcp",
  381. Settings: serial.ToTypedMessage(ts),
  382. })
  383. }
  384. if c.KCPSettings != nil {
  385. ts, err := c.KCPSettings.Build()
  386. if err != nil {
  387. return nil, newError("Failed to build mKCP config.").Base(err)
  388. }
  389. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  390. ProtocolName: "mkcp",
  391. Settings: serial.ToTypedMessage(ts),
  392. })
  393. }
  394. if c.WSSettings != nil {
  395. ts, err := c.WSSettings.Build()
  396. if err != nil {
  397. return nil, newError("Failed to build WebSocket config.").Base(err)
  398. }
  399. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  400. ProtocolName: "websocket",
  401. Settings: serial.ToTypedMessage(ts),
  402. })
  403. }
  404. if c.HTTPSettings != nil {
  405. ts, err := c.HTTPSettings.Build()
  406. if err != nil {
  407. return nil, newError("Failed to build HTTP config.").Base(err)
  408. }
  409. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  410. ProtocolName: "http",
  411. Settings: serial.ToTypedMessage(ts),
  412. })
  413. }
  414. if c.DSSettings != nil {
  415. ds, err := c.DSSettings.Build()
  416. if err != nil {
  417. return nil, newError("Failed to build DomainSocket config.").Base(err)
  418. }
  419. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  420. ProtocolName: "domainsocket",
  421. Settings: serial.ToTypedMessage(ds),
  422. })
  423. }
  424. if c.QUICSettings != nil {
  425. qs, err := c.QUICSettings.Build()
  426. if err != nil {
  427. return nil, newError("failed to build QUIC config").Base(err)
  428. }
  429. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  430. ProtocolName: "quic",
  431. Settings: serial.ToTypedMessage(qs),
  432. })
  433. }
  434. if c.SocketSettings != nil {
  435. ss, err := c.SocketSettings.Build()
  436. if err != nil {
  437. return nil, newError("failed to build sockopt").Base(err)
  438. }
  439. config.SocketSettings = ss
  440. }
  441. return config, nil
  442. }
  443. type ProxyConfig struct {
  444. Tag string `json:"tag"`
  445. }
  446. // Build implements Buildable.
  447. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) {
  448. if v.Tag == "" {
  449. return nil, newError("Proxy tag is not set.")
  450. }
  451. return &internet.ProxyConfig{
  452. Tag: v.Tag,
  453. }, nil
  454. }