There are several TrafficScript functions that will help you to manage binary data. Here are some points that may help:
request.getline( regex ) can be used instead; it will happily parse binary data, so if you can identify the end of your request with a regular expression, this may be suitable.
The following functions may help to parse binary strings:
You can assemble a binary string using:
You can encode non-printable bytes in a string literal using octal escapes:
$str = "\123\047\110\077";
There are also a range of functions that convert between different ASCII encodings of strings, such as hex, base64 and %-encoding, which may also be useful.
Suppose that you have a protocol in which the request looks like the following:
<2-byte msg length><msg>
You wish to add a header to the msg and update the length in a request rule:
<2-byte msg length><header><msg>
The following TrafficScript rule may suffice:
# 1. calculate the length of the entire message: $len_str = request.get( 2 ); # read the 2-byte length $len = string.bytesToInt( $len_str, 2 ); # parse it # 2. read the entire message $msg = request.get( 2 + $len ); # 3. Insert the header just after the length $msg = string.insertBytes( $msg, $header, 2 ); # 4. Update the length $len = $len + string.len( $header ); $len_str = string.intToBytes( $len ); $msg = string.replaceBytes( $msg, $len_str, 0 ); # 5. Change the request data request.set( $msg );