Function Reference

TrafficScript Core Functions

TrafficScript core functions provide the basic function set for the TrafficScript language, including support for the core TrafficScript types, mathematical functions, and date and time manipulation.

The core functions are grouped into several families:

array.: These functions facilitate the use and manipulation of arrays within TrafficScript.

hash.: These functions facilitate the use and manipulation of hashes (or key/value pairs) within TrafficScript.

json.: These functions provide the ability to convert between TrafficScript arrays/hash variables and JavaScript Object Notation (JSON) strings.

lang.: These functions deal with language-specific tasks like forced type conversions.

math.: These functions provide mathematical operations.

string.: These functions operate on strings and other sequences of data.

string.gmtime.: These functions are used to format time values.

sys.: These functions return operating-system related parameters, such as the hostname.

sys.(gmtime./.localtime./.time.): These functions are used to format time values.

TrafficScript function names are not case sensitive. Therefore, the function lang.todouble() can be invoked using lang.toDouble(), Lang.ToDouble(), and lang.todouble().

Many functions take parameters and return values with specific types. TrafficScript casts variables and values to the appropriate type as described in Type Casts in TrafficScript.

array.append( array1, array2 )

Appends each element of array2 to the end of array1. Note that this behaviour is different to that of array.push(), which would add one new element to the end of array1 containing array2. The return value of this function can be used as the argument to another function to perform multiple operations on the same array.

Sample Usage

# Append 4, 5 and 6 to the array

$numbers = [ 1, 2, 3 ];

array.append( $numbers, [ 4, 5, 6 ] );

 

# $numbers is now [ 1, 2, 3, 4, 5, 6 ]

See also: array.push( array, value )

array.contains( array, value )

Returns whether or not the supplied array contains the specified value as an element. Note that it will not match elements inside sub-arrays.

Sample Usage

$array = [ "one", "two", [ "three", "four" ] ];

 

# true

array.contains( $array, "one" );

 

# false

array.contains( $array, "three" );

See also: array.filter( array, pattern, [flags] )

array.copy( array )

Returns a copy of the supplied array. This is semantically equivalent to `$arraycopy = $array`, however it will warn if the variable passed to it is not an array.

Sample Usage

# Loop around a sorted version of an array without

# permanently sorting it

$arr = [ "London", "Berlin", "Lisbon", "Paris" ];

foreach( $val in array.sort( array.copy( $arr ) )) {

log.info( $val );

}

 

# $arr will be unsorted here

See also: array.create( size, [default] )

array.create( size, [default] )

Creates a new array of the specified size and optionally fills the array with the default data.

Sample Usage

# Create an array of length 20 with all the elements

# set to zero.

$zeroarray = array.create( 20, 0 );

See also: array.resize( array, size, [default] ), array.copy( array )

array.filter( array, pattern, [flags] )

Removes elements from the supplied array that do not match the pattern. The optional 'flags' parameter contains a string of single-letter options. The following options are supported:

'i', meaning 'case insensitive' - letters in the pattern match both upper and lower case letters.

'!', meaning negate - elements of the array that match the regular expression are removed.

The return value of this function can be used as the argument to another function to perform multiple operations on the same array.

Sample Usage

# Get the extension headers for this request

$headers = http.listHeaderNames();

$extensions = array.filter( $headers, "^X-", "i" );

array.join( array, [separator] )

Concatenates all the elements of the supplied array into a string separated by the separator. The elements will be separated by a space if no separator is supplied. Note that a warning will be printed should the supplied array itself contain any arrays or hashes.

Sample Usage

# Print a comma-separated list of names

$names = [ "alice", "bob", "mallory" ];

log.info( array.join( $names, ", " ) );

See also: string.split( string, [separator] )

array.length( array )

Returns the length of the supplied array

Sample Usage

# See how many HTTP headers there are

$headers = http.listHeaderNames();

log.info( "There are "

. array.length( $headers )

. " headers in this request" );

array.pop( array )

Removes the last element of the supplied array and returns it as the result of the function.

Sample Usage

$stack = [];

array.push( $stack, 3 );

array.push( $stack, 2 );

array.push( $stack, 1 );

# $stack is now [ 3, 2, 1 ];

 

# Prints 1 2 3

while( array.length( $stack ) > 0 ) {

log.info( array.pop( $stack ) );

}

See also: array.unshift( array, value ), array.push( array, value ), array.shift( array )

array.push( array, value )

Adds the supplied value to the end of the supplied array. The return value of this function can be used as the argument to another function to perform multiple operations on the same array.

Sample Usage

# Append 4 to the array

$numbers = [ 1, 2, 3 ];

array.push( $numbers, 4 );

See also: array.shift( array ), array.unshift( array, value ), array.pop( array )

array.resize( array, size, [default] )

Resizes the supplied array to the specified size. If the size of the array is being increased and the default parameter is specified then the new elements added to the array will be set to the default parameter. If the new size is smaller than the original size then the appropriate number of elements will be removed from the end of the array. The return value of this function can be used as the argument to another function to perform multiple operations on the same array.

Sample Usage

# We're only interested in the first

# 10 lines of body data - but fill in the

# rest with blank lines if there are fewer

# than 10 lines.

$body = array.resize( http.getBodyLines(), 10, "" );

See also: array.create( size, [default] )

array.reverse( array )

Reverses the elements of the supplied array. The return value of this function can be used as the argument to another function to perform multiple operations on the same array.

Sample Usage

$array = [ 1, 2, 3, [ 4, 5 ] ];

 

# array will be [ [ 4, 5 ], 3, 2, 1 ]

array.reverse( $array );

See also: array.sort( array, [reverse] )

array.shift( array )

Removes the first element of the supplied array and returns it as the result of the function.

Sample Usage

$array = [ 1, 2, 3, 4 ];

# Empty an array from the front while printing

# its contents

while( array.length( $array ) > 0 ) {

log.info( array.shift( $array ) );

}

See also: array.unshift( array, value ), array.push( array, value ), array.pop( array )

array.sort( array, [reverse] )

Sorts the supplied array alphanumerically. If the optional reverse parameter is true, then the array will be sorted in reverse. The return value of this function can be used as the argument to another function to perform multiple operations on the same array.

Sample Usage

# Sort the keys of a hash before iterating over them

foreach( $key in array.sort( hash.keys( $hash ) ) ) {

log.info( $key . " maps to " . $hash[$keys] );

}

 

# Sort these numbers alphanumerically

$sorted = array.sort( [ 1, 2, 3, 4, 10, 11 ] );

 

# The result will be [ 1, 10, 11, 2, 3, 4 ]

 

# Reverse sort these numbers alphanumerically

$rev = array.sort( [ 1, 2, 3, 4, 10, 11 ], true );

 

# The result will be [ 4, 3, 2, 11, 10, 1 ]

See also: array.sortNumerical( array, [reverse] )

array.sortNumerical( array, [reverse] )

Sort the supplied array numerically in ascending order. If the optional reverse parameter is true, then the array will be sorted in descending order. The return value of this function can be used as the argument to another function to perform multiple operations on the same array.

Sample Usage

# Sort an array of numbers

$numbers = [ 2, 10, "3", "4", 24, "11" ];

array.sortNumerical( $numbers );

 

# $numbers is now [ 2, "3", "4", 10, "11", 24 ]

 

# Reverse sort an array of numbers

array.sortNumerical( $numbers, true );

 

# $numbers is now [ 24, "11", 10, "4", "3", 2 ]

See also: array.sort( array, [reverse] )

array.splice( array, offset, length, [values] )

Replace elements in the supplied array. Any elements between offset and length will be removed from the array and any extra values specified after the length parameter will be inserted into the array at that location. The return value of this function can be used as the argument to another function to perform multiple operations on the same array.

Sample Usage

$numbers = [ 0, 1, 2, 3, 4, 5 ];

 

# Starting from element 2, remove one element

# and insert "a" and "b" into the array

array.splice( $numbers, 2, 1, "a", "b" );

 

# $numbers is now [ 0, 1, "a", "b", 3, 4, 5 ]

 

# Starting at element 0, remove 3 elements

array.splice( $numbers, 0, 3 );

 

# $numbers is now [ "b", 3, 4, 5 ]

See also: array.filter( array, pattern, [flags] )

array.unshift( array, value )

