encoding.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. package encoding
  2. //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
  3. import (
  4. "bytes"
  5. "context"
  6. "crypto/rand"
  7. "io"
  8. "math/big"
  9. "runtime"
  10. "strconv"
  11. "syscall"
  12. "time"
  13. "github.com/xtls/xray-core/common/buf"
  14. "github.com/xtls/xray-core/common/errors"
  15. "github.com/xtls/xray-core/common/net"
  16. "github.com/xtls/xray-core/common/protocol"
  17. "github.com/xtls/xray-core/common/session"
  18. "github.com/xtls/xray-core/common/signal"
  19. "github.com/xtls/xray-core/features/stats"
  20. "github.com/xtls/xray-core/proxy/vless"
  21. "github.com/xtls/xray-core/transport/internet/reality"
  22. "github.com/xtls/xray-core/transport/internet/stat"
  23. "github.com/xtls/xray-core/transport/internet/tls"
  24. )
  25. const (
  26. Version = byte(0)
  27. )
  28. var (
  29. tls13SupportedVersions = []byte{0x00, 0x2b, 0x00, 0x02, 0x03, 0x04}
  30. tlsClientHandShakeStart = []byte{0x16, 0x03}
  31. tlsServerHandShakeStart = []byte{0x16, 0x03, 0x03}
  32. tlsApplicationDataStart = []byte{0x17, 0x03, 0x03}
  33. Tls13CipherSuiteDic = map[uint16]string{
  34. 0x1301: "TLS_AES_128_GCM_SHA256",
  35. 0x1302: "TLS_AES_256_GCM_SHA384",
  36. 0x1303: "TLS_CHACHA20_POLY1305_SHA256",
  37. 0x1304: "TLS_AES_128_CCM_SHA256",
  38. 0x1305: "TLS_AES_128_CCM_8_SHA256",
  39. }
  40. )
  41. const (
  42. tlsHandshakeTypeClientHello byte = 0x01
  43. tlsHandshakeTypeServerHello byte = 0x02
  44. CommandPaddingContinue byte = 0x00
  45. CommandPaddingEnd byte = 0x01
  46. CommandPaddingDirect byte = 0x02
  47. )
  48. var addrParser = protocol.NewAddressParser(
  49. protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv4), net.AddressFamilyIPv4),
  50. protocol.AddressFamilyByte(byte(protocol.AddressTypeDomain), net.AddressFamilyDomain),
  51. protocol.AddressFamilyByte(byte(protocol.AddressTypeIPv6), net.AddressFamilyIPv6),
  52. protocol.PortThenAddress(),
  53. )
  54. // EncodeRequestHeader writes encoded request header into the given writer.
  55. func EncodeRequestHeader(writer io.Writer, request *protocol.RequestHeader, requestAddons *Addons) error {
  56. buffer := buf.StackNew()
  57. defer buffer.Release()
  58. if err := buffer.WriteByte(request.Version); err != nil {
  59. return newError("failed to write request version").Base(err)
  60. }
  61. if _, err := buffer.Write(request.User.Account.(*vless.MemoryAccount).ID.Bytes()); err != nil {
  62. return newError("failed to write request user id").Base(err)
  63. }
  64. if err := EncodeHeaderAddons(&buffer, requestAddons); err != nil {
  65. return newError("failed to encode request header addons").Base(err)
  66. }
  67. if err := buffer.WriteByte(byte(request.Command)); err != nil {
  68. return newError("failed to write request command").Base(err)
  69. }
  70. if request.Command != protocol.RequestCommandMux {
  71. if err := addrParser.WriteAddressPort(&buffer, request.Address, request.Port); err != nil {
  72. return newError("failed to write request address and port").Base(err)
  73. }
  74. }
  75. if _, err := writer.Write(buffer.Bytes()); err != nil {
  76. return newError("failed to write request header").Base(err)
  77. }
  78. return nil
  79. }
  80. // DecodeRequestHeader decodes and returns (if successful) a RequestHeader from an input stream.
  81. func DecodeRequestHeader(isfb bool, first *buf.Buffer, reader io.Reader, validator *vless.Validator) (*protocol.RequestHeader, *Addons, bool, error) {
  82. buffer := buf.StackNew()
  83. defer buffer.Release()
  84. request := new(protocol.RequestHeader)
  85. if isfb {
  86. request.Version = first.Byte(0)
  87. } else {
  88. if _, err := buffer.ReadFullFrom(reader, 1); err != nil {
  89. return nil, nil, false, newError("failed to read request version").Base(err)
  90. }
  91. request.Version = buffer.Byte(0)
  92. }
  93. switch request.Version {
  94. case 0:
  95. var id [16]byte
  96. if isfb {
  97. copy(id[:], first.BytesRange(1, 17))
  98. } else {
  99. buffer.Clear()
  100. if _, err := buffer.ReadFullFrom(reader, 16); err != nil {
  101. return nil, nil, false, newError("failed to read request user id").Base(err)
  102. }
  103. copy(id[:], buffer.Bytes())
  104. }
  105. if request.User = validator.Get(id); request.User == nil {
  106. return nil, nil, isfb, newError("invalid request user id")
  107. }
  108. if isfb {
  109. first.Advance(17)
  110. }
  111. requestAddons, err := DecodeHeaderAddons(&buffer, reader)
  112. if err != nil {
  113. return nil, nil, false, newError("failed to decode request header addons").Base(err)
  114. }
  115. buffer.Clear()
  116. if _, err := buffer.ReadFullFrom(reader, 1); err != nil {
  117. return nil, nil, false, newError("failed to read request command").Base(err)
  118. }
  119. request.Command = protocol.RequestCommand(buffer.Byte(0))
  120. switch request.Command {
  121. case protocol.RequestCommandMux:
  122. request.Address = net.DomainAddress("v1.mux.cool")
  123. request.Port = 0
  124. case protocol.RequestCommandTCP, protocol.RequestCommandUDP:
  125. if addr, port, err := addrParser.ReadAddressPort(&buffer, reader); err == nil {
  126. request.Address = addr
  127. request.Port = port
  128. }
  129. }
  130. if request.Address == nil {
  131. return nil, nil, false, newError("invalid request address")
  132. }
  133. return request, requestAddons, false, nil
  134. default:
  135. return nil, nil, isfb, newError("invalid request version")
  136. }
  137. }
  138. // EncodeResponseHeader writes encoded response header into the given writer.
  139. func EncodeResponseHeader(writer io.Writer, request *protocol.RequestHeader, responseAddons *Addons) error {
  140. buffer := buf.StackNew()
  141. defer buffer.Release()
  142. if err := buffer.WriteByte(request.Version); err != nil {
  143. return newError("failed to write response version").Base(err)
  144. }
  145. if err := EncodeHeaderAddons(&buffer, responseAddons); err != nil {
  146. return newError("failed to encode response header addons").Base(err)
  147. }
  148. if _, err := writer.Write(buffer.Bytes()); err != nil {
  149. return newError("failed to write response header").Base(err)
  150. }
  151. return nil
  152. }
  153. // DecodeResponseHeader decodes and returns (if successful) a ResponseHeader from an input stream.
  154. func DecodeResponseHeader(reader io.Reader, request *protocol.RequestHeader) (*Addons, error) {
  155. buffer := buf.StackNew()
  156. defer buffer.Release()
  157. if _, err := buffer.ReadFullFrom(reader, 1); err != nil {
  158. return nil, newError("failed to read response version").Base(err)
  159. }
  160. if buffer.Byte(0) != request.Version {
  161. return nil, newError("unexpected response version. Expecting ", int(request.Version), " but actually ", int(buffer.Byte(0)))
  162. }
  163. responseAddons, err := DecodeHeaderAddons(&buffer, reader)
  164. if err != nil {
  165. return nil, newError("failed to decode response header addons").Base(err)
  166. }
  167. return responseAddons, nil
  168. }
  169. // XtlsRead filter and read xtls protocol
  170. func XtlsRead(reader buf.Reader, writer buf.Writer, timer signal.ActivityUpdater, conn net.Conn, rawConn syscall.RawConn,
  171. input *bytes.Reader, rawInput *bytes.Buffer,
  172. counter stats.Counter, ctx context.Context, userUUID []byte, numberOfPacketToFilter *int, enableXtls *bool,
  173. isTLS12orAbove *bool, isTLS *bool, cipher *uint16, remainingServerHello *int32,
  174. ) error {
  175. err := func() error {
  176. var ct stats.Counter
  177. withinPaddingBuffers := true
  178. shouldSwitchToDirectCopy := false
  179. var remainingContent int32 = -1
  180. var remainingPadding int32 = -1
  181. currentCommand := 0
  182. for {
  183. if shouldSwitchToDirectCopy {
  184. shouldSwitchToDirectCopy = false
  185. if inbound := session.InboundFromContext(ctx); inbound != nil && inbound.Conn != nil && (runtime.GOOS == "linux" || runtime.GOOS == "android") {
  186. if _, ok := inbound.User.Account.(*vless.MemoryAccount); inbound.User.Account == nil || ok {
  187. iConn := inbound.Conn
  188. statConn, ok := iConn.(*stat.CounterConnection)
  189. if ok {
  190. iConn = statConn.Connection
  191. }
  192. if tlsConn, ok := iConn.(*tls.Conn); ok {
  193. iConn = tlsConn.NetConn()
  194. } else if realityConn, ok := iConn.(*reality.Conn); ok {
  195. iConn = realityConn.NetConn()
  196. }
  197. if tc, ok := iConn.(*net.TCPConn); ok {
  198. newError("XtlsRead splice").WriteToLog(session.ExportIDToError(ctx))
  199. runtime.Gosched() // necessary
  200. w, err := tc.ReadFrom(conn)
  201. if counter != nil {
  202. counter.Add(w)
  203. }
  204. if statConn != nil && statConn.WriteCounter != nil {
  205. statConn.WriteCounter.Add(w)
  206. }
  207. return err
  208. }
  209. }
  210. }
  211. reader = buf.NewReadVReader(conn, rawConn, nil)
  212. ct = counter
  213. newError("XtlsRead readV").WriteToLog(session.ExportIDToError(ctx))
  214. }
  215. buffer, err := reader.ReadMultiBuffer()
  216. if !buffer.IsEmpty() {
  217. if withinPaddingBuffers || *numberOfPacketToFilter > 0 {
  218. buffer = XtlsUnpadding(ctx, buffer, userUUID, &remainingContent, &remainingPadding, &currentCommand)
  219. if remainingContent == 0 && remainingPadding == 0 {
  220. if currentCommand == 1 {
  221. withinPaddingBuffers = false
  222. remainingContent = -1
  223. remainingPadding = -1 // set to initial state to parse the next padding
  224. } else if currentCommand == 2 {
  225. withinPaddingBuffers = false
  226. shouldSwitchToDirectCopy = true
  227. // XTLS Vision processes struct TLS Conn's input and rawInput
  228. if inputBuffer, err := buf.ReadFrom(input); err == nil {
  229. if !inputBuffer.IsEmpty() {
  230. buffer, _ = buf.MergeMulti(buffer, inputBuffer)
  231. }
  232. }
  233. if rawInputBuffer, err := buf.ReadFrom(rawInput); err == nil {
  234. if !rawInputBuffer.IsEmpty() {
  235. buffer, _ = buf.MergeMulti(buffer, rawInputBuffer)
  236. }
  237. }
  238. } else if currentCommand == 0 {
  239. withinPaddingBuffers = true
  240. } else {
  241. newError("XtlsRead unknown command ", currentCommand, buffer.Len()).WriteToLog(session.ExportIDToError(ctx))
  242. }
  243. } else if remainingContent > 0 || remainingPadding > 0 {
  244. withinPaddingBuffers = true
  245. } else {
  246. withinPaddingBuffers = false
  247. }
  248. }
  249. if *numberOfPacketToFilter > 0 {
  250. XtlsFilterTls(buffer, numberOfPacketToFilter, enableXtls, isTLS12orAbove, isTLS, cipher, remainingServerHello, ctx)
  251. }
  252. if ct != nil {
  253. ct.Add(int64(buffer.Len()))
  254. }
  255. timer.Update()
  256. if werr := writer.WriteMultiBuffer(buffer); werr != nil {
  257. return werr
  258. }
  259. }
  260. if err != nil {
  261. return err
  262. }
  263. }
  264. }()
  265. if err != nil && errors.Cause(err) != io.EOF {
  266. return err
  267. }
  268. return nil
  269. }
  270. // XtlsWrite filter and write xtls protocol
  271. func XtlsWrite(reader buf.Reader, writer buf.Writer, timer signal.ActivityUpdater, conn net.Conn, counter stats.Counter,
  272. ctx context.Context, numberOfPacketToFilter *int, enableXtls *bool, isTLS12orAbove *bool, isTLS *bool,
  273. cipher *uint16, remainingServerHello *int32,
  274. ) error {
  275. err := func() error {
  276. var ct stats.Counter
  277. isPadding := true
  278. shouldSwitchToDirectCopy := false
  279. for {
  280. buffer, err := reader.ReadMultiBuffer()
  281. if !buffer.IsEmpty() {
  282. if *numberOfPacketToFilter > 0 {
  283. XtlsFilterTls(buffer, numberOfPacketToFilter, enableXtls, isTLS12orAbove, isTLS, cipher, remainingServerHello, ctx)
  284. }
  285. if isPadding {
  286. buffer = ReshapeMultiBuffer(ctx, buffer)
  287. var xtlsSpecIndex int
  288. for i, b := range buffer {
  289. if *isTLS && b.Len() >= 6 && bytes.Equal(tlsApplicationDataStart, b.BytesTo(3)) {
  290. var command byte = CommandPaddingEnd
  291. if *enableXtls {
  292. shouldSwitchToDirectCopy = true
  293. xtlsSpecIndex = i
  294. command = CommandPaddingDirect
  295. }
  296. isPadding = false
  297. buffer[i] = XtlsPadding(b, command, nil, *isTLS, ctx)
  298. break
  299. } else if !*isTLS12orAbove && *numberOfPacketToFilter <= 1 { // For compatibility with earlier vision receiver, we finish padding 1 packet early
  300. isPadding = false
  301. buffer[i] = XtlsPadding(b, CommandPaddingEnd, nil, *isTLS, ctx)
  302. break
  303. }
  304. buffer[i] = XtlsPadding(b, CommandPaddingContinue, nil, *isTLS, ctx)
  305. }
  306. if shouldSwitchToDirectCopy {
  307. encryptBuffer, directBuffer := buf.SplitMulti(buffer, xtlsSpecIndex+1)
  308. length := encryptBuffer.Len()
  309. if !encryptBuffer.IsEmpty() {
  310. timer.Update()
  311. if werr := writer.WriteMultiBuffer(encryptBuffer); werr != nil {
  312. return werr
  313. }
  314. }
  315. buffer = directBuffer
  316. writer = buf.NewWriter(conn)
  317. ct = counter
  318. newError("XtlsWrite writeV ", xtlsSpecIndex, " ", length, " ", buffer.Len()).WriteToLog(session.ExportIDToError(ctx))
  319. time.Sleep(5 * time.Millisecond) // for some device, the first xtls direct packet fails without this delay
  320. }
  321. }
  322. if !buffer.IsEmpty() {
  323. if ct != nil {
  324. ct.Add(int64(buffer.Len()))
  325. }
  326. timer.Update()
  327. if werr := writer.WriteMultiBuffer(buffer); werr != nil {
  328. return werr
  329. }
  330. }
  331. }
  332. if err != nil {
  333. return err
  334. }
  335. }
  336. }()
  337. if err != nil && errors.Cause(err) != io.EOF {
  338. return err
  339. }
  340. return nil
  341. }
  342. // XtlsFilterTls filter and recognize tls 1.3 and other info
  343. func XtlsFilterTls(buffer buf.MultiBuffer, numberOfPacketToFilter *int, enableXtls *bool, isTLS12orAbove *bool, isTLS *bool,
  344. cipher *uint16, remainingServerHello *int32, ctx context.Context,
  345. ) {
  346. for _, b := range buffer {
  347. *numberOfPacketToFilter--
  348. if b.Len() >= 6 {
  349. startsBytes := b.BytesTo(6)
  350. if bytes.Equal(tlsServerHandShakeStart, startsBytes[:3]) && startsBytes[5] == tlsHandshakeTypeServerHello {
  351. *remainingServerHello = (int32(startsBytes[3])<<8 | int32(startsBytes[4])) + 5
  352. *isTLS12orAbove = true
  353. *isTLS = true
  354. if b.Len() >= 79 && *remainingServerHello >= 79 {
  355. sessionIdLen := int32(b.Byte(43))
  356. cipherSuite := b.BytesRange(43+sessionIdLen+1, 43+sessionIdLen+3)
  357. *cipher = uint16(cipherSuite[0])<<8 | uint16(cipherSuite[1])
  358. } else {
  359. newError("XtlsFilterTls short server hello, tls 1.2 or older? ", b.Len(), " ", *remainingServerHello).WriteToLog(session.ExportIDToError(ctx))
  360. }
  361. } else if bytes.Equal(tlsClientHandShakeStart, startsBytes[:2]) && startsBytes[5] == tlsHandshakeTypeClientHello {
  362. *isTLS = true
  363. newError("XtlsFilterTls found tls client hello! ", buffer.Len()).WriteToLog(session.ExportIDToError(ctx))
  364. }
  365. }
  366. if *remainingServerHello > 0 {
  367. end := *remainingServerHello
  368. if end > b.Len() {
  369. end = b.Len()
  370. }
  371. *remainingServerHello -= b.Len()
  372. if bytes.Contains(b.BytesTo(end), tls13SupportedVersions) {
  373. v, ok := Tls13CipherSuiteDic[*cipher]
  374. if !ok {
  375. v = "Old cipher: " + strconv.FormatUint(uint64(*cipher), 16)
  376. } else if v != "TLS_AES_128_CCM_8_SHA256" {
  377. *enableXtls = true
  378. }
  379. newError("XtlsFilterTls found tls 1.3! ", b.Len(), " ", v).WriteToLog(session.ExportIDToError(ctx))
  380. *numberOfPacketToFilter = 0
  381. return
  382. } else if *remainingServerHello <= 0 {
  383. newError("XtlsFilterTls found tls 1.2! ", b.Len()).WriteToLog(session.ExportIDToError(ctx))
  384. *numberOfPacketToFilter = 0
  385. return
  386. }
  387. newError("XtlsFilterTls inconclusive server hello ", b.Len(), " ", *remainingServerHello).WriteToLog(session.ExportIDToError(ctx))
  388. }
  389. if *numberOfPacketToFilter <= 0 {
  390. newError("XtlsFilterTls stop filtering", buffer.Len()).WriteToLog(session.ExportIDToError(ctx))
  391. }
  392. }
  393. }
  394. // ReshapeMultiBuffer prepare multi buffer for padding stucture (max 21 bytes)
  395. func ReshapeMultiBuffer(ctx context.Context, buffer buf.MultiBuffer) buf.MultiBuffer {
  396. needReshape := 0
  397. for _, b := range buffer {
  398. if b.Len() >= buf.Size-21 {
  399. needReshape += 1
  400. }
  401. }
  402. if needReshape == 0 {
  403. return buffer
  404. }
  405. mb2 := make(buf.MultiBuffer, 0, len(buffer)+needReshape)
  406. toPrint := ""
  407. for i, buffer1 := range buffer {
  408. if buffer1.Len() >= buf.Size-21 {
  409. index := int32(bytes.LastIndex(buffer1.Bytes(), tlsApplicationDataStart))
  410. if index <= 0 || index > buf.Size-21 {
  411. index = buf.Size / 2
  412. }
  413. buffer2 := buf.New()
  414. buffer2.Write(buffer1.BytesFrom(index))
  415. buffer1.Resize(0, index)
  416. mb2 = append(mb2, buffer1, buffer2)
  417. toPrint += " " + strconv.Itoa(int(buffer1.Len())) + " " + strconv.Itoa(int(buffer2.Len()))
  418. } else {
  419. mb2 = append(mb2, buffer1)
  420. toPrint += " " + strconv.Itoa(int(buffer1.Len()))
  421. }
  422. buffer[i] = nil
  423. }
  424. buffer = buffer[:0]
  425. newError("ReshapeMultiBuffer ", toPrint).WriteToLog(session.ExportIDToError(ctx))
  426. return mb2
  427. }
  428. // XtlsPadding add padding to eliminate length siganature during tls handshake
  429. func XtlsPadding(b *buf.Buffer, command byte, userUUID *[]byte, longPadding bool, ctx context.Context) *buf.Buffer {
  430. var contentLen int32 = 0
  431. var paddingLen int32 = 0
  432. if b != nil {
  433. contentLen = b.Len()
  434. }
  435. if contentLen < 900 && longPadding {
  436. l, err := rand.Int(rand.Reader, big.NewInt(500))
  437. if err != nil {
  438. newError("failed to generate padding").Base(err).WriteToLog(session.ExportIDToError(ctx))
  439. }
  440. paddingLen = int32(l.Int64()) + 900 - contentLen
  441. } else {
  442. l, err := rand.Int(rand.Reader, big.NewInt(256))
  443. if err != nil {
  444. newError("failed to generate padding").Base(err).WriteToLog(session.ExportIDToError(ctx))
  445. }
  446. paddingLen = int32(l.Int64())
  447. }
  448. if paddingLen > buf.Size-21-contentLen {
  449. paddingLen = buf.Size - 21 - contentLen
  450. }
  451. newbuffer := buf.New()
  452. if userUUID != nil {
  453. newbuffer.Write(*userUUID)
  454. *userUUID = nil
  455. }
  456. newbuffer.Write([]byte{command, byte(contentLen >> 8), byte(contentLen), byte(paddingLen >> 8), byte(paddingLen)})
  457. if b != nil {
  458. newbuffer.Write(b.Bytes())
  459. b.Release()
  460. b = nil
  461. }
  462. newbuffer.Extend(paddingLen)
  463. newError("XtlsPadding ", contentLen, " ", paddingLen, " ", command).WriteToLog(session.ExportIDToError(ctx))
  464. return newbuffer
  465. }
  466. // XtlsUnpadding remove padding and parse command
  467. func XtlsUnpadding(ctx context.Context, buffer buf.MultiBuffer, userUUID []byte, remainingContent *int32, remainingPadding *int32, currentCommand *int) buf.MultiBuffer {
  468. posindex := 0
  469. var posByte int32 = 0
  470. if *remainingContent == -1 && *remainingPadding == -1 {
  471. for i, b := range buffer {
  472. if b.Len() >= 21 && bytes.Equal(userUUID, b.BytesTo(16)) {
  473. posindex = i
  474. posByte = 16
  475. *remainingContent = 0
  476. *remainingPadding = 0
  477. *currentCommand = 0
  478. break
  479. }
  480. }
  481. }
  482. if *remainingContent == -1 && *remainingPadding == -1 {
  483. return buffer
  484. }
  485. mb2 := make(buf.MultiBuffer, 0, len(buffer))
  486. for i := 0; i < posindex; i++ {
  487. newbuffer := buf.New()
  488. newbuffer.Write(buffer[i].Bytes())
  489. mb2 = append(mb2, newbuffer)
  490. }
  491. for i := posindex; i < len(buffer); i++ {
  492. b := buffer[i]
  493. for posByte < b.Len() {
  494. if *remainingContent <= 0 && *remainingPadding <= 0 {
  495. if *currentCommand == 1 { // possible buffer after padding, no need to worry about xtls (command 2)
  496. len := b.Len() - posByte
  497. newbuffer := buf.New()
  498. newbuffer.Write(b.BytesRange(posByte, posByte+len))
  499. mb2 = append(mb2, newbuffer)
  500. posByte += len
  501. } else {
  502. paddingInfo := b.BytesRange(posByte, posByte+5)
  503. *currentCommand = int(paddingInfo[0])
  504. *remainingContent = int32(paddingInfo[1])<<8 | int32(paddingInfo[2])
  505. *remainingPadding = int32(paddingInfo[3])<<8 | int32(paddingInfo[4])
  506. newError("Xtls Unpadding new block", i, " ", posByte, " content ", *remainingContent, " padding ", *remainingPadding, " ", paddingInfo[0]).WriteToLog(session.ExportIDToError(ctx))
  507. posByte += 5
  508. }
  509. } else if *remainingContent > 0 {
  510. len := *remainingContent
  511. if b.Len() < posByte+*remainingContent {
  512. len = b.Len() - posByte
  513. }
  514. newbuffer := buf.New()
  515. newbuffer.Write(b.BytesRange(posByte, posByte+len))
  516. mb2 = append(mb2, newbuffer)
  517. *remainingContent -= len
  518. posByte += len
  519. } else { // remainingPadding > 0
  520. len := *remainingPadding
  521. if b.Len() < posByte+*remainingPadding {
  522. len = b.Len() - posByte
  523. }
  524. *remainingPadding -= len
  525. posByte += len
  526. }
  527. if posByte == b.Len() {
  528. posByte = 0
  529. break
  530. }
  531. }
  532. }
  533. buf.ReleaseMulti(buffer)
  534. return mb2
  535. }