transport_internet.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. package conf
  2. import (
  3. "encoding/base64"
  4. "encoding/hex"
  5. "encoding/json"
  6. "math"
  7. "net/url"
  8. "runtime"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. "github.com/xtls/xray-core/common/net"
  13. "github.com/xtls/xray-core/common/platform/filesystem"
  14. "github.com/xtls/xray-core/common/protocol"
  15. "github.com/xtls/xray-core/common/serial"
  16. "github.com/xtls/xray-core/transport/internet"
  17. "github.com/xtls/xray-core/transport/internet/domainsocket"
  18. httpheader "github.com/xtls/xray-core/transport/internet/headers/http"
  19. "github.com/xtls/xray-core/transport/internet/http"
  20. "github.com/xtls/xray-core/transport/internet/kcp"
  21. "github.com/xtls/xray-core/transport/internet/quic"
  22. "github.com/xtls/xray-core/transport/internet/reality"
  23. "github.com/xtls/xray-core/transport/internet/tcp"
  24. "github.com/xtls/xray-core/transport/internet/tls"
  25. "github.com/xtls/xray-core/transport/internet/websocket"
  26. "google.golang.org/protobuf/proto"
  27. )
  28. var (
  29. kcpHeaderLoader = NewJSONConfigLoader(ConfigCreatorCache{
  30. "none": func() interface{} { return new(NoOpAuthenticator) },
  31. "srtp": func() interface{} { return new(SRTPAuthenticator) },
  32. "utp": func() interface{} { return new(UTPAuthenticator) },
  33. "wechat-video": func() interface{} { return new(WechatVideoAuthenticator) },
  34. "dtls": func() interface{} { return new(DTLSAuthenticator) },
  35. "wireguard": func() interface{} { return new(WireguardAuthenticator) },
  36. "dns": func() interface{} { return new(DNSAuthenticator) },
  37. }, "type", "")
  38. tcpHeaderLoader = NewJSONConfigLoader(ConfigCreatorCache{
  39. "none": func() interface{} { return new(NoOpConnectionAuthenticator) },
  40. "http": func() interface{} { return new(Authenticator) },
  41. }, "type", "")
  42. )
  43. type KCPConfig struct {
  44. Mtu *uint32 `json:"mtu"`
  45. Tti *uint32 `json:"tti"`
  46. UpCap *uint32 `json:"uplinkCapacity"`
  47. DownCap *uint32 `json:"downlinkCapacity"`
  48. Congestion *bool `json:"congestion"`
  49. ReadBufferSize *uint32 `json:"readBufferSize"`
  50. WriteBufferSize *uint32 `json:"writeBufferSize"`
  51. HeaderConfig json.RawMessage `json:"header"`
  52. Seed *string `json:"seed"`
  53. }
  54. // Build implements Buildable.
  55. func (c *KCPConfig) Build() (proto.Message, error) {
  56. config := new(kcp.Config)
  57. if c.Mtu != nil {
  58. mtu := *c.Mtu
  59. if mtu < 576 || mtu > 1460 {
  60. return nil, newError("invalid mKCP MTU size: ", mtu).AtError()
  61. }
  62. config.Mtu = &kcp.MTU{Value: mtu}
  63. }
  64. if c.Tti != nil {
  65. tti := *c.Tti
  66. if tti < 10 || tti > 100 {
  67. return nil, newError("invalid mKCP TTI: ", tti).AtError()
  68. }
  69. config.Tti = &kcp.TTI{Value: tti}
  70. }
  71. if c.UpCap != nil {
  72. config.UplinkCapacity = &kcp.UplinkCapacity{Value: *c.UpCap}
  73. }
  74. if c.DownCap != nil {
  75. config.DownlinkCapacity = &kcp.DownlinkCapacity{Value: *c.DownCap}
  76. }
  77. if c.Congestion != nil {
  78. config.Congestion = *c.Congestion
  79. }
  80. if c.ReadBufferSize != nil {
  81. size := *c.ReadBufferSize
  82. if size > 0 {
  83. config.ReadBuffer = &kcp.ReadBuffer{Size: size * 1024 * 1024}
  84. } else {
  85. config.ReadBuffer = &kcp.ReadBuffer{Size: 512 * 1024}
  86. }
  87. }
  88. if c.WriteBufferSize != nil {
  89. size := *c.WriteBufferSize
  90. if size > 0 {
  91. config.WriteBuffer = &kcp.WriteBuffer{Size: size * 1024 * 1024}
  92. } else {
  93. config.WriteBuffer = &kcp.WriteBuffer{Size: 512 * 1024}
  94. }
  95. }
  96. if len(c.HeaderConfig) > 0 {
  97. headerConfig, _, err := kcpHeaderLoader.Load(c.HeaderConfig)
  98. if err != nil {
  99. return nil, newError("invalid mKCP header config.").Base(err).AtError()
  100. }
  101. ts, err := headerConfig.(Buildable).Build()
  102. if err != nil {
  103. return nil, newError("invalid mKCP header config").Base(err).AtError()
  104. }
  105. config.HeaderConfig = serial.ToTypedMessage(ts)
  106. }
  107. if c.Seed != nil {
  108. config.Seed = &kcp.EncryptionSeed{Seed: *c.Seed}
  109. }
  110. return config, nil
  111. }
  112. type TCPConfig struct {
  113. HeaderConfig json.RawMessage `json:"header"`
  114. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  115. }
  116. // Build implements Buildable.
  117. func (c *TCPConfig) Build() (proto.Message, error) {
  118. config := new(tcp.Config)
  119. if len(c.HeaderConfig) > 0 {
  120. headerConfig, _, err := tcpHeaderLoader.Load(c.HeaderConfig)
  121. if err != nil {
  122. return nil, newError("invalid TCP header config").Base(err).AtError()
  123. }
  124. ts, err := headerConfig.(Buildable).Build()
  125. if err != nil {
  126. return nil, newError("invalid TCP header config").Base(err).AtError()
  127. }
  128. config.HeaderSettings = serial.ToTypedMessage(ts)
  129. }
  130. if c.AcceptProxyProtocol {
  131. config.AcceptProxyProtocol = c.AcceptProxyProtocol
  132. }
  133. return config, nil
  134. }
  135. type WebSocketConfig struct {
  136. Path string `json:"path"`
  137. Headers map[string]string `json:"headers"`
  138. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  139. }
  140. // Build implements Buildable.
  141. func (c *WebSocketConfig) Build() (proto.Message, error) {
  142. path := c.Path
  143. header := make([]*websocket.Header, 0, 32)
  144. for key, value := range c.Headers {
  145. header = append(header, &websocket.Header{
  146. Key: key,
  147. Value: value,
  148. })
  149. }
  150. var ed uint32
  151. if u, err := url.Parse(path); err == nil {
  152. if q := u.Query(); q.Get("ed") != "" {
  153. Ed, _ := strconv.Atoi(q.Get("ed"))
  154. ed = uint32(Ed)
  155. q.Del("ed")
  156. u.RawQuery = q.Encode()
  157. path = u.String()
  158. }
  159. }
  160. config := &websocket.Config{
  161. Path: path,
  162. Header: header,
  163. Ed: ed,
  164. }
  165. if c.AcceptProxyProtocol {
  166. config.AcceptProxyProtocol = c.AcceptProxyProtocol
  167. }
  168. return config, nil
  169. }
  170. type HTTPConfig struct {
  171. Host *StringList `json:"host"`
  172. Path string `json:"path"`
  173. ReadIdleTimeout int32 `json:"read_idle_timeout"`
  174. HealthCheckTimeout int32 `json:"health_check_timeout"`
  175. Method string `json:"method"`
  176. Headers map[string]*StringList `json:"headers"`
  177. }
  178. // Build implements Buildable.
  179. func (c *HTTPConfig) Build() (proto.Message, error) {
  180. if c.ReadIdleTimeout <= 0 {
  181. c.ReadIdleTimeout = 0
  182. }
  183. if c.HealthCheckTimeout <= 0 {
  184. c.HealthCheckTimeout = 0
  185. }
  186. config := &http.Config{
  187. Path: c.Path,
  188. IdleTimeout: c.ReadIdleTimeout,
  189. HealthCheckTimeout: c.HealthCheckTimeout,
  190. }
  191. if c.Host != nil {
  192. config.Host = []string(*c.Host)
  193. }
  194. if c.Method != "" {
  195. config.Method = c.Method
  196. }
  197. if len(c.Headers) > 0 {
  198. config.Header = make([]*httpheader.Header, 0, len(c.Headers))
  199. headerNames := sortMapKeys(c.Headers)
  200. for _, key := range headerNames {
  201. value := c.Headers[key]
  202. if value == nil {
  203. return nil, newError("empty HTTP header value: " + key).AtError()
  204. }
  205. config.Header = append(config.Header, &httpheader.Header{
  206. Name: key,
  207. Value: append([]string(nil), (*value)...),
  208. })
  209. }
  210. }
  211. return config, nil
  212. }
  213. type QUICConfig struct {
  214. Header json.RawMessage `json:"header"`
  215. Security string `json:"security"`
  216. Key string `json:"key"`
  217. }
  218. // Build implements Buildable.
  219. func (c *QUICConfig) Build() (proto.Message, error) {
  220. config := &quic.Config{
  221. Key: c.Key,
  222. }
  223. if len(c.Header) > 0 {
  224. headerConfig, _, err := kcpHeaderLoader.Load(c.Header)
  225. if err != nil {
  226. return nil, newError("invalid QUIC header config.").Base(err).AtError()
  227. }
  228. ts, err := headerConfig.(Buildable).Build()
  229. if err != nil {
  230. return nil, newError("invalid QUIC header config").Base(err).AtError()
  231. }
  232. config.Header = serial.ToTypedMessage(ts)
  233. }
  234. var st protocol.SecurityType
  235. switch strings.ToLower(c.Security) {
  236. case "aes-128-gcm":
  237. st = protocol.SecurityType_AES128_GCM
  238. case "chacha20-poly1305":
  239. st = protocol.SecurityType_CHACHA20_POLY1305
  240. default:
  241. st = protocol.SecurityType_NONE
  242. }
  243. config.Security = &protocol.SecurityConfig{
  244. Type: st,
  245. }
  246. return config, nil
  247. }
  248. type DomainSocketConfig struct {
  249. Path string `json:"path"`
  250. Abstract bool `json:"abstract"`
  251. Padding bool `json:"padding"`
  252. }
  253. // Build implements Buildable.
  254. func (c *DomainSocketConfig) Build() (proto.Message, error) {
  255. return &domainsocket.Config{
  256. Path: c.Path,
  257. Abstract: c.Abstract,
  258. Padding: c.Padding,
  259. }, nil
  260. }
  261. func readFileOrString(f string, s []string) ([]byte, error) {
  262. if len(f) > 0 {
  263. return filesystem.ReadFile(f)
  264. }
  265. if len(s) > 0 {
  266. return []byte(strings.Join(s, "\n")), nil
  267. }
  268. return nil, newError("both file and bytes are empty.")
  269. }
  270. type TLSCertConfig struct {
  271. CertFile string `json:"certificateFile"`
  272. CertStr []string `json:"certificate"`
  273. KeyFile string `json:"keyFile"`
  274. KeyStr []string `json:"key"`
  275. Usage string `json:"usage"`
  276. OcspStapling uint64 `json:"ocspStapling"`
  277. OneTimeLoading bool `json:"oneTimeLoading"`
  278. }
  279. // Build implements Buildable.
  280. func (c *TLSCertConfig) Build() (*tls.Certificate, error) {
  281. certificate := new(tls.Certificate)
  282. cert, err := readFileOrString(c.CertFile, c.CertStr)
  283. if err != nil {
  284. return nil, newError("failed to parse certificate").Base(err)
  285. }
  286. certificate.Certificate = cert
  287. certificate.CertificatePath = c.CertFile
  288. if len(c.KeyFile) > 0 || len(c.KeyStr) > 0 {
  289. key, err := readFileOrString(c.KeyFile, c.KeyStr)
  290. if err != nil {
  291. return nil, newError("failed to parse key").Base(err)
  292. }
  293. certificate.Key = key
  294. certificate.KeyPath = c.KeyFile
  295. }
  296. switch strings.ToLower(c.Usage) {
  297. case "encipherment":
  298. certificate.Usage = tls.Certificate_ENCIPHERMENT
  299. case "verify":
  300. certificate.Usage = tls.Certificate_AUTHORITY_VERIFY
  301. case "issue":
  302. certificate.Usage = tls.Certificate_AUTHORITY_ISSUE
  303. default:
  304. certificate.Usage = tls.Certificate_ENCIPHERMENT
  305. }
  306. if certificate.KeyPath == "" && certificate.CertificatePath == "" {
  307. certificate.OneTimeLoading = true
  308. } else {
  309. certificate.OneTimeLoading = c.OneTimeLoading
  310. }
  311. certificate.OcspStapling = c.OcspStapling
  312. return certificate, nil
  313. }
  314. type TLSConfig struct {
  315. Insecure bool `json:"allowInsecure"`
  316. Certs []*TLSCertConfig `json:"certificates"`
  317. ServerName string `json:"serverName"`
  318. ALPN *StringList `json:"alpn"`
  319. EnableSessionResumption bool `json:"enableSessionResumption"`
  320. DisableSystemRoot bool `json:"disableSystemRoot"`
  321. MinVersion string `json:"minVersion"`
  322. MaxVersion string `json:"maxVersion"`
  323. CipherSuites string `json:"cipherSuites"`
  324. PreferServerCipherSuites bool `json:"preferServerCipherSuites"`
  325. Fingerprint string `json:"fingerprint"`
  326. RejectUnknownSNI bool `json:"rejectUnknownSni"`
  327. PinnedPeerCertificateChainSha256 *[]string `json:"pinnedPeerCertificateChainSha256"`
  328. PinnedPeerCertificatePublicKeySha256 *[]string `json:"pinnedPeerCertificatePublicKeySha256"`
  329. }
  330. // Build implements Buildable.
  331. func (c *TLSConfig) Build() (proto.Message, error) {
  332. config := new(tls.Config)
  333. config.Certificate = make([]*tls.Certificate, len(c.Certs))
  334. for idx, certConf := range c.Certs {
  335. cert, err := certConf.Build()
  336. if err != nil {
  337. return nil, err
  338. }
  339. config.Certificate[idx] = cert
  340. }
  341. serverName := c.ServerName
  342. config.AllowInsecure = c.Insecure
  343. if len(c.ServerName) > 0 {
  344. config.ServerName = serverName
  345. }
  346. if c.ALPN != nil && len(*c.ALPN) > 0 {
  347. config.NextProtocol = []string(*c.ALPN)
  348. }
  349. config.EnableSessionResumption = c.EnableSessionResumption
  350. config.DisableSystemRoot = c.DisableSystemRoot
  351. config.MinVersion = c.MinVersion
  352. config.MaxVersion = c.MaxVersion
  353. config.CipherSuites = c.CipherSuites
  354. config.PreferServerCipherSuites = c.PreferServerCipherSuites
  355. config.Fingerprint = strings.ToLower(c.Fingerprint)
  356. if config.Fingerprint != "" && tls.GetFingerprint(config.Fingerprint) == nil {
  357. return nil, newError(`unknown fingerprint: `, config.Fingerprint)
  358. }
  359. config.RejectUnknownSni = c.RejectUnknownSNI
  360. if c.PinnedPeerCertificateChainSha256 != nil {
  361. config.PinnedPeerCertificateChainSha256 = [][]byte{}
  362. for _, v := range *c.PinnedPeerCertificateChainSha256 {
  363. hashValue, err := base64.StdEncoding.DecodeString(v)
  364. if err != nil {
  365. return nil, err
  366. }
  367. config.PinnedPeerCertificateChainSha256 = append(config.PinnedPeerCertificateChainSha256, hashValue)
  368. }
  369. }
  370. if c.PinnedPeerCertificatePublicKeySha256 != nil {
  371. config.PinnedPeerCertificatePublicKeySha256 = [][]byte{}
  372. for _, v := range *c.PinnedPeerCertificatePublicKeySha256 {
  373. hashValue, err := base64.StdEncoding.DecodeString(v)
  374. if err != nil {
  375. return nil, err
  376. }
  377. config.PinnedPeerCertificatePublicKeySha256 = append(config.PinnedPeerCertificatePublicKeySha256, hashValue)
  378. }
  379. }
  380. return config, nil
  381. }
  382. type REALITYConfig struct {
  383. Show bool `json:"show"`
  384. Dest json.RawMessage `json:"dest"`
  385. Type string `json:"type"`
  386. Xver uint64 `json:"xver"`
  387. ServerNames []string `json:"serverNames"`
  388. PrivateKey string `json:"privateKey"`
  389. MinClientVer string `json:"minClientVer"`
  390. MaxClientVer string `json:"maxClientVer"`
  391. MaxTimeDiff uint64 `json:"maxTimeDiff"`
  392. ShortIds []string `json:"shortIds"`
  393. Fingerprint string `json:"fingerprint"`
  394. ServerName string `json:"serverName"`
  395. PublicKey string `json:"publicKey"`
  396. ShortId string `json:"shortId"`
  397. SpiderX string `json:"spiderX"`
  398. }
  399. func (c *REALITYConfig) Build() (proto.Message, error) {
  400. config := new(reality.Config)
  401. config.Show = c.Show
  402. var err error
  403. if c.Dest != nil {
  404. var i uint16
  405. var s string
  406. if err = json.Unmarshal(c.Dest, &i); err == nil {
  407. s = strconv.Itoa(int(i))
  408. } else {
  409. _ = json.Unmarshal(c.Dest, &s)
  410. }
  411. if c.Type == "" && s != "" {
  412. switch s[0] {
  413. case '@', '/':
  414. c.Type = "unix"
  415. if s[0] == '@' && len(s) > 1 && s[1] == '@' && (runtime.GOOS == "linux" || runtime.GOOS == "android") {
  416. fullAddr := make([]byte, len(syscall.RawSockaddrUnix{}.Path)) // may need padding to work with haproxy
  417. copy(fullAddr, s[1:])
  418. s = string(fullAddr)
  419. }
  420. default:
  421. if _, err = strconv.Atoi(s); err == nil {
  422. s = "127.0.0.1:" + s
  423. }
  424. if _, _, err = net.SplitHostPort(s); err == nil {
  425. c.Type = "tcp"
  426. }
  427. }
  428. }
  429. if c.Type == "" {
  430. return nil, newError(`please fill in a valid value for "dest"`)
  431. }
  432. if c.Xver > 2 {
  433. return nil, newError(`invalid PROXY protocol version, "xver" only accepts 0, 1, 2`)
  434. }
  435. if len(c.ServerNames) == 0 {
  436. return nil, newError(`empty "serverNames"`)
  437. }
  438. if c.PrivateKey == "" {
  439. return nil, newError(`empty "privateKey"`)
  440. }
  441. if config.PrivateKey, err = base64.RawURLEncoding.DecodeString(c.PrivateKey); err != nil || len(config.PrivateKey) != 32 {
  442. return nil, newError(`invalid "privateKey": `, c.PrivateKey)
  443. }
  444. if c.MinClientVer != "" {
  445. config.MinClientVer = make([]byte, 3)
  446. var u uint64
  447. for i, s := range strings.Split(c.MinClientVer, ".") {
  448. if i == 3 {
  449. return nil, newError(`invalid "minClientVer": `, c.MinClientVer)
  450. }
  451. if u, err = strconv.ParseUint(s, 10, 8); err != nil {
  452. return nil, newError(`"minClientVer[`, i, `]" should be lesser than 256`)
  453. } else {
  454. config.MinClientVer[i] = byte(u)
  455. }
  456. }
  457. }
  458. if c.MaxClientVer != "" {
  459. config.MaxClientVer = make([]byte, 3)
  460. var u uint64
  461. for i, s := range strings.Split(c.MaxClientVer, ".") {
  462. if i == 3 {
  463. return nil, newError(`invalid "maxClientVer": `, c.MaxClientVer)
  464. }
  465. if u, err = strconv.ParseUint(s, 10, 8); err != nil {
  466. return nil, newError(`"maxClientVer[`, i, `]" should be lesser than 256`)
  467. } else {
  468. config.MaxClientVer[i] = byte(u)
  469. }
  470. }
  471. }
  472. if len(c.ShortIds) == 0 {
  473. return nil, newError(`empty "shortIds"`)
  474. }
  475. config.ShortIds = make([][]byte, len(c.ShortIds))
  476. for i, s := range c.ShortIds {
  477. config.ShortIds[i] = make([]byte, 8)
  478. if _, err = hex.Decode(config.ShortIds[i], []byte(s)); err != nil {
  479. return nil, newError(`invalid "shortIds[`, i, `]": `, s)
  480. }
  481. }
  482. config.Dest = s
  483. config.Type = c.Type
  484. config.Xver = c.Xver
  485. config.ServerNames = c.ServerNames
  486. config.MaxTimeDiff = c.MaxTimeDiff
  487. } else {
  488. if c.Fingerprint == "" {
  489. return nil, newError(`empty "fingerprint"`)
  490. }
  491. if config.Fingerprint = strings.ToLower(c.Fingerprint); tls.GetFingerprint(config.Fingerprint) == nil {
  492. return nil, newError(`unknown "fingerprint": `, config.Fingerprint)
  493. }
  494. if config.Fingerprint == "hellogolang" {
  495. return nil, newError(`invalid "fingerprint": `, config.Fingerprint)
  496. }
  497. if len(c.ServerNames) != 0 {
  498. return nil, newError(`non-empty "serverNames", please use "serverName" instead`)
  499. }
  500. if c.PublicKey == "" {
  501. return nil, newError(`empty "publicKey"`)
  502. }
  503. if config.PublicKey, err = base64.RawURLEncoding.DecodeString(c.PublicKey); err != nil || len(config.PublicKey) != 32 {
  504. return nil, newError(`invalid "publicKey": `, c.PublicKey)
  505. }
  506. if len(c.ShortIds) != 0 {
  507. return nil, newError(`non-empty "shortIds", please use "shortId" instead`)
  508. }
  509. config.ShortId = make([]byte, 8)
  510. if _, err = hex.Decode(config.ShortId, []byte(c.ShortId)); err != nil {
  511. return nil, newError(`invalid "shortId": `, c.ShortId)
  512. }
  513. if c.SpiderX == "" {
  514. c.SpiderX = "/"
  515. }
  516. if c.SpiderX[0] != '/' {
  517. return nil, newError(`invalid "spiderX": `, c.SpiderX)
  518. }
  519. config.SpiderY = make([]int64, 10)
  520. u, _ := url.Parse(c.SpiderX)
  521. q := u.Query()
  522. parse := func(param string, index int) {
  523. if q.Get(param) != "" {
  524. s := strings.Split(q.Get(param), "-")
  525. if len(s) == 1 {
  526. config.SpiderY[index], _ = strconv.ParseInt(s[0], 10, 64)
  527. config.SpiderY[index+1], _ = strconv.ParseInt(s[0], 10, 64)
  528. } else {
  529. config.SpiderY[index], _ = strconv.ParseInt(s[0], 10, 64)
  530. config.SpiderY[index+1], _ = strconv.ParseInt(s[1], 10, 64)
  531. }
  532. }
  533. q.Del(param)
  534. }
  535. parse("p", 0) // padding
  536. parse("c", 2) // concurrency
  537. parse("t", 4) // times
  538. parse("i", 6) // interval
  539. parse("r", 8) // return
  540. u.RawQuery = q.Encode()
  541. config.SpiderX = u.String()
  542. config.ServerName = c.ServerName
  543. }
  544. return config, nil
  545. }
  546. type TransportProtocol string
  547. // Build implements Buildable.
  548. func (p TransportProtocol) Build() (string, error) {
  549. switch strings.ToLower(string(p)) {
  550. case "tcp":
  551. return "tcp", nil
  552. case "kcp", "mkcp":
  553. return "mkcp", nil
  554. case "ws", "websocket":
  555. return "websocket", nil
  556. case "h2", "http":
  557. return "http", nil
  558. case "ds", "domainsocket":
  559. return "domainsocket", nil
  560. case "quic":
  561. return "quic", nil
  562. case "grpc", "gun":
  563. return "grpc", nil
  564. default:
  565. return "", newError("Config: unknown transport protocol: ", p)
  566. }
  567. }
  568. type SocketConfig struct {
  569. Mark int32 `json:"mark"`
  570. TFO interface{} `json:"tcpFastOpen"`
  571. TProxy string `json:"tproxy"`
  572. AcceptProxyProtocol bool `json:"acceptProxyProtocol"`
  573. DomainStrategy string `json:"domainStrategy"`
  574. DialerProxy string `json:"dialerProxy"`
  575. TCPKeepAliveInterval int32 `json:"tcpKeepAliveInterval"`
  576. TCPKeepAliveIdle int32 `json:"tcpKeepAliveIdle"`
  577. TCPCongestion string `json:"tcpCongestion"`
  578. TCPWindowClamp int32 `json:"tcpWindowClamp"`
  579. TCPMaxSeg int32 `json:"tcpMaxSeg"`
  580. TcpNoDelay bool `json:"tcpNoDelay"`
  581. TCPUserTimeout int32 `json:"tcpUserTimeout"`
  582. V6only bool `json:"v6only"`
  583. Interface string `json:"interface"`
  584. TcpMptcp bool `json:"tcpMptcp"`
  585. }
  586. // Build implements Buildable.
  587. func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
  588. tfo := int32(0) // don't invoke setsockopt() for TFO
  589. if c.TFO != nil {
  590. switch v := c.TFO.(type) {
  591. case bool:
  592. if v {
  593. tfo = 256
  594. } else {
  595. tfo = -1 // TFO need to be disabled
  596. }
  597. case float64:
  598. tfo = int32(math.Min(v, math.MaxInt32))
  599. default:
  600. return nil, newError("tcpFastOpen: only boolean and integer value is acceptable")
  601. }
  602. }
  603. var tproxy internet.SocketConfig_TProxyMode
  604. switch strings.ToLower(c.TProxy) {
  605. case "tproxy":
  606. tproxy = internet.SocketConfig_TProxy
  607. case "redirect":
  608. tproxy = internet.SocketConfig_Redirect
  609. default:
  610. tproxy = internet.SocketConfig_Off
  611. }
  612. dStrategy := internet.DomainStrategy_AS_IS
  613. switch strings.ToLower(c.DomainStrategy) {
  614. case "useip", "use_ip":
  615. dStrategy = internet.DomainStrategy_USE_IP
  616. case "useip4", "useipv4", "use_ipv4", "use_ip_v4", "use_ip4":
  617. dStrategy = internet.DomainStrategy_USE_IP4
  618. case "useip6", "useipv6", "use_ipv6", "use_ip_v6", "use_ip6":
  619. dStrategy = internet.DomainStrategy_USE_IP6
  620. }
  621. return &internet.SocketConfig{
  622. Mark: c.Mark,
  623. Tfo: tfo,
  624. Tproxy: tproxy,
  625. DomainStrategy: dStrategy,
  626. AcceptProxyProtocol: c.AcceptProxyProtocol,
  627. DialerProxy: c.DialerProxy,
  628. TcpKeepAliveInterval: c.TCPKeepAliveInterval,
  629. TcpKeepAliveIdle: c.TCPKeepAliveIdle,
  630. TcpCongestion: c.TCPCongestion,
  631. TcpWindowClamp: c.TCPWindowClamp,
  632. TcpMaxSeg: c.TCPMaxSeg,
  633. TcpNoDelay: c.TcpNoDelay,
  634. TcpUserTimeout: c.TCPUserTimeout,
  635. V6Only: c.V6only,
  636. Interface: c.Interface,
  637. TcpMptcp: c.TcpMptcp,
  638. }, nil
  639. }
  640. type StreamConfig struct {
  641. Network *TransportProtocol `json:"network"`
  642. Security string `json:"security"`
  643. TLSSettings *TLSConfig `json:"tlsSettings"`
  644. REALITYSettings *REALITYConfig `json:"realitySettings"`
  645. TCPSettings *TCPConfig `json:"tcpSettings"`
  646. KCPSettings *KCPConfig `json:"kcpSettings"`
  647. WSSettings *WebSocketConfig `json:"wsSettings"`
  648. HTTPSettings *HTTPConfig `json:"httpSettings"`
  649. DSSettings *DomainSocketConfig `json:"dsSettings"`
  650. QUICSettings *QUICConfig `json:"quicSettings"`
  651. SocketSettings *SocketConfig `json:"sockopt"`
  652. GRPCConfig *GRPCConfig `json:"grpcSettings"`
  653. GUNConfig *GRPCConfig `json:"gunSettings"`
  654. }
  655. // Build implements Buildable.
  656. func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
  657. config := &internet.StreamConfig{
  658. ProtocolName: "tcp",
  659. }
  660. if c.Network != nil {
  661. protocol, err := c.Network.Build()
  662. if err != nil {
  663. return nil, err
  664. }
  665. config.ProtocolName = protocol
  666. }
  667. switch strings.ToLower(c.Security) {
  668. case "", "none":
  669. case "tls":
  670. tlsSettings := c.TLSSettings
  671. if tlsSettings == nil {
  672. tlsSettings = &TLSConfig{}
  673. }
  674. ts, err := tlsSettings.Build()
  675. if err != nil {
  676. return nil, newError("Failed to build TLS config.").Base(err)
  677. }
  678. tm := serial.ToTypedMessage(ts)
  679. config.SecuritySettings = append(config.SecuritySettings, tm)
  680. config.SecurityType = tm.Type
  681. case "reality":
  682. if config.ProtocolName != "tcp" && config.ProtocolName != "http" && config.ProtocolName != "grpc" && config.ProtocolName != "domainsocket" {
  683. return nil, newError("REALITY only supports TCP, H2, gRPC and DomainSocket for now.")
  684. }
  685. if c.REALITYSettings == nil {
  686. return nil, newError(`REALITY: Empty "realitySettings".`)
  687. }
  688. ts, err := c.REALITYSettings.Build()
  689. if err != nil {
  690. return nil, newError("Failed to build REALITY config.").Base(err)
  691. }
  692. tm := serial.ToTypedMessage(ts)
  693. config.SecuritySettings = append(config.SecuritySettings, tm)
  694. config.SecurityType = tm.Type
  695. case "xtls":
  696. return nil, newError(`Please use VLESS flow "xtls-rprx-vision" with TLS or REALITY.`)
  697. default:
  698. return nil, newError(`Unknown security "` + c.Security + `".`)
  699. }
  700. if c.TCPSettings != nil {
  701. ts, err := c.TCPSettings.Build()
  702. if err != nil {
  703. return nil, newError("Failed to build TCP config.").Base(err)
  704. }
  705. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  706. ProtocolName: "tcp",
  707. Settings: serial.ToTypedMessage(ts),
  708. })
  709. }
  710. if c.KCPSettings != nil {
  711. ts, err := c.KCPSettings.Build()
  712. if err != nil {
  713. return nil, newError("Failed to build mKCP config.").Base(err)
  714. }
  715. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  716. ProtocolName: "mkcp",
  717. Settings: serial.ToTypedMessage(ts),
  718. })
  719. }
  720. if c.WSSettings != nil {
  721. ts, err := c.WSSettings.Build()
  722. if err != nil {
  723. return nil, newError("Failed to build WebSocket config.").Base(err)
  724. }
  725. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  726. ProtocolName: "websocket",
  727. Settings: serial.ToTypedMessage(ts),
  728. })
  729. }
  730. if c.HTTPSettings != nil {
  731. ts, err := c.HTTPSettings.Build()
  732. if err != nil {
  733. return nil, newError("Failed to build HTTP config.").Base(err)
  734. }
  735. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  736. ProtocolName: "http",
  737. Settings: serial.ToTypedMessage(ts),
  738. })
  739. }
  740. if c.DSSettings != nil {
  741. ds, err := c.DSSettings.Build()
  742. if err != nil {
  743. return nil, newError("Failed to build DomainSocket config.").Base(err)
  744. }
  745. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  746. ProtocolName: "domainsocket",
  747. Settings: serial.ToTypedMessage(ds),
  748. })
  749. }
  750. if c.QUICSettings != nil {
  751. qs, err := c.QUICSettings.Build()
  752. if err != nil {
  753. return nil, newError("Failed to build QUIC config").Base(err)
  754. }
  755. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  756. ProtocolName: "quic",
  757. Settings: serial.ToTypedMessage(qs),
  758. })
  759. }
  760. if c.GRPCConfig == nil {
  761. c.GRPCConfig = c.GUNConfig
  762. }
  763. if c.GRPCConfig != nil {
  764. gs, err := c.GRPCConfig.Build()
  765. if err != nil {
  766. return nil, newError("Failed to build gRPC config.").Base(err)
  767. }
  768. config.TransportSettings = append(config.TransportSettings, &internet.TransportConfig{
  769. ProtocolName: "grpc",
  770. Settings: serial.ToTypedMessage(gs),
  771. })
  772. }
  773. if c.SocketSettings != nil {
  774. ss, err := c.SocketSettings.Build()
  775. if err != nil {
  776. return nil, newError("Failed to build sockopt").Base(err)
  777. }
  778. config.SocketSettings = ss
  779. }
  780. return config, nil
  781. }
  782. type ProxyConfig struct {
  783. Tag string `json:"tag"`
  784. // TransportLayerProxy: For compatibility.
  785. TransportLayerProxy bool `json:"transportLayer"`
  786. }
  787. // Build implements Buildable.
  788. func (v *ProxyConfig) Build() (*internet.ProxyConfig, error) {
  789. if v.Tag == "" {
  790. return nil, newError("Proxy tag is not set.")
  791. }
  792. return &internet.ProxyConfig{
  793. Tag: v.Tag,
  794. TransportLayerProxy: v.TransportLayerProxy,
  795. }, nil
  796. }