Adds the supplied value to the front of the supplied array. The return value of this function can be used as the argument to another function to perform multiple operations on the same array.

Sample Usage

# Prepend 1 to the array

$numbers = [ 2, 3, 4 ];

array.unshift( $numbers, 1 );

See also: array.shift( array ), array.push( array, value ), array.pop( array )

hash.contains( hash, key )

Returns whether the supplied hash contains a particular key.

Sample Usage

# See if bob is in the hash of users

# and if so, whether his password matches

if( hash.contains( $users, "bob" ) ) {

if( $users["bob"] == $password ) {

# Access granted

} else {

# Access denied

}

} else {

# User does not exist

}

See also: hash.keys( hash )

hash.count( hash )

Returns the number of items in the hash.

Sample Usage

# See how many HTTP headers there are

$headers = http.getHeaders();

log.info( "There are "

. hash.count( $headers )

. " headers in this request" );

hash.delete( hash, key )

Deletes the specified key from the hash. The return value of this function can be used as the argument to another function to perform multiple operations on the same hash.

Sample Usage

$hash = [ "orange" => "fruit",

"apple" => "fruit",

"cabbage" => "vegetable",

"pear" => "fruit" ];

 

hash.delete( $hash, "cabbage" );

 

# keys will be orange, apple and pear

$keys = hash.keys( $hash );

See also: hash.keys( hash )

hash.empty( hash )

Removes all the values from the hash. The return value of this function can be used as the argument to another function to perform multiple operations on the same hash.

Sample Usage

# Empty the contents of a hypothetical set object

sub set.empty( $set ) {

# You cannot do '$set = [];' here because that

# would be reassigning the input variable

hash.empty( $set );

}

 

set.empty( $my_set );

See also: hash.keys( hash )

hash.keys( hash )

Returns an array containing the keys that map to values in the supplied hash data structure.

Sample Usage

# Get the set of IPs that have connected to the site

$ips = data.get( "connected_ips" );

$ips[request.getRemoteIP()] = 1;

data.set( "connected_ips", $ips );

$connected_set = hash.keys( $ips );

log.info( array.length( $connected_set ) .

" unique IPs have connected to the site" );

See also: hash.values( hash )

hash.values( hash )

Returns an array containing the values that have been mapped to in the hash.

Sample Usage

# Add up the values of a hash

$values = hash.values( $hash );

$total = 0;

foreach( $val in $values ) {

$total += $val;

}

log.info( "The total is " . $total );

See also: hash.keys( hash )

json.deserialize( json_string )

Converts the supplied string in JavaScript Object Notation (JSON) into a TrafficScript array or hash variable. If the supplied string is not in the correct format then a warning will be printed and the result will be empty.

Sample Usage

# Deserialising a JSON array

$json_array = '[ "element 1", "element 2" ]';

$array = json.deserialize( $json_array );

 

# Deserialising a JSON hash

$json_object = '{ "key 1":"value 1", \

"key 2":[ "array element" ] }';

$hash = json.deserialize( $json_object );

See also: json.serialize( object )

json.serialize( object )

Converts the supplied array or hash variable into JavaScript Object Notation (JSON). This format is commonly used to exchange data between online applications.

Sample Usage

# Serialising an array

$array = [ "element 1", "element 2" ];

$json_array = json.serialize( $array );

 

# Serialising a hash

$hash = [ "key 1" => "value 1",

"key 2" => [ "array element" ] ];

$json_object = json.serialize( $hash );

See also: json.deserialize( json_string )

lang.assert( condition, message )

If the condition is false, prints a warning to the log with the current line number and terminates the rule. If the condition is true then no messages will be printed and the rule will continue as normal.

Sample Usage

# Make sure that this rule is only run with

# Virtual Servers that are using SSL Decryption.

