transport_internet.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. DiableSystemRoot bool `json:"disableSystemRoot"`
  250. }
  251. // Build implements Buildable.
  252. func (c *TLSConfig) Build() (proto.Message, error) {
  253. config := new(tls.Config)
  254. config.Certificate = make([]*tls.Certificate, len(c.Certs))
  255. for idx, certConf := range c.Certs {
  256. cert, err := certConf.Build()
  257. if err != nil {
  258. return nil, err
  259. }
  260. config.Certificate[idx] = cert
  261. }
  262. serverName := c.ServerName
  263. config.AllowInsecure = c.Insecure
  264. config.AllowInsecureCiphers = c.InsecureCiphers
  265. if len(c.ServerName) > 0 {
  266. config.ServerName = serverName
  267. }
  268. if c.ALPN != nil && len(*c.ALPN) > 0 {
  269. config.NextProtocol = []string(*c.ALPN)
  270. }
  271. config.DisableSystemRoot = c.DiableSystemRoot
  272. return config, nil
  273. }
  274. type TransportProtocol string
  275. // Build implements Buildable.
  276. func (p TransportProtocol) Build() (string, error) {
  277. switch strings.ToLower(string(p)) {
  278. case "tcp":
  279. return "tcp", nil
  280. case "kcp", "mkcp":
  281. return "mkcp", nil
  282. case "ws", "websocket":
  283. return "websocket", nil
  284. case "h2", "http":
  285. return "http", nil
  286. case "ds", "domainsocket":
  287. return "domainsocket", nil
  288. case "quic":
  289. return "quic", nil
  290. default:
  291. return "", newError("Config: unknown transport protocol: ", p)
  292. }
  293. }
  294. type SocketConfig struct {
  295. Mark int32 `json:"mark"`
  296. TFO *bool `json:"tcpFastOpen"`
  297. TProxy string `json:"tproxy"`
  298. }
  299. func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
  300. var tfoSettings internet.SocketConfig_TCPFastOpenState
  301. if c.TFO != nil {
  302. if *c.TFO {
  303. tfoSettings = internet.SocketConfig_Enable
  304. } else {
  305. tfoSettings = internet.SocketConfig_Disable
  306. }
  307. }
  308. var tproxy internet.SocketConfig_TProxyMode
  309. switch strings.ToLower(c.TProxy) {
  310. case "tproxy":
  311. tproxy = internet.SocketConfig_TProxy
  312. case "redirect":
  313. tproxy = internet.SocketConfig_Redirect
  314. default:
  315. tproxy = internet.SocketConfig_Off
  316. }
  317. return &internet.SocketConfig{
  318. Mark: c.Mark,
  319. Tfo: tfoSettings,
  320. Tproxy: tproxy,
  321. }, nil
  322. }
  323. type StreamConfig struct {
  324. Network *TransportProtocol `json:"network"`
  325. Security string `json:"security"`
  326. TLSSettings *TLSConfig `json:"tlsSettings"`
  327. TCPSettings *TCPConfig `json:"tcpSettings"`
  328. KCPSettings *KCPConfig `json:"kcpSettings"`
  329. WSSettings *WebSocketConfig `json:"wsSettings"`
  330. HTTPSettings *HTTPConfig `json:"httpSettings"`
  331. DSSettings *DomainSocketConfig `json:"dsSettings"`
  332. QUICSettings *QUICConfig `json:"quicSettings"`
  333. SocketSettings *SocketConfig `json:"sockopt"`
  334. }
  335. // Build implements Buildable.
  336. func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
  337. config := &internet.StreamConfig{
  338. ProtocolName: "tcp",
  339. }
  340. if c.Network != nil {
  341. protocol, err := (*c.Network).Build()
  342. if err != nil {
  343. return nil, err
  344. }
  345. config.ProtocolName = protocol
  346. }
  347. if strings.EqualFold(c.Security, "tls") {
  348. tlsSettings := c.TLSSettings
  349. if tlsSettings == nil {
  350. tlsSettings = &TLSConfig{}
  351. }
  352. ts, err := tlsSettings.Build()
  353. if err != nil {
  354. return nil, newError("Failed to build TLS config.").Base(err)
  355. }
  356. tm := serial.ToTypedMessage(ts)
  357. config.SecuritySettings = append(config.SecuritySettings, tm)
  358. config.SecurityType = tm.Type
  359. }
  360. if c.TCPSettings != nil {
  361. ts, err := c.TCPSettings.Build()
  362. if err != nil {
  363. return nil, newError("Failed to build TCP config.").Base(err)
  364. }
  365. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  366. ProtocolName: "tcp",
  367. Settings: serial.ToTypedMessage(ts),
  368. })
  369. }
  370. if c.KCPSettings != nil {
  371. ts, err := c.KCPSettings.Build()
  372. if err != nil {
  373. return nil, newError("Failed to build mKCP config.").Base(err)
  374. }
  375. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  376. ProtocolName: "mkcp",
  377. Settings: serial.ToTypedMessage(ts),
  378. })
  379. }
  380. if c.WSSettings != nil {
  381. ts, err := c.WSSettings.Build()
  382. if err != nil {
  383. return nil, newError("Failed to build WebSocket config.").Base(err)
  384. }
  385. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  386. ProtocolName: "websocket",
  387. Settings: serial.ToTypedMessage(ts),
  388. })
  389. }
  390. if c.HTTPSettings != nil {
  391. ts, err := c.HTTPSettings.Build()
  392. if err != nil {
  393. return nil, newError("Failed to build HTTP config.").Base(err)
  394. }
  395. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  396. ProtocolName: "http",
  397. Settings: serial.ToTypedMessage(ts),
  398. })
  399. }
  400. if c.DSSettings != nil {
  401. ds, err := c.DSSettings.Build()
  402. if err != nil {
  403. return nil, newError("Failed to build DomainSocket config.").Base(err)
  404. }
  405. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  406. ProtocolName: "domainsocket",
  407. Settings: serial.ToTypedMessage(ds),
  408. })
  409. }
  410. if c.QUICSettings != nil {
  411. qs, err := c.QUICSettings.Build()
  412. if err != nil {
  413. return nil, newError("failed to build QUIC config").Base(err)
  414. }
  415. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  416. ProtocolName: "quic",
  417. Settings: serial.ToTypedMessage(qs),
  418. })
  419. }
  420. if c.SocketSettings != nil {
  421. ss, err := c.SocketSettings.Build()
  422. if err != nil {
  423. return nil, newError("failed to build sockopt").Base(err)
  424. }
  425. config.SocketSettings = ss
  426. }
  427. return config, nil
  428. }
  429. type ProxyConfig struct {
  430. Tag string `json:"tag"`
  431. }
  432. // Build implements Buildable.
  433. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) {
  434. if v.Tag == "" {
  435. return nil, newError("Proxy tag is not set.")
  436. }
  437. return &internet.ProxyConfig{
  438. Tag: v.Tag,
  439. }, nil
  440. }