Help us improve your experience.

Let us know what you think.

Do you have time for a two-minute survey?

libslax Default Extension Libraries: bit, curl, db, os, and xutil

 

libslax bit Extension Library

The libslax bit extension library contains functions that create and manipulate bit strings. The functions support 64-bit integer arguments. To incorporate functions from the bit extension library into SLAX scripts, include the namespace statement for that library in the script.

Call the bit extension functions using the bit prefix and the function name. For example:

Table 1 lists the functions available in the bit extension library, which is supported in SLAX 1.1 scripts in Junos OS Release 12.2 and later.

Table 1: Functions in the libslax bit Extension Library

Function and Arguments

Description

Example

bit:and(b1, b2)

Return the logical AND of two bit strings.

bit:and("101100", "100101")

return value: "100100"

bit:clear(b1,bitnum)

Set the specified bit in the bit string to zero and return the new bit string. Bits are numbered starting from zero. If the integer argument is greater than the bit string length, the bit string is extended.

bit:clear("11111", 0)

return value: "11110"

bit:clear("11111", 6)

return value: "0011111"

bit:compare(value1, value2)

Compare two values and return an integer less than, equal to, or greater than zero, if the first argument is found to be less than, equal to, or greater than the second argument, respectively.

bit:compare("10000", 16)

return value: 0

bit:compare("11111", "10000")

return value: 1

bit:from-hex(string, len?)

Return the value of the hexademical argument as a bit string. The optional second argument pads the bit string with leading zeros (0s) until it is the specified length.

bit:from-hex("0x45", 8)

return value: "01000101"

bit:from-int(integer, len?)

Return the value of the integer argument as a bit string. The optional second argument pads the bit string with leading zeros until it is the specified length.

bit:from-int(65,8)

return value: "01000001"

bit:mask(count, len?)

Return a bit string with the specified number of low-order bits set to one. The optional second argument pads the bit string with leading zeros until it is the specified length.

bit:mask(4, 8)

return value: "00001111"

bit:nand(b1, b2)

Return the logical NAND of two bit strings.

bit:nand("101100", "100101")

return value: "010010"

bit:nor(b1, b2)

Return the logical NOR of two bit strings.

bit:nor("101100", "100101")

return value: "011011"

bit:not(b1)

Return the inversion (NOT) of a bit string.

bit:not("101100")

return value: "010011"

bit:or(b1, b2)

Return the logical OR of two bit strings.

bit:or("101100", "100101")

return value: "101101"

bit:set(b1, bitnum)

Set the specified bit in the bit string and return the new bit string. Bits are numbered starting from zero. If the integer argument is greater than the bit string length, the bit string is extended.

bit:set("1001", 2)

return value: "1101"

bit:set("1001", 6)

return value: "1001001"

bit:to-int(b1)

Return the value of the bit string argument as an integer.

bit:to-int("101100")

return value: 44

bit:to-hex(b1)

Return the value of the bit string argument as a string representation of the hexadecimal value.

bit:to-hex("101100")

return value: "0x2c"

bit:xor(b1, b2)

Return the logical XOR of two bit strings.

bit:xor("101100", "100101")

return value: "001001"

bit:xnor(b1, b2)

Return the logical XNOR of two bit strings.

bit:xnor("101100",  "100101")

return value: "110110"

libslax curl Extension Library

Understanding the libslax curl Extension Library

cURL is a command-line tool that uses the libcurl library and supports data transfers using a number of protocols, including FTP, FTPS, HTTP, HTTPS, SCP, and SMTP. For more information about cURL, see the cURL website at http://curl.haxx.se/.

The libslax distribution includes the curl extension library, which contains functions that perform cURL operations. To incorporate functions from the libslax curl extension library in SLAX scripts, include the namespace statement for that library in the script.

Call the curl extension functions using the curl prefix and the function name. cURL operations are directed using a set of elements passed to the extension functions.

Table 2 lists the supported operations in the curl extension library and includes a description of each function. Table 3 and Table 4 list the supported elements and include the syntax and a description of each element. More specifically, Table 3 lists elements used for web services operations, and Table 4 lists the elements used for e-mail operations. For examples and additional information about using the curl extension library, see The curl Extension Library.

Table 2: Functions in the libslax curl Extension Library

Function

Description

curl:close

Close an open connection. Further operations cannot be performed over the connection. See curl:close.

curl:open

Open a connection to a remote server, allowing multiple operations over a single connection. See curl:open.