lang.assert( ssl.isSSL(),

"This rule should only be used \

with decrypted SSL connections" );

See also: lang.warn( message )

lang.chr( number )

Converts a number to the corresponding ASCII character. chr() may be used as an alias for lang.chr().

Sample Usage

# Pick a random letter from A - Z

$char = lang.chr( math.random( 26 ) + 65 );

Alternative name: chr

See also: lang.ord( string )

lang.dump( variable )

Converts the supplied variable into a human-readable string. This function is useful for printing the contents of arrays and hashes when debugging TrafficScript rules.

Sample Usage

# Print the headers of the current HTTP request

log.info( lang.dump( http.getHeaders() ) );

lang.isarray( data )

Returns whether or not the supplied data is an array.

Sample Usage

sub passMeAnArray( $array ) {

# Test whether the supplied data is an array

if( !lang.isArray( $array ) ) {

return false;

}

# ...

}

See also: lang.ishash( data )

lang.ishash( data )

Returns whether or not the supplied data is a hash.

Sample Usage

sub passMeAHash( $hash ) {

# Test whether the supplied data is a hash

if( !lang.isHash( $hash ) ) {

return false;

}

# ...

}

See also: lang.isarray( data )

lang.max( param1, param2 )

Returns the maximum value of the two parameters provided. If both parameters are strings, it uses a string comparison; otherwise, the parameters are promoted to integers or doubles and compared. max() may be used as a shorthand for lang.max().

Sample Usage

$r = lang.max( 9, 10 ); # returns 10

$s = lang.max( "9", "10" ); # returns "9"

$r = lang.max( 2, "4.8" ); # returns 4.8

Alternative name: max

See also: lang.min( param1, param2 )

lang.min( param1, param2 )

Returns the minimum value of the two parameters provided. If both parameters are strings, it uses a string comparison; otherwise, the parameters are promoted to integers or doubles and compared. min() may be used as a shorthand for lang.min().

Sample Usage

$r = lang.min( 9, 10 ); # returns 9

$s = lang.min( "9", "10" ); # returns "10"

$r = lang.min( 2, "4.8" ); # returns 2

Alternative name: min

See also: lang.max( param1, param2 )

lang.ord( string )

Converts an ascii character to an integer. ord() may be used as a shorthand alias for lang.ord().

Sample Usage

# Get the integer value of a character.

$val = lang.ord( "A" );

Alternative name: ord

See also: lang.toString( value ), lang.chr( number )

lang.toArray( values )

Returns an array of the supplied values.

Sample Usage

$arr = lang.toArray( "10", "hello" );

See also: lang.toDouble( value ), lang.toString( value ), lang.toInt( value )

lang.toDouble( value )

Returns the double (floating point) value of its parameter, using the TrafficScript type-casting rules.

Sample Usage

$r = lang.toDouble( "3.14157" ); # returns 3.14157

$r = lang.toDouble( 10 ); # returns 10

$r = lang.toDouble( 3.14175 ); # returns 3.14175

$r = lang.toDouble( "..." ); # returns 0.0

Alternative name: toDouble

See also: lang.toInt( value ), lang.toString( value )

lang.toHash( values )

Returns an hash of the supplied key value pairs.

Sample Usage

$hash = lang.toHash( "ten", 10, "eleven", 11 );

See also: lang.toDouble( value ), lang.toString( value ), lang.toInt( value ), lang.toArray( values )

lang.toInt( value )

Returns the integer value of its parameter, using the TrafficScript type-casting rules.

Sample Usage

$r = lang.toInt( "10xxx" ); # returns 10

$r = lang.toInt( 3.14157 ); # returns 3

$r = lang.toInt( 10 ); # returns 10

$r = lang.toInt( "..." ); # returns 0

Alternative name: toInt

See also: lang.toDouble( value ), lang.toString( value )

lang.toString( value )

Returns the string value of its parameter, using the TrafficScript type-casting rules.

Sample Usage

$s = lang.toString( 10 ); # returns "10"

$s = lang.toString( 3.14157 ); # returns "3.14157"

$s = lang.toString( "10" ); # returns "10"

Alternative name: toString

See also: lang.toInt( value ), lang.toDouble( value ), lang.chr( number ), lang.ord( string )

lang.tochar( number )

This function is an alias for lang.chr.

Sample Usage

# Pick a random letter from A - Z

$char = lang.tochar( math.random( 26 ) + 65 );

Alternative name: tochar

See also: lang.chr( number )

lang.warn( message )

Prints a warning to the log with the line number that this function call appears on. If strict error checking is enabled then the rule will abort.

Sample Usage

$decoded = string.decrypt( $password, "passphrase" );

if( !$decoded ) {

lang.warn( "Failed to decrypt string" );

} else {

# String decrypt succeeded...

}

See also: lang.assert( condition, message )

math.acos( x )

Calculates the arc cosine of x and returns an angle in radians in the range 0 to pi.

Sample Usage

$acos = math.acos( 0 ); # returns pi/2 (approx.)

Alternative name: acos

See also: math.cos( angle )

math.asin( x )

Calculates the arc sine of x and returns an angle in radians in the range -pi/2 to pi/2.

Sample Usage

$asin = math.asin( 0 ); # returns 0 (approx.)

Alternative name: asin

See also: math.sin( angle )

math.atan( angle )

Calculates the arc tangent of x and returns an angle in radians in the range -pi/2 to pi/2.

Sample Usage

$atan = math.atan( 0 ); # returns 0 (approx.)

Alternative name: atan

See also: math.tan( angle )

math.ceil( value )

Returns the smallest integer greater than or equal to its parameter.

Sample Usage

$r = math.ceil( 6.28 ); # returns 7

$r = math.ceil( "4" ); # returns 4

Alternative name: ceil

See also: math.floor( value ), math.rint( value ), math.fabs( value )

math.cos( angle )

Interprets its parameter as an angle in radians and returns its cosine.

Sample Usage

$cos = math.cos( 6.28314 ); # returns 1 (approx.)

Alternative name: cos

See also: math.sin( angle ), math.tan( angle )

math.exp( power )

Calculates e raised to the power of its parameter and returns the result.

Sample Usage

$r = math.exp( math.ln( 10 ) ); # returns 10

Alternative name: exp

See also: math.ln( value ), math.pow( num, power )

math.fabs( value )

Interprets its parameter as a floating point number and returns its absolute value.

Sample Usage

$r = math.fabs( -6.28 ); # returns 6.28

Alternative name: fabs

See also: math.floor( value ), math.ceil( value ), math.rint( value )

math.floor( value )

Returns the largest integer not greater than its parameter.

Sample Usage

$r = math.floor( 4.001 ); # returns 4

$r = math.floor( 17 ); # returns 17

Alternative name: floor

See also: math.ceil( value ), math.rint( value ), math.fabs( value )

math.ln( value )

Returns the natural logarithm of its parameter.

Sample Usage

$ln = math.ln( 2.71828 ); # returns 1 (approximately)

Alternative name: ln

See also: math.log( value ), math.exp( power )

math.log( value )

Returns the base10 logarithm of its parameter.

Sample Usage

$log = math.log( 100 ); # returns 2

Alternative name: log

See also: math.ln( value ), math.pow( num, power )

math.pow( num, power )

Raises its first parameter to the power of its second parameter and returns the result.

Sample Usage

$r = math.pow( 2, 3 ); # returns 8

Alternative name: pow

See also: math.ln( value ), math.exp( power ), math.sqrt( num )

math.random( range )

Returns a pseudorandom integer greater than or equal to zero, and less than its parameter. This function uses a quick pseudo-random number generator meaning that the output of this function is not suitable for cryptographic purposes.

Sample Usage

# returns a value in the range 0 to 99

$rand = math.random( 100 );

Alternative name: random

See also: string.randomBytes( length )

math.rint( value )

Rounds its parameter by returning the integer closest to its value.

Sample Usage

$r = math.rint( 4.25 ); # returns 4

$r = math.rint( 4.75 ); # returns 5

Alternative name: rint

See also: math.floor( value ), math.ceil( value ), math.fabs( value )

math.sin( angle )

Interprets its parameter as an angle in radians and returns its sine.

Sample Usage

$sin = math.sin( 6.28314 ); # returns 0 (approx.)

Alternative name: sin

See also: math.cos( angle ), math.tan( angle )

math.sqrt( num )

Returns the square root of its parameter.

Sample Usage

$root = math.sqrt( 2 ); # returns 1.414 (approx.)

 

if( lang.toString( math.sqrt( $num ) ) == "nan" ) {

# $num is negative or NaN ...

}

Alternative name: sqrt

See also: math.pow( num, power )

math.tan( angle )

Interprets its parameter as an angle in radians and returns its tangent.

Sample Usage

$tan = math.tan( 6.28314 ); # returns 0 (approx.)

Alternative name: tan

See also: math.sin( angle ), math.cos( angle )

string.BERToInt( string )

Converts a BER compressed integer into an integer.

Sample Usage

# $r = 200

$r = string.BERToInt( "\201\110" );

Alternative name: BERToInt

See also: string.intToBER( number ), string.bytesToInt( string )

string.Ireplace( string, search, replacement ) - deprecated

This function has been deprecated. Use instead string.replaceI( string, search, replacement ).

Returns a new string, copied from the original string, with the first occurrence of the search string in the supplied string replaced by the replacement string. This function is case-insensitive.

string.IreplaceAll( string, search, replacement ) - deprecated

This function has been deprecated. Use instead string.replaceAllI( string, search, replacement ).

Returns a new string, copied from the original string, with all occurrences of the search string in the supplied string replaced by the replacement string. This function is case-insensitive.

string.append( str1, str2, ... )

Returns the result of concatenating all of its inputs together as strings.

Sample Usage

# Returns "The answer is 42"

$s = string.append( "The ", "answer ", "is " , 42 );

Alternative name: append

string.base64Urldecode( Input string, strictMode Flag )

Decodes a base64Url-encoded string and returns the hash of "flag" and "value".

If strict mode is on(1) and invalid input(eg. padding characters, whitespace, line breaks) is given then hash conatining error flag(1) and empty string is returned.

Base64Url encoding is used for files names and JWT tokens.

Sample Usage

# Decodes the JOSE header of JWT token

$token = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ\

9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQo\

gImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.d\

BjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";

$splitted = string.split( $token, "." );

$hash = string.base64Urldecode( $splitted[0], 1 );

if( $hash["flag"] == 0) {

$jose = $hash["value"];

log.info( "JOSE header is: ".$jose );

}

Alternative name: base64Urldecode

See also: string.base64decode( string ), string.hexdecode( encoded string ), string.unescape( escaped string )

string.base64Urlencode( Input string, strictMode Flag )

Returns the base64Url-encoded version of the provided string.

This converts each group of three characters into a 4-character string containing just [A-Za-z0-9-_], and '=' for padding if strictMode is off(0).

Base64Url encoding is used for files names and JWT tokens.

Sample Usage

# Encodes the JOSE header of JWT token

$header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";

$enc = string.base64Urlencode( $header, 1 );

log.info( "Encode JOSE header is: ".$enc );

Alternative name: base64Urlencode

See also: string.base64encode( string ), string.hexdecode( encoded string ), string.unescape( escaped string )

string.base64decode( string )

Decodes a base64-encoded string and returns the result.

Base64 encoding is used for MIME-encoded messages, and in the HTTP Basic Authorization header.

Sample Usage

# Decodes a username and password from HTTP

# BASIC authentication

$h = http.getHeader( "Authorization" );

if( string.startsWith( $h, "Basic " ) ) {

$enc = string.skip( $h, 6 );

$userpasswd = string.base64decode( $enc );

log.info( "User used: ".$userpasswd );

}

Alternative name: base64decode

See also: string.base64encode( string ), string.hexdecode( encoded string ), string.unescape( escaped string )

string.base64encode( string )

Returns the base64-encoded version of the provided string. This converts each group of three characters into a 4-character string containing just [A-Za-z0-9+/], and '=' for padding.

Base64 encoding is used for MIME-encoded messages, and in the HTTP Basic Authorization header.

Sample Usage

# Encodes a username and password for HTTP

# BASIC authentication

$enc = string.base64encode( "user:passwd" );

$h = "Basic ".$enc;

http.setHeader( "Authorization", $h );

Alternative name: base64encode

See also: string.base64decode( string ), string.hexencode( string ), string.escape( string )

string.bytesToDotted( string )

Converts a network ordered byte string into an IP address.

Sample Usage

# The first 4 bytes are the IP address

$ipstr = string.substring( $msg, 0, 3 );

log.info( "IP is ".string.bytesToDotted( $ipstr ) );

Alternative name: bytesToDotted

See also: string.dottedToBytes( IP address ), string.bytesToInt( string )

string.bytesToInt( string )

Converts a byte string in network order to an integer. The byte string should be either 1, 2 or 4 bytes long.

Sample Usage

# $msg starts with a 2-bytes length

$lenstr = string.substring( $msg, 0, 1 );

$len = string.bytesToInt( $lenstr );

$msg = string.substring( $msg, 2, 2+$len-1 );

Alternative name: bytesToInt

See also: string.intToBytes( number, [width] ), string.bytesToDotted( string ), string.BERToInt( string )

string.cmp( str1, str2 )

Compares its two parameters as strings in a case-sensitive manner. It returns a negative value if str1 is less than str2; zero if they are equal, and a positive value if str1 is greater than str2.

Sample Usage

if( string.cmp( $a, "HTTP/1.0" ) == 0 ) {

# $a is "HTTP/1.0"

}

 

if( string.cmp( $a, $b ) < 0 ) {

# $a is less than $b

}

Alternative name: cmp

See also: string.icmp( str1, str2 )

string.contains( haystack, needle )

Searches for the provided string (the needle) in the given source (the haystack).

It returns 1 if the 'needle' was found, or 0 otherwise.

Sample Usage

if( string.contains( $cookie, "chocolate" ) ) {

# The cookie contains chocolate ...

}

Alternative name: contains

See also: string.containsI( haystack, needle ), string.find( haystack, needle, [start] ), string.findr( haystack, needle, [distanceFromEndToStart] ), string.startsWith( string, prefix ), string.endsWith( string, suffix )

string.containsI( haystack, needle )

Searches for the provided string (the needle) in the given source (the haystack). It is case-insensitive.

It returns 1 if the 'needle' was found, or 0 otherwise.

Sample Usage

if( string.containsI( $path, "danger" ) ) {

# The path contains danger ...

}

Alternative name: containsI

See also: string.contains( haystack, needle ), string.findI( haystack, needle, [start] ), string.startsWithI( string, prefix ), string.endsWithI( string, suffix )

string.count( haystack, needle, [start] )

Searches from the start of a string, counting the number of times that the provided search string (the needle) is found inside the given string (the haystack). An optional parameter can specify the start position for the search.

It returns the number of times that the string is found.

Sample Usage

# Returns 2

$r = string.count( "This is it!", "is" );

 

# Returns 1, no overlaps allowed

$s = string.count( "ooo", "oo" );

Alternative name: count

See also: string.find( haystack, needle, [start] ), string.contains( haystack, needle )

string.decrypt( string, passphrase )

Returns the decrypted version of a string that has previously been encrypted using string.encrypt(). The passphrase supplied must match that given to string.encrypt(), otherwise the decoding will fail.

An empty string is returned if the decrypt or the integrity check fails.

Sample Usage

# Decrypt the 'kart' cookie

$cookie = http.getcookie( "kart" );

if( $cookie != "" ) {

$cookie = string.decrypt( $cookie, $passphrase );

if( $cookie == "" ) {

log.warn( "User modified kart cookie" );

http.removecookie( "kart" );

} else {

http.setcookie( "kart", $cookie );

}

}

Alternative name: decrypt

See also: string.encrypt( string, passphrase )

string.dottedToBytes( IP address )

Converts an IP address to a network order byte string.

Sample Usage

# Prepend the client IP onto $msg

$ip = request.getRemoteIP();

$msg = string.dottedToBytes( $ip ).$msg;

Alternative name: dottedToBytes

See also: string.bytesToDotted( string ), string.intToBytes( number, [width] )

string.drop( string, count )

Returns all but the last 'count' characters from the end of the provided string. An empty string will be returned if 'count' is greater than the length of the original string.

Sample Usage

# returns "www.example"

$s = string.drop( "www.example.com", 4 );

Alternative name: drop

See also: string.skip( string, count ), string.trim( string )

string.encrypt( string, passphrase )

Encrypts a string using the provided pass phrase. The returned string is encrypted using the AES block cipher, using an expanded form of the passphrase as the cipher key. A MAC is also added to ensure the integrity of the string.

This is open to replay attacks, and as such, should not be used to encrypt sensitive data, such as credit card details.

Sample Usage

# Encrypt the 'kart' cookie

$cookie = http.getresponsecookie( "kart" );

if( $cookie != "" ) {

$cookie = string.encrypt( $cookie, $passphrase );

http.setresponsecookie( "kart", $cookie );

}

Alternative name: encrypt

See also: string.decrypt( string, passphrase )

string.endsWith( string, suffix )

Returns 1 if the provided string ends with the given suffix, and 0 otherwise.

Sample Usage

if( string.endsWith( $url, ".cgi") ) {

# Request is for a CGI script ...

}

Alternative name: endsWith

See also: string.endsWithI( string, suffix ), string.startsWith( string, prefix ), string.contains( haystack, needle )

string.endsWithI( string, suffix )

Returns 1 if the provided string ends with the given suffix, and 0 otherwise. It is case-insensitive.

Sample Usage

if( string.endsWithI( $path, "victory") ) {

# The path ends with victory

}

Alternative name: endsWithI

See also: string.endsWith( string, suffix ), string.startsWithI( string, prefix ), string.containsI( haystack, needle )

string.escape( string )

Returns a percent-encoded version of its parameter.

Control characters and spaces (character value <= 32) and '%' characters are each replaced by a '%' symbol, followed by their 2-digit hex value.

Sample Usage

# returns "Hello%20World!%0D%0A"

$s = string.escape( "Hello World!\r\n" );

Alternative name: escape

See also: string.unescape( escaped string ), string.hexencode( string ), string.regexescape( string ), string.urlencode( string )

string.extractHost( string )

Returns the host part of the supplied address if it is a valid IP or hostname. Otherwise the empty string is returned.

Sample Usage

sub lookup_proxy( $path ) {

# Code to map a path to a node

}

# Send certain requests to an external server

$forward = lookup_proxy( http.getPath() );

if( $forward

&& $host = string.extractHost( $forward ) ) {

if( !$port = string.extractPort( $forward ) ) {

$port = 80;

}

pool.use( "External", $host, $port );

}

Alternative name: extractHost

See also: string.extractPort( string )

string.extractPort( string )

Returns the port part of the supplied address if both the host and port of the supplied address are valid. Otherwise the empty string is returned.

Sample Usage

# Get the SIP request's next destination

$next = sip.getRequestHeader( "Route" );

string.regexmatch( $next, "^<sip:(.*?)>" );

$next = $1;

# Get the port number of the destination

if( $port = string.extractPort( $next ) ) {

if( $port < 1024 ) {

# Don't forward the message

sip.sendResponse( "403", "Forbidden" );

}

}

Alternative name: extractPort

See also: string.extractHost( string )

string.find( haystack, needle, [start] )

Reports whether the provided search string (the needle) is contained inside the given string (the haystack). An optional parameter can specify the start position for the search.

It returns the location of the first instance of the search string; note that character positions start at 0.

If it could not find the search string, it returns -1.

Sample Usage

$r = string.find( "This is it!", "is" ); # Returns 2

Alternative name: find

See also: string.findI( haystack, needle, [start] ), string.findr( haystack, needle, [distanceFromEndToStart] ), string.contains( haystack, needle )

string.findI( haystack, needle, [start] )

Reports whether the provided search string (the needle) is contained inside the given string (the haystack). An optional parameter can specify the start position for the search. It is case-insensitive.

It returns the location of the first instance of the search string; note that character positions start at 0.

If it could not find the search string, it returns -1.

Sample Usage

# Returns 0

$r = string.findI( "The way of the warrior", "the" );

Alternative name: findI

See also: string.find( haystack, needle, [start] ), string.containsI( haystack, needle )

string.findr( haystack, needle, [distanceFromEndToStart] )

Searches backwards from the end of a string, determining whether the provided search string (the needle) is contained inside the given string (the haystack). An optional parameter can specify the start position for the search, measured from the end of the string (so setting it to 1 skips the last character in the string).

It returns the location of the last instance of the search string; note that character positions start at 0.

If it could not find the search string, it returns -1.

Sample Usage

# Returns 8 (the 'i' in it)

$r = string.findr( "This is it!", "i" );

 

# Returns 5 (the 'i' in is)

$r = string.findr( "This is it!", "i", 3 );

Alternative name: findr

See also: string.find( haystack, needle, [start] ), string.contains( haystack, needle )

string.hash( string )

Returns a number representing a hash of the provided string. When using string.hash(), negative numbers can be returned for the hash value. The returned value should not be relied on to be consistent across different releases of the software.

Sample Usage

$hash = string.hash( http.getRawURL() );

connection.setPersistenceKey( $hash % 1000 );

Alternative name: hash

string.hashMD5( string )

Returns the MD5 hash of the provided string. The returned string will be 16 bytes long, and may contain non-printable characters.

Sample Usage

$hash = string.hashMD5( $data );

Alternative name: hashMD5

See also: string.hexencode( string ), string.hashSHA1( string ), string.hashSHA256( string ), string.hashSHA384( string ), string.hashSHA512( string )

string.hashSHA1( string )

Returns the SHA1 hash of the provided string. The returned string will be 20 bytes long, and may contain non-printable characters.

Sample Usage

$hash = string.hashSHA1( $data );

Alternative name: hashSHA1

See also: string.hexencode( string ), string.hashMD5( string ), string.hashSHA256( string ), string.hashSHA384( string ), string.hashSHA512( string )

string.hashSHA256( string )

Returns the SHA-256 hash of the provided string. The returned string will be 32 bytes long, and may contain non-printable characters.

Sample Usage

$hash = string.hashSHA256( $data );

Alternative name: hashSHA256

See also: string.hexencode( string ), string.hashSHA1( string ), string.hashMD5( string ), string.hashSHA384( string ), string.hashSHA512( string )

string.hashSHA384( string )

Returns the SHA-384 hash of the provided string. The returned string will be 48 bytes long, and may contain non-printable characters.

Sample Usage

$hash = string.hashSHA384( $data );

Alternative name: hashSHA384

See also: string.hexencode( string ), string.hashSHA1( string ), string.hashMD5( string ), string.hashSHA256( string ), string.hashSHA512( string )

string.hashSHA512( string )

Returns the SHA-512 hash of the provided string. The returned string will be 64 bytes long, and may contain non-printable characters.

Sample Usage

$hash = string.hashSHA512( $data );

Alternative name: hashSHA512

See also: string.hexencode( string ), string.hashSHA1( string ), string.hashMD5( string ), string.hashSHA256( string ), string.hashSHA384( string )

string.hexToInt( string )

Converts a hexadecimal number to an integer. Returns the first valid hexadecimal value found in the string, or 0. A prefix of "0x" is accepted, but not required. Negative numbers are also valid.

Sample Usage

# Returns 10.

$int = string.hexToInt( "0000a" );

See also: string.intToHex( string )

string.hexdecode( encoded string )

Returns the hex-decoded version of the provided string. This interprets each character pair as a 2-digit hex value, replacing it with the corresponding 8-bit character. It does not verify that the original string was correctly encoded.

Sample Usage

# returns "hello"

$s = string.hexdecode("68656C6C6F");

Alternative name: hexdecode

See also: string.hexencode( string ), string.base64decode( string ), string.unescape( escaped string )

string.hexencode( string )

Returns the hex-encoded version of the provided string . This converts each character into a two-character hex representation, doubling the length of the string.

Sample Usage

# Returns "68656C6C6F"

$s = string.hexencode( "hello" );

Alternative name: hexencode

See also: string.hexdecode( encoded string ), string.base64encode( string ), string.escape( string )

string.hmacSHA256( secret_key, string )

Returns the keyed-hash message authentication code (HMAC) for the key and string supplied, using the SHA-256 algorithm. The returned string will be 32 bytes long, and may contain non-printable characters.

Sample Usage

$hash = string.hmacSHA256( $secret_key, $data );

Alternative name: hmacSHA256

See also: string.hexencode( string ), string.hashSHA256( string )

string.htmldecode( encodedstring )

Returned the HTML-decoded version of a string, converting symbols such as &lt; and &quot;

Sample Usage

$body = string.htmldecode( http.getBody( 0 ) );

Alternative name: htmldecode

See also: string.hexencode( string )

string.htmlencode( string )

Returns the encoded version of the supplied string to make it safe for including in HTML. It converts '<' to &lt;, '>' to &gt;, ''' to &quot; and '&' to &amp;. Control characters are hex-encoded.

Sample Usage

$html = string.htmlencode( $parameter );

Alternative name: htmlencode

See also: string.htmldecode( encodedstring ), string.urlencode( string )

string.icmp( str1, str2 )

Compares its two parameters as strings in a case-insensitive manner. It returns a negative value if str1 is less than str2; zero if they are equal, and a positive value if str1 is greater than str2.

Sample Usage

if( string.icmp( $a, "Content-Length" ) == 0 ) {

# $a is "Content-Length"

}

Alternative name: icmp

See also: string.cmp( str1, str2 )

string.insertBytes( string, insertion, offset )

Returns a new string with the supplied string inserted into the original string at the offset specified. If offset < 0, or offset > length( string ), the original string is returned unchanged. If offset == 0 the insertion string is prepended; if offset == length( string ) the insertion string is appended.

Sample Usage

# $r = "he was Othello"

$r = string.insertbytes( "hello", " was Othe", 2 );

 

# $r = "hello world"

$r = string.insertbytes( "hello", " world", 5 );

 

# $r = "I say hello"

$r = string.insertbytes( "hello", "I say ", 0 );

Alternative name: insertBytes

See also: string.replaceBytes( string, replacement, offset )

string.intToBER( number )

Converts an integer into a BER compressed integer (which is a variable-length binary string encoding).

Sample Usage

# $r = "\201\110"

$r = string.intToBER( 200 );

Alternative name: intToBER

See also: string.BERToInt( string ), string.intToBytes( number, [width] )

string.intToBytes( number, [width] )

Converts an integer to a network order byte string of the specified width. Only widths of 1, 2 and 4 are permitted, and the width defaults to 4 if it is not supplied.

Sample Usage

# Prepend $msg with its length, as a 4-byte int

$msg = string.insertBytes( $msg,

string.intToBytes( string.len( $msg ) ),

0 );

Alternative name: intToBytes

See also: string.bytesToInt( string ), string.bytesToDotted( string ), string.intToBER( number )

string.intToHex( string )

Converts an integer into a hexadecimal string.

Sample Usage

# Returns "0000cafe"

$hex = string.intToHex( 51966 );

See also: string.hexToInt( string )

string.ipmaskmatch( IP Address, CIDR IP Subnet )

Returns 1 if the provided IP address is contained in the CIDR IP Subnet, and 0 otherwise.

It interprets its first parameter as a string containing an IP address, and its second parameter as an CIDR IP subnet. CIDR IP subnets can be of the form "10.0.1.0/24", "10.0.1.0/255.255.255.0", "10.0.1." or "10.0.1.1".

For IPv6, the standard notation of "2001:200:0:8002::/64" is supported.

Sample Usage

if( string.ipmaskmatch( $ip, "10.0.0.0/8" ) ) {

# IP is in the 10.*.*.* subnet ...

}

Alternative name: ipmaskmatch

See also: string.validIPAddress( string )

string.left( string, count )

Returns the first 'count' characters of the provided string. An empty string will be returned if 'count' is less than or equal to zero.

Sample Usage

# returns "#!"

$s = string.left( "#!/bin/sh", 2 );

Alternative name: left

See also: string.skip( string, count )

string.len( string )

Interprets its parameter as a string and returns its length (in bytes).

Sample Usage

$len = string.len( "Hello world!" ); # returns 12

Alternative name: len

string.length( string )

This function is an alias for string.len.

Sample Usage

$len = string.length( "Hello world!" ); # returns 12

Alternative name: length

See also: string.len( string )

string.lowercase( string )

Returns a new string containing all characters in the provided string converted to lowercase. The provided string is not modified.

Sample Usage

$s = string.lowercase("AbCdEfG"); # Returns "abcdefg"

Alternative name: lowercase

See also: string.uppercase( string )

string.normalizeIPAddress( string )

Returns a unique string representation of an IP address: all leading zeros are removed, and for IPv6 addresses the longest occurrence of a block of more than one consecutive zero is replaced by "::". If there is more than one such block then the first one is replaced. This normal form can be used to compare IP addresses without ambiguity and is also the form used by TrafficScript functions returning IP addresses. If the string is not a valid IP address, the empty string is returned.

Sample Usage

$remote_ip = request.getremoteip();

$client = string.normalizeipaddress(

"2001::0157:0:0:0:0:006a" );

# $client is now "2001:0:157::6a"

if( $remote_ip == $client ){

# do something specific for this client

}

Alternative name: normalizeIPAddress

See also: string.validIPAddress( string )

string.randomBytes( length )

Returns a string of the supplied length filled with random bytes. The random number generator used by this function generates output that is suitable for use in cryptographic operations.

Sample Usage

# Get a string 16 bytes long filled with random data

$str = string.randomBytes( 16 );

Alternative name: randomBytes

See also: math.random( range )

string.regexescape( string )

Returns a version of its parameter suitable for using inside a regex match as a string literal.

All characters in the string that aren't a-z, A-Z, 0-9 or '_' are escaped using a backslash.

Sample Usage

$str = "10.100.230.5";

$escaped = string.regexescape( $str );

if( string.regexmatch( $line, $escaped ) ) {

log.info( "Line matched: " . $str );

}

Alternative name: regexescape

See also: string.escape( string )

string.regexmatch( string, regex, [flags] ) )

Performs a regular expression match on the supplied string. If the regular expression 'regex' contains bracketed sub-expressions, then the variables $1 ... $9 will be set to the matching substrings.

Note that the '\' character is an escape character in TrafficScript strings enclosed with double quotation marks. If you need to put a literal '\' in a regular expression, you must escape it as '\\' or enclose the string in single quotation marks. To match a literal string inside a regular expression use the string.regexEscape function.

The optional 'flags' parameter contains a string of single-letter options. The following options are supported:

'i', meaning 'case insensitive' - letters in the pattern match both upper and lower case letters.

It returns 1 if matched, and 0 otherwise.

If the regular expression is constructed from client supplied data, see the security considerations in the "Administration System Security" chapter of the User's Guide.

Sample Usage

$id = "user=Joe, password=Secret";

if( string.regexmatch(

$id, "^user=(.*), password=(.*)$" ) ) {

log.info( "Got UserID: ".$1.", Password: ".$2 );

}

 

$name = "Name( Bob )";

string.regexmatch( $name, 'Name\( (\S+) \)' );

log.info( $1 ); # prints Bob

Alternative name: regexmatch

See also: string.wildmatch( string, pattern ), string.regexsub( string, regex, replacement, [flags] ), string.regexescape( string )

string.regexsub( string, regex, replacement, [flags] )

Returns a new string containing the results of a regular expression match on the supplied string, replacing each matching substring with the supplied replacement. The replacement string may contain $1 .. $9 substitutions, which reference bracketed sub-expressions in the regular expression.

Note that the '\' character is an escape character in TrafficScript strings enclosed with double quotation marks. If you need to put a literal '\' in a regular expression, you must escape it as '\\' or enclose the string in single quotation marks. To match a literal string inside a regular expression use the string.regexEscape function.

The optional 'flags' parameter contains a string of single-letter options. The following options are supported:

'g', meaning 'global replace' - apply the regex pattern as many times as possible.

'i', meaning 'case insensitive' - letters in the pattern match both upper and lower case letters.

string.regexsub() returns the string with the replacements.

If the regular expression is constructed from client supplied data, see the security considerations in the "Administration System Security" chapter of the User's Guide.

Sample Usage

# Rewrite incoming URL

$url = string.regexsub($url, "^/(.*)/secure",

"/$1/private");

 

 

# Remove cookieless session from URL

# e.g. "/(sessionid)/app/index" => "/app/index"

$url = string.regexsub( $url, '/\(\S+\)/', "/" );

Alternative name: regexsub

See also: string.regexmatch( string, regex, [flags] ) )

string.replace( string, search, replacement )

Returns a new string, copied from the original string, with the first occurrence of the search string in the supplied string replaced by the replacement string. This function is case-sensitive.

Sample Usage

# Rewrite incoming URL

$url = string.replace($url, "/secure", "/private");

Alternative name: replace

See also: string.replaceI( string, search, replacement ), string.replaceAll( string, search, replacement ), string.replaceAllI( string, search, replacement )

string.replaceAll( string, search, replacement )

Returns a new string, copied from the original string, with all occurrences of the search string in the supplied string replaced by the replacement string. This function is case-sensitive.

Sample Usage

# Rewrite incoming URL

$url = string.replaceAll($url, "/in", "/out");

Alternative name: replaceAll

See also: string.replaceAllI( string, search, replacement ), string.replace( string, search, replacement ), string.replaceI( string, search, replacement )

string.replaceAllI( string, search, replacement )

Returns a new string, copied from the original string, with all occurrences of the search string in the supplied string replaced by the replacement string. This function is case-insensitive.

Sample Usage

# Rewrite incoming URL

$url = string.replaceAllI($url, "/in", "/out");

Alternative name: replaceAllI

See also: string.replaceAll( string, search, replacement ), string.replaceI( string, search, replacement ), string.replace( string, search, replacement )

string.replaceBytes( string, replacement, offset )

Returns a new string, copied from the original string, with the appropriate bytes replaced by the replacement string at the supplied offset. The new string is the same length as the original string.

If offset < 0, or offset >= length( string ), or length( replacement ) == 0, string.replaceBytes returns a copy of the original string.

Sample Usage

# $r = "hi lo"

$r = string.replaceBytes( "hello", "i ", 1 );

 

# $r = "helwo"

$r = string.replaceBytes( "hello", "world", 3 );

Alternative name: replaceBytes

See also: string.insertBytes( string, insertion, offset )

string.replaceI( string, search, replacement )

Returns a new string, copied from the original string, with the first occurrence of the search string in the supplied string replaced by the replacement string. This function is case-insensitive.

Sample Usage

# Rewrite incoming URL

$url = string.replaceI($url, "/secure", "/private");

Alternative name: replaceI

See also: string.replace( string, search, replacement ), string.replaceAllI( string, search, replacement ), string.replaceAll( string, search, replacement )

string.reverse( string )

Returns the characters of a string in reverse order.

Sample Usage

$c = string.reverse( "esrever" ); # Returns "reverse"

Alternative name: reverse

string.right( string, count )

Returns the last 'count' characters of the provided string. An empty string will be returned if 'count' is less than or equal to zero.

Sample Usage

# returns "sh"

$s = string.right( "#!/bin/sh", 2 );

Alternative name: right

See also: string.drop( string, count )

string.skip( string, count )

Returns all but the first 'count' characters from the input string. An empty string will be returned if 'count' is greater than the length of the original string.

Sample Usage

# returns "/bin/sh"

$s = string.skip( "#!/bin/sh", 2 );

Alternative name: skip

See also: string.drop( string, count ), string.trim( string )

string.split( string, [separator] )

Returns an array containing the substrings of the supplied string that are delimited by the separator. The separator defaults to a space character, so applying this method to a string without supplying the separator character will return an array containing all the individual words in the string. Using the empty string as the separator will return an array with each character as a separate element.

Sample Usage

$words = string.split( http.getResponseBody() );

log.info( "There were " . array.length( $words )

. " words in the response" );

See also: array.join( array, [separator] )

string.sprintf( format string, arguments )

Behaves like the C library sprintf() function. Only %s, %c, %d and %f are supported. The function returns the generated string.

Sample Usage

$text = string.sprintf(

"Apples: %3d Oranges: %3d\n",

$apples, $oranges );

Alternative name: sprintf

See also: string.append( str1, str2, ... )

string.startsWith( string, prefix )

Returns 1 if the provided string starts with the given prefix, and 0 otherwise.

Sample Usage

if( string.startsWith( $url, "http://" ) ) {

# URL is of the form http://host/uri ...

}

Alternative name: startsWith

See also: string.startsWithI( string, prefix ), string.endsWith( string, suffix ), string.contains( haystack, needle )

string.startsWithI( string, prefix )

Returns 1 if the provided string starts with the given prefix, and 0 otherwise. It is case-insensitive.

Sample Usage

if( string.startsWithI( $path, "/tea" ) ) {

# The path starts with tea ...

}

Alternative name: startsWithI

See also: string.startsWith( string, prefix ), string.endsWithI( string, suffix ), string.containsI( haystack, needle )

string.substring( string, base, end )

Returns the substring starting at character position 'base' and ending at position 'end'.

Note that character positions start at 0, and the end position is inclusive.

Sample Usage

# Set $s to "is is a"

$s = string.substring( "This is a string", 2, 8 );

Alternative name: substring

string.trim( string )

Returns the result of removing leading and trailing white space (and control characters) from its input

Sample Usage

$s = string.trim( " 1234 " ); # returns "1234"

Alternative name: trim

See also: string.skip( string, count ), string.drop( string, count )

string.unescape( escaped string )

Returns the escape-decoded version of its parameter.

%-encoded characters are replaced with their decoded versions. %u-encoded characters are replaced with their UTF-8 representation. If there are illegal digits which cannot safely be converted, the variable $1 is set to 0 and the result contains '_' in place of the '%'. Such malicious %-escaped URLs are a common way of attacking unassuming servers or applications, and by handling them in this way, the attack is thwarted, but some information about a suspicious request is retained.

Sample Usage

# returns "\r\n100%"

$s = string.unescape("%0D%0A100%25");

# returns "something_BGelse"

$s = string.unescape("something%BGelse");

# returns "file.ida"

$s = string.unescape("file.%u0069%u0064%u0061");

Alternative name: unescape

See also: string.escape( string ), string.hexdecode( encoded string )

string.uppercase( string )

Returns a new string containing all characters in the provided string converted to uppercase. The provided string is not modified.

Sample Usage

$s = string.uppercase("aBcDeFg"); # Returns "ABCDEFG"

Alternative name: uppercase

See also: string.lowercase( string )

string.urlencode( string )

Returns the URL-encoded version of the supplied string to make it safe for including in URLs. It converts anything other than A-Z a-z 0-9 . - _ to percent+hex form. It encodes reserved characters (RFC 3986) and % as well. string.urlencodeexceptreserved() should be used instead to exclude those.

Sample Usage

#$url will be

# %2Fcheck%20price%3Famount%3D12%26currency%3D%24

$url = string.urlencode(

"/check price?amount=12&currency=$");

Alternative name: urlencode

See also: string.unescape( escaped string ), string.htmlencode( string )

string.urlencodeexceptreserved( string )

Returns the URL-encoded version of the supplied string to make it safe for including in URLs. It converts characters except - unreserved characters A-Z a-z 0-9 . - _ - reserved characters / ? # [ ] @ ! $ & ' ( ) - % according to RFC 3986 to percent+hex form.

Sample Usage

# $url will be

# "/check%20price?amount=12&currency=$"

# where space ' ' gets encoded to %20

# and leaving /, ?, = and $ as they were.

$url = string.urlencodeexceptreserved(

"/check price?amount=12&currency=$");

Alternative name: urlencodeexceptreserved

See also: string.unescape( escaped string ), string.htmlencode( string ), string.urlencode( string )

string.validIPAddress( string )

Returns 4 if the string provided is an IPv4 address, 6 if it is an IPv6 address and 0 if it is not a valid IP address.

Sample Usage

$ipversion = string.validIPAddress( $x );

if( 4 == $ipversion ) {

# do something specific to IPv4

} else if( 6 == $ipversion ) {

# do something specific to IPv6

} else {

# error: not a valid IP address

}

Alternative name: validIPAddress

See also: string.ipmaskmatch( IP Address, CIDR IP Subnet )

string.wildmatch( string, pattern )

Performs a shell-like wild match on the supplied string. The pattern may contain the wildcard characters '?' (which matches a single character) and '*' (which matches any substring).

It returns 1 if matched, and 0 otherwise.

Sample Usage

$url = http.getPath();

if( string.wildmatch( $url, "*.cgi" ) ) {

# Is a request for a CGI script ...

}

Alternative name: wildmatch

See also: string.regexmatch( string, regex, [flags] ) )

string.gmtime.parse( str )

Parses the supplied string as a time stamp and returns the time in seconds since the epoch (1st Jan 1970). Dates before the epoch or after 2038 will produce unexpected results.

Note: Timezone information contained inside the time string is ignored. The time is always assumed to be in GMT.

Sample Usage

# Parse a string into unix time format

$str = "Tue, 21 Oct 2008 13:44:26 GMT";

$time = string.gmtime.parse( $str );

See also: sys.gmtime.format( format, unixtime )

sys.domainname()

Returns the domain name of the host machine. For example, if the machine is named "server1.example.com", sys.domainname() will return "example.com".

Sample Usage

$domainname = sys.domainname();

Alternative name: domainname

See also: sys.hostname()

sys.getenv( variable )

Returns the named environment variable, or the empty string if the environment variable does not exists.

Sample Usage

$zeushome = sys.getenv( "ZEUSHOME" );

Alternative name: getenv

sys.getnetworkinterfaces( hash_of_options )

Returns a list of network interfaces on the system, with a hash of the following for each one: Bcast, pppdest, IfName, netmask, MacAddr, IP, up

The following options can be supplied in a hash in order to alter the output:

"include_lo" => [0|1] This option controls whether the list returned should include loopback addresses. (Default: 1)

"up" => [0|1] If 1, only return interfaces marked as UP. If 0, ignore the UP status. (Default: 0)

Sample Usage

$info = sys.getnetworkinterfaces( ["include_lo" => 0,

"up" => 1 ] );

if($info)

{

foreach( $ipinfo in $info ) {

$ip = $ipinfo["IP"];

$name = $ipinfo["IfName"];

$mac = $ipinfo["MacAddr"];

log.info("---------------------"

. "\n interface = " . $name

. "\n IP = " . $ip

. "\n MAC = " . $mac

);

}

}else {

log.info("No network interfaces returned");

}

sys.getpid()

Returns the process id of the current process.

Sample Usage

$mypid = sys.getpid();

Alternative name: getpid

sys.hostname()

Returns the hostname of the host machine. For example, if the machine is named "server1.example.com", sys.hostname() will return "server1".

Sample Usage

$hostname = sys.hostname();

Alternative name: hostname

See also: sys.domainname()

sys.time()

Returns the current system time as the number of seconds since midnight, 1/1/1970.

Sample Usage

$unixtime = sys.time();

Alternative name: time

See also: sys.timeToString( unixtime ), sys.localtime.format( format, unixtime ), sys.gmtime.format( format, unixtime ), sys.tztime.format( format, timezone, unixtime ), sys.time.highres()

sys.timeToString( unixtime )

Takes the time in seconds since midnight, 1/1/1970 and if the optional unixtime parameter is provided, returns a formatted string representing that time. If the unixtime parameter is not given, it returns the current time as a formatted string.

Sample Usage

# Returns "[01/Feb/2004:12:24:51 +2000]"

$tm = sys.timeToString( sys.time() );

Alternative name: timeToString

See also: sys.time()

sys.gmtime.format( format, unixtime )

Converts the time into a string format. This function converts using GM time - see sys.localtime.format() to convert using localtime.

Format

Meaning

Format

Meaning

%a

Mon Tue Wed ...

%A

Monday Tuesday ...

%b

Jan Feb Mar ...

%B

January February ...

%d

Day of month "01"-"31"

%D

%m/%d/%y

%e

Day of month " 1"-"31"

%H

Hour of day "00-23"

%h

Equivalent to %b

%I

Hour of day "01" - "12"

%j

Julian day of the year "001" to "366"

%m

Month of year "01" - "12"

%M

Minute "00" - "59"

%n

Newline character

%p

AM/PM

%r

Time in %I:%M:%S [AM|PM]

%R

%H:%M

%S

Seconds, output as a number between "00" and "61"

%t

Tab character

%T

%H:%M:%S

%u

Day of week (1 = Monday, 7 = Sunday)

%w

Day of week (0 = Sunday, 6 = Saturday)

%y

Year (without century) "00" to "99"

%Y

Year "0000" to "9999"

%Z

Time zone ("GMT")

%%

"%"

If supplied, the optional 'unixtime' parameter specifies the number of seconds since midnight 1/1/1970, and the function returns a formatted string representing that time. If the 'unixtime' value is not provided, the current time will be returned.

Sample Usage

# Return a time suitable for an HTTP header

# e.g. Mon, 14 Aug 2006 12:39:01 GMT

$str = sys.gmtime.format( "%a, %d %b %Y %T GMT" );

Alternative name: gmtime.format

See also: sys.time(), sys.time.seconds( unixtime ), sys.time.minutes( unixtime ), sys.time.hour( unixtime ), sys.time.weekday( unixtime ), sys.time.monthday( unixtime ), sys.time.month(), sys.time.year( unixtime ), sys.time.yearday( unixtime ), sys.localtime.format( format, unixtime ), string.gmtime.parse( str )

sys.localtime.format( format, unixtime )

Converts the time into a string format. This function converts using localtime - see sys.gmtime.format() to convert using GMT.

Format

Meaning

Format

Meaning

%a

Mon Tue Wed ...

%A

Monday Tuesday ...

%b

Jan Feb Mar ...

%B

January February ...

%d

Day of month "01"-"31"

%D

%m/%d/%y

%e

Day of month " 1"-"31"

%H

Hour of day "00-23"

%h

Equivalent to %b

%I

Hour of day "01" - "12"

%j

Julian day of the year "001" to "366"

%m

Month of year "01" - "12"

%M

Minute "00" - "59"

%n

Newline character

%p

AM/PM

%r

Time in %I:%M:%S [AM|PM]

%R

%H:%M

%S

Seconds, output as a number between "00" and "61"

%t

Tab character

%T

%H:%M:%S

%u

Day of week (1 = Monday, 7 = Sunday)

%w

Day of week (0 = Sunday, 6 = Saturday)

%y

Year (without century) "00" to "99"

%Y

Year "0000" to "9999"

%Z

Time zone (from $TZ)

%%

"%"

If supplied, the optional 'unixtime' parameter specifies the number of seconds since midnight 1/1/1970, and the function returns a formatted string representing that time. If the 'unixtime' value is not provided, the current time will be returned.

Sample Usage

# Return a formatted string

# e.g. Mon, 14 Aug 2006 12:39:01 EST

$str = sys.localtime.format( "%a, %d %b %Y %T EST" );

Alternative name: localtime.format

See also: sys.time(), sys.time.seconds( unixtime ), sys.time.minutes( unixtime ), sys.time.hour( unixtime ), sys.time.weekday( unixtime ), sys.time.monthday( unixtime ), sys.time.month(), sys.time.year( unixtime ), sys.time.yearday( unixtime ), sys.gmtime.format( format, unixtime )

sys.time.highres()

Returns the current system time as the number of seconds and microseconds since midnight, 1/1/1970. The value is returned as a double, e.g. 1138417190.823265

Sample Usage

$time = sys.time.highres();

Alternative name: time.highres

See also: sys.timeToString( unixtime ), sys.localtime.format( format, unixtime ), sys.gmtime.format( format, unixtime ), sys.time()

sys.time.hour( unixtime )

Returns the hour of the day in local time (0-23).

If optional parameter 'unixtime' is supplied, then this specifies the time since midnight 1/1/1970 otherwise the current time will be used.

Sample Usage

$hour = sys.time.hour();

Alternative name: time.hour

See also: sys.time(), sys.time.seconds( unixtime ), sys.time.minutes( unixtime ), sys.time.weekday( unixtime ), sys.time.monthday( unixtime ), sys.time.yearday( unixtime ), sys.time.month(), sys.time.year( unixtime ), sys.localtime.format( format, unixtime )

sys.time.minutes( unixtime )

Returns the minutes after the hour in local time (0-59).

If optional parameter 'unixtime' is supplied, then this specifies the time since midnight 1/1/1970 otherwise the current time will be used.

Sample Usage

$mins = sys.time.minutes();

Alternative name: time.minutes

See also: sys.time(), sys.time.seconds( unixtime ), sys.time.hour( unixtime ), sys.time.weekday( unixtime ), sys.time.monthday( unixtime ), sys.time.yearday( unixtime ), sys.time.month(), sys.time.year( unixtime ), sys.localtime.format( format, unixtime )

sys.time.month()

Returns the month of the year in local time (1-12).

If optional parameter 'unixtime' is supplied, then this specifies the time since midnight 1/1/1970 otherwise the current time will be used.

Sample Usage

# Find out what the month is tomorrow.

$month = sys.time.month( sys.time() + 86400);

Alternative name: time.month

See also: sys.time(), sys.time.seconds( unixtime ), sys.time.minutes( unixtime ), sys.time.hour( unixtime ), sys.time.weekday( unixtime ), sys.time.monthday( unixtime ), sys.time.yearday( unixtime ), sys.time.year( unixtime ), sys.localtime.format( format, unixtime )

sys.time.monthday( unixtime )

Returns the day of the month in local time (1-31).

If optional parameter 'unixtime' is supplied, then this specifies the time since midnight 1/1/1970 otherwise the current time will be used.

Sample Usage

$dayofmonth = sys.time.monthday();

Alternative name: time.monthday

See also: sys.time(), sys.time.seconds( unixtime ), sys.time.minutes( unixtime ), sys.time.hour( unixtime ), sys.time.weekday( unixtime ), sys.time.yearday( unixtime ), sys.time.month(), sys.time.year( unixtime ), sys.localtime.format( format, unixtime )

sys.time.seconds( unixtime )

Returns the seconds after the minute in local time. Normally, it returns a number in the range of (0-59), but can be up to 61 to allow for leap seconds.

If optional parameter 'unixtime' is supplied, then this specifies the time since midnight 1/1/1970 otherwise the current time will be used.

Sample Usage

$secs = sys.time.seconds();

Alternative name: time.seconds

See also: sys.time(), sys.time.minutes( unixtime ), sys.time.hour( unixtime ), sys.time.weekday( unixtime ), sys.time.monthday( unixtime ), sys.time.yearday( unixtime ), sys.time.month(), sys.time.year( unixtime ), sys.localtime.format( format, unixtime )

sys.time.weekday( unixtime )

Returns the day of the week in local time (1-7). Sunday has the value 1; Saturday has the value 7.

If optional parameter 'unixtime' is supplied, then this specifies the time since midnight 1/1/1970 otherwise the current time will be used.

Sample Usage

$dayofweek = sys.time.weekday();

Alternative name: time.weekday

See also: sys.time(), sys.time.seconds( unixtime ), sys.time.minutes( unixtime ), sys.time.hour( unixtime ), sys.time.monthday( unixtime ), sys.time.yearday( unixtime ), sys.time.month(), sys.time.year( unixtime ), sys.localtime.format( format, unixtime )

sys.time.year( unixtime )

Returns the year in local time (1970-2038).

If optional parameter 'unixtime' is supplied, then this specifies the time since midnight 1/1/1970 otherwise the current time will be used.

Sample Usage

$year = sys.time.year();

Alternative name: time.year

See also: sys.time(), sys.time.seconds( unixtime ), sys.time.minutes( unixtime ), sys.time.weekday( unixtime ), sys.time.monthday( unixtime ), sys.time.yearday( unixtime ), sys.time.month(), sys.time.year( unixtime ), sys.localtime.format( format, unixtime )

sys.time.yearday( unixtime )

Returns the day of the year in local time (1-366).

If optional parameter 'unixtime' is supplied, then this specifies the time since midnight 1/1/1970 otherwise the current time will be used.

Sample Usage

$dayofyear = sys.time.yearday();

Alternative name: time.yearday

See also: sys.time(), sys.time.seconds( unixtime ), sys.time.minutes( unixtime ), sys.time.hour( unixtime ), sys.time.weekday( unixtime ), sys.time.monthday( unixtime ), sys.time.month(), sys.time.year( unixtime ), sys.localtime.format( format, unixtime )

sys.tztime.format( format, timezone, unixtime )

Converts the time into a string format using the time zone specified by the timezone parameter. The OS-supplied timezone database is used to determine the necessary offset from unixtime (or the current time).

See sys.localtime.format for a description of the format string.

If supplied, the optional 'unixtime' parameter specifies the number of seconds since midnight 1/1/1970 UTC, and the function returns a formatted string representing that time. If the 'unixtime' value is not provided, the current time will be returned.

Sample Usage

# Format a string with the date and time in the

# local time of the remote IP

$ip = request.getRemoteIP();

$str = sys.tztime.format( "%a, %d %b %Y %T %Z",

geo.getTimezone( $ip ) );

Alternative name: tztime.format

See also: sys.gmtime.format( format, unixtime ), sys.localtime.format( format, unixtime ), geo.getTimezone( ip )