transport_internet.go 13 KB

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