curl:perform

Perform simple transfers using a persistent connection handle provided by curl:open. See curl:perform.

curl:set

Record a set of parameters that persists for the lifespan of a connection. See curl:set.

curl:single

Perform transfer operations without using a persistent connection. See curl:single.



Table 3: Web Services Elements in the libslax curl Extension Library

Element

Description

Syntax

<connect-timeout>

Number of seconds before a connection attempt is considered to have failed.

<connect-timeout> 10;

<content-type>

MIME type for the transfer payload.

<content-type> "mime/type";

<errors>

Control how HTML and XML parsing errors are handled.

See Handling Errors

<fail-on-error>

Indicate that the transfer should fail if any errors, including insignificant ones, are detected.

<fail-on-error>;

<format>

Specify the expected format of returned results, allowing the curl extension to automatically make the content available in the native format. Formats include "html", "name", "text", "url-encoded", and "xml".

<format> "xml";

<header>

Provide additional header fields for the request.

<header name="name"> "value";

<insecure>

Indicate a willingness to tolerate insecure communications operations. Specifically, allow SSL Certs without checking the common name.

<insecure>;

<method>

Method used to transfer data. This controls the HTTP request type, as well as triggering other transfer mechanisms.

Acceptable method names include "get", "post", "delete", "head", "email", "put", and "upload". "get" is the default.

<method> "get";

<param>

Provide additional parameter values for the request. These parameters are typically encoded into the URL.

<param name="x"> "y";

<password>

User's password to use for the transfer.

<password> "password";

<secure>

Request the use of the secure version of a protocol, including HTTPS and FTPS.

<secure>;

<timeout>

Number of seconds before an open connection is considered to have failed.

<timeout> 10;

<upload>

Indicate this is a file upload request.

<upload>;

<url>

Base URL for the request.

<url> "target-url";

<username>

Username to use for the transfer.

<username> "username";

<verbose>

Request detailed debug information about the operations and communication of the transfer.

<verbose>;

Table 4: E-Mail Elements in the libslax curl Extension Library

Element

Description

Syntax

<cc>

"Cc" address for e-mail (SMTP) requests. For multiple addresses, use multiple <cc> elements.

<cc> "cc-user@email.example.com";

<contents>

Contents to be transferred.

<contents> "multi-\nline\ncontents\n";

<from>

"From" address for e-mail (SMTP) requests.

<from> "source-user@email.example.com";

<local>

Local hostname used for e-mail (SMTP) requests.

<local> "local host name";

<server>

Outgoing SMTP server name. Currently, MX records are not processed.

<server> "email-server.example.com";

<subject>

"Subject" field for e-mail (SMTP) requests.

<subject> "email subject string";

<to>

"To" address for e-mail (SMTP) requests. For multiple addresses, use multiple <to> elements.

<to> "to-user@email.example.com";

The libcurl elements closely mimic the options used by the native C libcurl API in libcurl's curl_easy_setopt() function. Once the options are set, a call to curl_easy_perform() performs the requested transfer. For more information about the curl_easy_setopt() function, see http://curl.haxx.se/libcurl/c/curl_easy_setopt.html .

In the libslax curl extension library, the libcurl API options are represented as individual elements. For example, the <url> element is mapped to the CURLOPT_URL option , the <method> element is mapped to the CURLOPT_CUSTOMREQUEST option, and so forth.

These elements can be used in three ways:

  • The curl:single() extension function supports using a set of options in a single transfer operation with no persistent connection handle.

  • The curl:perform() extension function supports using a set of options with a persistent connection handle. The handle is returned from the curl:open() extension function and can be closed with the curl:close() extension function.

  • The curl:set() extension function records a set of options for a connection handle and keeps those options active for the lifetime of the connection. For example, if the script needs to transfer a number of files, it can record the <username> and <password> options and avoid repeating them in every curl:perform() call.

curl:close

The curl:close() extension function closes an open connection. Further operations cannot be performed over the connection once it is closed.

The syntax is:

The argument is the connection handle to close.

curl:open

The curl:open() extension function opens a connection to a remote server, allowing multiple operations over a single connection.

The syntax is:

The returned object is a connection handle that can be passed to curl:perform() or curl:close().

curl:perform

The curl:perform() extension function performs simple transfers using a persistent connection handle provided by curl:open().

The syntax is:

The arguments are the connection handle and a set of option elements. Supported curl extension library elements are defined in Table 3 and Table 4.

