config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. package splithttp
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. "github.com/xtls/xray-core/common"
  9. "github.com/xtls/xray-core/common/buf"
  10. "github.com/xtls/xray-core/common/crypto"
  11. "github.com/xtls/xray-core/common/utils"
  12. "github.com/xtls/xray-core/transport/internet"
  13. )
  14. func (c *Config) GetNormalizedPath() string {
  15. pathAndQuery := strings.SplitN(c.Path, "?", 2)
  16. path := pathAndQuery[0]
  17. if path == "" || path[0] != '/' {
  18. path = "/" + path
  19. }
  20. if path[len(path)-1] != '/' {
  21. path = path + "/"
  22. }
  23. return path
  24. }
  25. func (c *Config) GetNormalizedQuery() string {
  26. pathAndQuery := strings.SplitN(c.Path, "?", 2)
  27. query := ""
  28. if len(pathAndQuery) > 1 {
  29. query = pathAndQuery[1]
  30. }
  31. /*
  32. if query != "" {
  33. query += "&"
  34. }
  35. query += "x_version=" + core.Version()
  36. */
  37. return query
  38. }
  39. func (c *Config) GetRequestHeader() http.Header {
  40. header := http.Header{}
  41. for k, v := range c.Headers {
  42. header.Add(k, v)
  43. }
  44. utils.TryDefaultHeadersWith(header, "fetch")
  45. return header
  46. }
  47. func (c *Config) GetRequestHeaderWithPayload(payload []byte) http.Header {
  48. header := c.GetRequestHeader()
  49. key := c.UplinkDataKey
  50. encodedData := base64.RawURLEncoding.EncodeToString(payload)
  51. for i := 0; len(encodedData) > 0; i++ {
  52. chunkSize := min(int(c.GetNormalizedUplinkChunkSize().rand()), len(encodedData))
  53. chunk := encodedData[:chunkSize]
  54. encodedData = encodedData[chunkSize:]
  55. headerKey := fmt.Sprintf("%s-%d", key, i)
  56. header.Set(headerKey, chunk)
  57. }
  58. return header
  59. }
  60. func (c *Config) GetRequestCookiesWithPayload(payload []byte) []*http.Cookie {
  61. cookies := []*http.Cookie{}
  62. key := c.UplinkDataKey
  63. encodedData := base64.RawURLEncoding.EncodeToString(payload)
  64. for i := 0; len(encodedData) > 0; i++ {
  65. chunkSize := min(int(c.GetNormalizedUplinkChunkSize().rand()), len(encodedData))
  66. chunk := encodedData[:chunkSize]
  67. encodedData = encodedData[chunkSize:]
  68. cookieName := fmt.Sprintf("%s_%d", key, i)
  69. cookies = append(cookies, &http.Cookie{Name: cookieName, Value: chunk})
  70. }
  71. return cookies
  72. }
  73. func (c *Config) WriteResponseHeader(writer http.ResponseWriter, requestMethod string, requestHeader http.Header) {
  74. // CORS headers for the browser dialer
  75. if origin := requestHeader.Get("Origin"); origin == "" {
  76. writer.Header().Set("Access-Control-Allow-Origin", "*")
  77. } else {
  78. // Chrome says: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
  79. writer.Header().Set("Access-Control-Allow-Origin", origin)
  80. }
  81. if c.GetNormalizedSessionPlacement() == PlacementCookie ||
  82. c.GetNormalizedSeqPlacement() == PlacementCookie ||
  83. c.XPaddingPlacement == PlacementCookie ||
  84. c.GetNormalizedUplinkDataPlacement() == PlacementCookie {
  85. writer.Header().Set("Access-Control-Allow-Credentials", "true")
  86. }
  87. if requestMethod == "OPTIONS" {
  88. requestedMethod := requestHeader.Get("Access-Control-Request-Method")
  89. if requestedMethod != "" {
  90. writer.Header().Set("Access-Control-Allow-Methods", requestedMethod)
  91. } else {
  92. writer.Header().Set("Access-Control-Allow-Methods", "*")
  93. }
  94. requestedHeaders := requestHeader.Get("Access-Control-Request-Headers")
  95. if requestedHeaders == "" {
  96. writer.Header().Set("Access-Control-Allow-Headers", "*")
  97. } else {
  98. writer.Header().Set("Access-Control-Allow-Headers", requestedHeaders)
  99. }
  100. }
  101. }
  102. func (c *Config) GetNormalizedUplinkHTTPMethod() string {
  103. if c.UplinkHTTPMethod == "" {
  104. return "POST"
  105. }
  106. return c.UplinkHTTPMethod
  107. }
  108. func (c *Config) GetNormalizedScMaxEachPostBytes() RangeConfig {
  109. if c.ScMaxEachPostBytes == nil || c.ScMaxEachPostBytes.To == 0 {
  110. return RangeConfig{
  111. From: 1000000,
  112. To: 1000000,
  113. }
  114. }
  115. return *c.ScMaxEachPostBytes
  116. }
  117. func (c *Config) GetNormalizedScMinPostsIntervalMs() RangeConfig {
  118. if c.ScMinPostsIntervalMs == nil || c.ScMinPostsIntervalMs.To == 0 {
  119. return RangeConfig{
  120. From: 30,
  121. To: 30,
  122. }
  123. }
  124. return *c.ScMinPostsIntervalMs
  125. }
  126. func (c *Config) GetNormalizedScMaxBufferedPosts() int {
  127. if c.ScMaxBufferedPosts == 0 {
  128. return 30
  129. }
  130. return int(c.ScMaxBufferedPosts)
  131. }
  132. func (c *Config) GetNormalizedScStreamUpServerSecs() RangeConfig {
  133. if c.ScStreamUpServerSecs == nil || c.ScStreamUpServerSecs.To == 0 {
  134. return RangeConfig{
  135. From: 20,
  136. To: 80,
  137. }
  138. }
  139. return *c.ScStreamUpServerSecs
  140. }
  141. func (c *Config) GetNormalizedUplinkChunkSize() RangeConfig {
  142. if c.UplinkChunkSize == nil || c.UplinkChunkSize.To == 0 {
  143. switch c.UplinkDataPlacement {
  144. case PlacementCookie:
  145. return RangeConfig{
  146. From: 2 * 1024, // 2 KiB
  147. To: 3 * 1024, // 3 KiB
  148. }
  149. case PlacementHeader:
  150. return RangeConfig{
  151. From: 3 * 1000, // 3 KB
  152. To: 4 * 1000, // 4 KB
  153. }
  154. default:
  155. return c.GetNormalizedScMaxEachPostBytes()
  156. }
  157. } else if c.UplinkChunkSize.From < 64 {
  158. return RangeConfig{
  159. From: 64,
  160. To: max(64, c.UplinkChunkSize.To),
  161. }
  162. }
  163. return *c.UplinkChunkSize
  164. }
  165. func (c *Config) GetNormalizedServerMaxHeaderBytes() int {
  166. if c.ServerMaxHeaderBytes <= 0 {
  167. return 8192
  168. } else {
  169. return int(c.ServerMaxHeaderBytes)
  170. }
  171. }
  172. func (c *Config) GetNormalizedSessionPlacement() string {
  173. if c.SessionPlacement == "" {
  174. return PlacementPath
  175. }
  176. return c.SessionPlacement
  177. }
  178. func (c *Config) GetNormalizedSeqPlacement() string {
  179. if c.SeqPlacement == "" {
  180. return PlacementPath
  181. }
  182. return c.SeqPlacement
  183. }
  184. func (c *Config) GetNormalizedUplinkDataPlacement() string {
  185. if c.UplinkDataPlacement == "" {
  186. return PlacementBody
  187. }
  188. return c.UplinkDataPlacement
  189. }
  190. func (c *Config) GetNormalizedSessionKey() string {
  191. if c.SessionKey != "" {
  192. return c.SessionKey
  193. }
  194. switch c.GetNormalizedSessionPlacement() {
  195. case PlacementHeader:
  196. return "X-Session"
  197. case PlacementCookie, PlacementQuery:
  198. return "x_session"
  199. default:
  200. return ""
  201. }
  202. }
  203. func (c *Config) GetNormalizedSeqKey() string {
  204. if c.SeqKey != "" {
  205. return c.SeqKey
  206. }
  207. switch c.GetNormalizedSeqPlacement() {
  208. case PlacementHeader:
  209. return "X-Seq"
  210. case PlacementCookie, PlacementQuery:
  211. return "x_seq"
  212. default:
  213. return ""
  214. }
  215. }
  216. func (c *Config) ApplyMetaToRequest(req *http.Request, sessionId string, seqStr string) {
  217. sessionPlacement := c.GetNormalizedSessionPlacement()
  218. seqPlacement := c.GetNormalizedSeqPlacement()
  219. sessionKey := c.GetNormalizedSessionKey()
  220. seqKey := c.GetNormalizedSeqKey()
  221. if sessionId != "" {
  222. switch sessionPlacement {
  223. case PlacementPath:
  224. req.URL.Path = appendToPath(req.URL.Path, sessionId)
  225. case PlacementQuery:
  226. q := req.URL.Query()
  227. q.Set(sessionKey, sessionId)
  228. req.URL.RawQuery = q.Encode()
  229. case PlacementHeader:
  230. req.Header.Set(sessionKey, sessionId)
  231. case PlacementCookie:
  232. req.AddCookie(&http.Cookie{Name: sessionKey, Value: sessionId})
  233. }
  234. }
  235. if seqStr != "" {
  236. switch seqPlacement {
  237. case PlacementPath:
  238. req.URL.Path = appendToPath(req.URL.Path, seqStr)
  239. case PlacementQuery:
  240. q := req.URL.Query()
  241. q.Set(seqKey, seqStr)
  242. req.URL.RawQuery = q.Encode()
  243. case PlacementHeader:
  244. req.Header.Set(seqKey, seqStr)
  245. case PlacementCookie:
  246. req.AddCookie(&http.Cookie{Name: seqKey, Value: seqStr})
  247. }
  248. }
  249. }
  250. func (c *Config) FillStreamRequest(request *http.Request, sessionId string, seqStr string) {
  251. request.Header = c.GetRequestHeader()
  252. length := int(c.GetNormalizedXPaddingBytes().rand())
  253. config := XPaddingConfig{Length: length}
  254. if c.XPaddingObfsMode {
  255. config.Placement = XPaddingPlacement{
  256. Placement: c.XPaddingPlacement,
  257. Key: c.XPaddingKey,
  258. Header: c.XPaddingHeader,
  259. RawURL: request.URL.String(),
  260. }
  261. config.Method = PaddingMethod(c.XPaddingMethod)
  262. } else {
  263. config.Placement = XPaddingPlacement{
  264. Placement: PlacementQueryInHeader,
  265. Key: "x_padding",
  266. Header: "Referer",
  267. RawURL: request.URL.String(),
  268. }
  269. }
  270. c.ApplyXPaddingToRequest(request, config)
  271. c.ApplyMetaToRequest(request, sessionId, "")
  272. if request.Body != nil && !c.NoGRPCHeader { // stream-up/one
  273. request.Header.Set("Content-Type", "application/grpc")
  274. }
  275. }
  276. func (c *Config) FillPacketRequest(request *http.Request, sessionId string, seqStr string, payload buf.MultiBuffer) error {
  277. dataPlacement := c.GetNormalizedUplinkDataPlacement()
  278. if dataPlacement == PlacementBody || dataPlacement == PlacementAuto {
  279. request.Header = c.GetRequestHeader()
  280. request.Body = io.NopCloser(&buf.MultiBufferContainer{MultiBuffer: payload})
  281. request.ContentLength = int64(payload.Len())
  282. } else {
  283. data := make([]byte, payload.Len())
  284. payload.Copy(data)
  285. buf.ReleaseMulti(payload)
  286. switch dataPlacement {
  287. case PlacementHeader:
  288. request.Header = c.GetRequestHeaderWithPayload(data)
  289. case PlacementCookie:
  290. request.Header = c.GetRequestHeader()
  291. for _, cookie := range c.GetRequestCookiesWithPayload(data) {
  292. request.AddCookie(cookie)
  293. }
  294. }
  295. }
  296. length := int(c.GetNormalizedXPaddingBytes().rand())
  297. config := XPaddingConfig{Length: length}
  298. if c.XPaddingObfsMode {
  299. config.Placement = XPaddingPlacement{
  300. Placement: c.XPaddingPlacement,
  301. Key: c.XPaddingKey,
  302. Header: c.XPaddingHeader,
  303. RawURL: request.URL.String(),
  304. }
  305. config.Method = PaddingMethod(c.XPaddingMethod)
  306. } else {
  307. config.Placement = XPaddingPlacement{
  308. Placement: PlacementQueryInHeader,
  309. Key: "x_padding",
  310. Header: "Referer",
  311. RawURL: request.URL.String(),
  312. }
  313. }
  314. c.ApplyXPaddingToRequest(request, config)
  315. c.ApplyMetaToRequest(request, sessionId, seqStr)
  316. return nil
  317. }
  318. func (c *Config) ExtractMetaFromRequest(req *http.Request, path string) (sessionId string, seqStr string) {
  319. sessionPlacement := c.GetNormalizedSessionPlacement()
  320. seqPlacement := c.GetNormalizedSeqPlacement()
  321. sessionKey := c.GetNormalizedSessionKey()
  322. seqKey := c.GetNormalizedSeqKey()
  323. var subpath []string
  324. pathPart := 0
  325. if sessionPlacement == PlacementPath || seqPlacement == PlacementPath {
  326. subpath = strings.Split(req.URL.Path[len(path):], "/")
  327. }
  328. switch sessionPlacement {
  329. case PlacementPath:
  330. if len(subpath) > pathPart {
  331. sessionId = subpath[pathPart]
  332. pathPart += 1
  333. }
  334. case PlacementQuery:
  335. sessionId = req.URL.Query().Get(sessionKey)
  336. case PlacementHeader:
  337. sessionId = req.Header.Get(sessionKey)
  338. case PlacementCookie:
  339. if cookie, e := req.Cookie(sessionKey); e == nil {
  340. sessionId = cookie.Value
  341. }
  342. }
  343. switch seqPlacement {
  344. case PlacementPath:
  345. if len(subpath) > pathPart {
  346. seqStr = subpath[pathPart]
  347. pathPart += 1
  348. }
  349. case PlacementQuery:
  350. seqStr = req.URL.Query().Get(seqKey)
  351. case PlacementHeader:
  352. seqStr = req.Header.Get(seqKey)
  353. case PlacementCookie:
  354. if cookie, e := req.Cookie(seqKey); e == nil {
  355. seqStr = cookie.Value
  356. }
  357. }
  358. return sessionId, seqStr
  359. }
  360. func (m *XmuxConfig) GetNormalizedMaxConcurrency() RangeConfig {
  361. if m.MaxConcurrency == nil {
  362. return RangeConfig{
  363. From: 0,
  364. To: 0,
  365. }
  366. }
  367. return *m.MaxConcurrency
  368. }
  369. func (m *XmuxConfig) GetNormalizedMaxConnections() RangeConfig {
  370. if m.MaxConnections == nil {
  371. return RangeConfig{
  372. From: 0,
  373. To: 0,
  374. }
  375. }
  376. return *m.MaxConnections
  377. }
  378. func (m *XmuxConfig) GetNormalizedCMaxReuseTimes() RangeConfig {
  379. if m.CMaxReuseTimes == nil {
  380. return RangeConfig{
  381. From: 0,
  382. To: 0,
  383. }
  384. }
  385. return *m.CMaxReuseTimes
  386. }
  387. func (m *XmuxConfig) GetNormalizedHMaxRequestTimes() RangeConfig {
  388. if m.HMaxRequestTimes == nil {
  389. return RangeConfig{
  390. From: 0,
  391. To: 0,
  392. }
  393. }
  394. return *m.HMaxRequestTimes
  395. }
  396. func (m *XmuxConfig) GetNormalizedHMaxReusableSecs() RangeConfig {
  397. if m.HMaxReusableSecs == nil {
  398. return RangeConfig{
  399. From: 0,
  400. To: 0,
  401. }
  402. }
  403. return *m.HMaxReusableSecs
  404. }
  405. func init() {
  406. common.Must(internet.RegisterProtocolConfigCreator(protocolName, func() interface{} {
  407. return new(Config)
  408. }))
  409. }
  410. func (c RangeConfig) rand() int32 {
  411. return int32(crypto.RandBetween(int64(c.From), int64(c.To)))
  412. }
  413. func appendToPath(path, value string) string {
  414. if strings.HasSuffix(path, "/") {
  415. return path + value
  416. }
  417. return path + "/" + value
  418. }