encoding.go 19 KB

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