The returned object is an XML hierarchy containing the results of the transfer. Table 5 lists the possible elements in the reply, and Table 6 lists the possible elements contained within the <header> element.

Table 5: curl:perform Reply Elements

Element

Contents

<curl-success>

Empty element which Indicates success

<data>

Parsed data

<error>

Error message text, if any

<header>

Parsed header fields

<raw-data>

Raw data from the reply

<raw-headers>

Raw header fields from the reply

<url>

Requested URL

Table 6: curl:perform <header> Elements

Element

Contents

<code>

HTTP reply code

<field>

HTTP reply field (with @name and value)

<message>

HTTP reply message

<version>

HTTP reply version string

The following example shows the <header> element with header fields parsed into <field> elements:

curl:set

The curl:set() extension function records a set of parameters that persist for the lifespan of a connection.

The syntax is:

The arguments are the connection handle and a set of option elements. Supported curl extension library elements are defined in Table 3 and Table 4.

curl:single

The curl:single() extension function performs transfer operations without using a persistent connection.

The syntax is:

The returned object is identical in structure to the one returned by curl:perform(). Refer to curl:perform for additional information.

Supported Format Elements

Starting with version 1.2 of the SLAX language, which is supported in Junos OS Release 14.2 and later releases, the format element supports two new formats in addition to "html", "text", and "xml": "name" and "url-encoded". The "name" encoding is used for name=value pairs that are separated by newlines, whereas the "url-encoded" encoding is used when the name=value pairs are separated by an ampersand (&).

The parsed data is returned in the <data> element, using <name> elements. In the following example, format is set to "url-encoded":

curl Examples

The following examples show SLAX version 1.1 scripts that use the libslax curl extension library functions to perform operations.

The following SLAX script performs a simple GET operation to retrieve a web page. The script specifies the header field for the HTTP header and a parameter that is incorporated into the requested URL.

The following SLAX script takes a username and password and uses the Google login services to translate them into an "Authorization" string:

The following SLAX script sends an e-mail by way of a server, which is provided as a parameter:

Handling Errors

Starting with version 1.2 of the SLAX language, which is supported in Junos OS Release 14.2 and later releases, you can use the <errors> element to control the handling of HTML and XML parsing errors. The default behavior is to display errors in the standard error output stream (stderr). By supplying different values for the <errors> element, you can also choose to ignore, log, or record the error. Table 7 lists the values that you can use for the errors element.

Table 7: Error Elements

Value

Special Behavior

default

Errors are displayed on stderr

ignore

Errors are discarded

log

Errors are logged (via slaxLog())

record

Errors are recorded

When the value of <errors> is set to "record", all errors appear in a string under the <errors> element in the XML node (as returned, for example by curl:perform). If no errors are generated, the <errors> element is not present, which can be used as a test for errors.

libslax db Extension Library

The libslax db extension library, which is supported in Junos OS Release 17.4R1 and later, provides a way for SLAX scripts to store, manipulate, retrieve and delete data stored in a database. To use functions from the db extension library in SLAX scripts, include the namespace statement for that library in the script.

Table 8 summarizes the functions that are available in the db extension library. For examples and additional information about the db extension functions, see db Extension Functions.

Table 8: Functions in the libslax db Extension Library

Function

Description

db:close()

Close the database connection and free all the structures associated with previous operations performed on this handle.

db:create()

Create a collection in the database associated with the open database handle using the given field information.

db:delete()

Delete instances in a collection that match the given conditions in the database associated with the open database handle.

db:fetch()

Fetch a result instance using the cursor returned from a db:find() or db:query call.

db:find()

Return a cursor to the result set for instances matching the given conditions. db:fetch() must be used to retrieve each of the result instances.

db:find-and-fetch()

Find and read all the instances matching the given conditions.

db:insert()

Insert data into a collection in the database associated with the open database handle.

db:open()

Open a database connection using the provided options, which include the back-end database engine and the database name.

db:query()

Run a custom query.

db:update()

Update a set of instances matching the given conditions with the provided instance.

Table 9 summarizes the elements that can be used in the options and data of db extensions functions. For examples and additional information about db elements, see db Elements.

Table 9: Elements in the db Extension Library

Element

Description

Example

<collection>

Specify the data collection on which to perform operations. This corresponds to a SQL database table.

<collection> "employee";

<condition>

