StreamDataToDatagramChunk converts UDP payload data to a CONNECT-UDP datagram chunk. This protocol is for tunneling a UDP stream via an HTTP proxy server. IETF draft: https://datatracker.ietf.org/doc/html/draft-ietf-masque-connect-udp-03 CONNECT-UDP datagram chunk is encoded in the format of T-L-V:
(payload []byte, l int)
| 393 | // |payload| is the UDP packet payload; |l| is the payload length. |
| 394 | // It returns the encoded chunk in a byte slice and its total length. |
| 395 | func StreamDataToDatagramChunk(payload []byte, l int) ([]byte, int) { |
| 396 | encode := make([]byte, 5) |
| 397 | encode[0] = 0x00 |
| 398 | dataLength := uint(l) |
| 399 | if dataLength > 63 { |
| 400 | if dataLength > 16383 { |
| 401 | encode[1] = 0x80 | uint8(dataLength>>24) // 4-byte length encoding |
| 402 | encode[2] = uint8(dataLength >> 16) |
| 403 | encode[3] = uint8(dataLength >> 8) |
| 404 | encode[4] = uint8(dataLength) |
| 405 | encode = append(encode[:4:4], payload...) |
| 406 | return encode, l + 5 |
| 407 | } |
| 408 | encode[1] = 0x40 | uint8(dataLength>>8) // 2-byte length encoding |
| 409 | encode[2] = uint8(dataLength) |
| 410 | encode = append(encode[:3:3], payload...) |
| 411 | return encode, l + 3 |
| 412 | } |
| 413 | encode[1] = uint8(dataLength) // 1-byte length encoding |
| 414 | encode = append(encode[:2:2], payload...) |
| 415 | return encode, l + 2 |
| 416 | } |
| 417 | |
| 418 | // datagramChunkToStreamData converts an encoded datagram chunk into a UDP raw byte slice. |
| 419 | // The input parameters are the CONNECT-UDP datagram chunk (chunk) and the payload length (len). |