transport_internet.go 13 KB

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