Specify a condition that must be satisfied when operating with data instances from the datastore. This forms the condition used with the WHERE clause when operating with a SQL datastore. Mandatory elements include:

  • <selector>—Name of the field to which this condition applies

  • <operator>–Comparison or logical operator (<, >, <=, >=, =, LIKE, IN, NOT)

  • <value>—Value used with the operator on this field

<condition> {
    <selector> "id;
    <operator> "in";
    <value> "(1, 10)";
}

<conditions>

Specify multiple conditions with <and> or <or> as parent nodes.

<conditions> {
    <and> {
        <condition> {
            ... /* c1 */
        } 
        <condition> {
            ... /* c2 */
        } 
        <or> {
            <condition> {
                ... /* c3 */
            }
            <condition> {
                ... /* c4 */
            }
        }
    }
}

<database>

Specify the name of the database on which to operate.

<database> "test.db";

<engine>

Specify the back-end database engine that is used to store and access data.

<engine> "sqlite";

<field>

Define the metadata for each field in the collection.

<field> {
    <name> "name";
    <type> "integer";
    <primary>;        
}

<fields>

Specify metadata about fields in a collection using <field> child elements.

<fields> {
    <field> {
        ...
    }
}

<instance>

Represent a single instance in a collection when inserting or manipulating data in the datastore. The element contains fields and their corresponding values in that record.

<instance> {
    <id> 5;
    <name> "John";
}

<instances>

Define multiple instances in a collection when inserting or manipulating data in the datastore.

<instances> {
    <instance> {
        ...
        ...
    }
    ...
}

<limit>

Limit the number of instances that a result can contain.

<limit> 10;

<result>

Output node returned from most of the db extension functions. This node contains a <status> element and can contain one or more <instance> elements.

<result> {
    <status> {
        <ok>
    }
}

<retrieve>

Specify only the fields that should appear as part of the result set when querying the datastore.

<retrieve> {
    <id>;
    <name>;
}

<skip>

Skip over a specified number of instances in the result set before returning to the user.

<skip> 5;

<sort>

Specify the fields and the order by which the result set must be sorted.

Specify the fields by including the <by> element, and specify the sort order by setting the value of <order> to "asc" (ascending) or "desc" (descending).

<sort> {
    <by> "id";
    <by> "age";
    <order> "desc";
}

libslax os Extension Library

The libslax os extension library provides a set of functions to invoke operating system-related operations on the local host. To use functions from the os extension library in SLAX scripts, include the namespace statement for that library in the script.

Table 10 summarizes the functions that are available in the os extension library. The return value of many os extension functions consists of a set of zero or more error nodes. Each node can contain an <error> element with additional child elements. For examples and additional information about os extension functions, see os Extension Functions.

Table 10: Functions in the libslax os Extension Library

Function

Description

First Supported Junos OS Release

os:chmod

Change the permissions of one or more files.

17.4

os:chown

Change the file owner and group for one or more files.

17.4

os:exit-code

Set the exit code for the process running the script.

14.1

os:mkdir

Create a new directory with the specified name, path, and permissions.

The <create> option, which returns an error if the last element of the path exists, is supported starting in Junos OS Release 17.4R1.

14.1

os:remove

Delete a file or empty directory.

17.4

os:stat

Return information about files and directories in a node-set of <entry> elements, which contain details about each file.

14.1

os:user-info

Return a <user-info> element with information about the user running the script.

17.4

libslax xutil Extension Library

The libslax xutil extension library contains functions that convert between strings and XML node sets. To incorporate functions from the xutil extension library into SLAX scripts, include the namespace statement for that library in the script.

Call the xutil extension functions using the xutil prefix and the function name. Table 11 lists the functions available in the xutil extension library, which are supported in SLAX 1.1 and later scripts. For examples and additional information about xutil extension functions, see xutil Extension Functions.

Table 11: Functions in the libslax xutil Extension Library

Function and Arguments

Description

First Supported Junos OS Release

xutil:json-to-xml(string)

Convert a string containing JSON data into the native representation of that data in XML.

14.2

xutil:max-call-depth(number)

Limit the depth of recursive calls. The default limit is 3000.

14.1

xutil:string-to-xml(string+)

Convert a string containing XML data into the native representation of that data.

12.2

xutil:xml-to-json(node-set+)

Convert XML data into a string containing JSON data. This function encodes tags as JSON objects inside a string.

14.2

xutil:xml-to-string(node-set+)

Convert XML data into a string.

12.2