transport_internet.go 13 KB

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