Network

This document describes the Network library available in the JavaScript environment for app serivices.

Table of content

Object Network
Functions socket
server
localAddresses
macAddress
socketContext

Object Socket
Functions connect
send
recv
close
onbind
onconnect
onrecv
onsend
onclose
localAddress
localPort

Object Server
Functions close
onbind
onsocket
onclose
localAddress
localPort

Object SocketContext
Functions setCertificate

Examples A simple telnet server

Network

socket
Creates a socket. Use this function for

Parameters

string protocol The protocol to be used. Supported values are "tcp", "tls" and "udp".
string addr Optional. The address of the local network interface that should be used for the socket. If not specified, the socket will be bound to all interfaces.
unsigned port Optional. The local port that shall be used for the socket. If not specified, the socket will be bound to any free port. In that case you can find out the actual port using the the onbind callback.
bool ipv6 Optional, defaulting to false. If true, the socket will use IPv6, otherwise it will use IPv4.
string socketContextId Optional, only used for TLS sockets. The ID of the SocketContext to be used. If not specified, the default context is used.

Return value

Socket The created socket object.
// Establish an outgoing TCP connection, and close it again.
Network.socket("tcp")
    .connect("10.0.0.1", 80)
    .onconnect(function(socket) {
        socket.close();
    });
// Establish an outgoing TLS connection, and close it again.
Network.socket("tcp")
    .connect("10.0.0.1", 443)
    .onconnect(function(socket) {
        socket.close();
    });
// Receive datagrams on UDP port 8000 and send them back to the original sender
Network.socket("udp", null, "8000")
    .onbind(function(socket, addr, port) {
        socket.recv(1024, true);
    });
    .onrecv(function(socket, data, addr, port) {
        socket.send(data, addr, port);
        socket.recv(1024, true);
    });
server
Creates a server that receives incoming connections. Use this function for

Parameters

string protocol The protocol to be used. Supported values are "tcp" and "tls".
string addr Optional. The address of the local network interface on which the server should listen. If not specified, the server will listen on all interfaces.
unsigned port Optional. The local port that shall be used for the server. If not specified, the server will be bound to any free port. In that case you can find out the actual port using the the onbind callback.
bool ipv6 Optional, defaulting to false. If true, the server will use IPv6, otherwise it will use IPv4.
string socketContextId Optional, only used for TLS servers. The ID of the SocketContext to be used. If not specified, the default context is used.

Return value

Server The created server object.
// TCP server listening on port 80 that rejects incoming connections right away
Network.server("tcp", null, 80)
    .onsocket(function(server, socket, addr, port) {
        socket.close();
    });
// TLS server listening on port 443 that rejects incoming connections right away
Network.server("tls", null, 443)
    .onsocket(function(server, socket, addr, port) {
        socket.close();
    });
localAddresses
Returns an all local IP addresses.

Return value

[addrInfo] An array containing information about all local IP addresses.
Each addrInfo object has the parameters addr and ipv6.
Example: [{ addr: "192.168.0.1", ipv6: false }, { addr: "10.0.0.1", ipv6: false }]
// Write the addresses of the local network interfaces to the log
var addrs = Network.localAddresses();
log("local addresses:");
addrs.forEach(function(a) {
    log("   " + a.addr);
});
// Bind a TLS server on the first interface
var addrs = Network.localAddresses();

if (addrs.length) {
    Network.server("tls", addrs[0].addr, 443, addrs[0].ipv6)
        .onsocket(function(server, socket, addr, port) {
            // handle connection using the socket object
        });
}
macAddress
Returns the MAC address of the app platform.

Return value

string A hexstring containing the MAC address.
Example: "029033410fcb"
// Write the MAC address of the AP to the log
var mac = Network.macAddress();
log("mac address: " + mac);
socketContext
TLS sockets use a context that includes the certificates to be used and a session cache for resuming sessions. There is a default context that includes a self-signed cerificate that is used for all TLS sockets by default.
Use this function
This function returns a socket context for a given ID. If the ID does not exist yet, the context is explicitly created.

Parameters

string socketContextId Optional. The ID of the context.
If not defined, the default context is returned.
If no context for the given ID exists, it is explicitly created.

Return value

SocketContextThe socket context.
// change the default certificate for all TLS connections
Network.socketContext().setCertificate(null, customCertPemFile);
// LDAPS client socket using a separate context with a specific certificate
Network.socketContext("ldaps").setCertificate("client", ldapsCertPemFile);

Network.socket("tls", null, 0, false, "ldaps")
    .connect("10.0.0.1", 389)
    .onconnect(function(socket) {
        // do something with the connection
    });

Socket

This object is used to handle TCP, TLS and UDP communication. Use Network.socket to create a socket.

connect
This function is used to establish a connection on TCP and TLS client sockets. When the socket has been connected the onconnect callback is triggered.

Parameters

string addrThe IP address of the server.
string portThe TCP port of the server

Return value

SocketA reference to the object itself. Useful for method chaining.
// Establish a TCP connection to 10.0.0.1:80
Network.socket("tcp")
    .connect("10.0.0.1", 80)
    .onconnect(function(socket) {
        // do something with the connection
    });
send
Sends data on the socket.

Parameters

Uint8Array dataThe data to be sent.
string addrOptional, UDP only. The IP address of the remote endpoint.
unsigned portOptional, UDP only. The UDP port of the remote endpoint.

Return value

SocketA reference to the object itself. Useful for method chaining.
// Send a UDP datagram containing a null byte to 10.0.0.1:1000
socket.send(new Uint8Array([ 0x00 ]), "10.0.0.1", 1000);
// Send a HTTP request on a TCP connection
var request = Encoding.stringToBin(
    "GET / HTTP/1.1\r\n" +
    "Host: www.example.com\r\n" +
    "Connection: close\r\n" +
    "\r\n"
);
            
socket.send(request);
recv
Tells the socket to receive the next chunk of data. The onrecv callback will be invoked when the data has been received.

Parameters

unsigned bytesThe (maximum) number of bytes to receive.
bool partial Optional, defaulting to false.
If false, the onrecv will only be triggered if the requested number of bytes has been fully received.
If true, the onrecv will be triggered if the requested number of bytes or less has been received.

Return value

SocketA reference to the object itself. Useful for method chaining.
 // receive excactly 5 bytes
socket.recv(5)
    .onrecv(function(socket, data) {
        // data.length == 5
    });
 // receive up to 1024 bytes
socket.recv(1024, true)
    .onrecv(function(socket, data) {
        // data.length <= 1024
    });
close
Closes the socket.

Return value

SocketA reference to the object itself. Useful for method chaining.
socket.close();
onbind
Sets a callback function that is invoked when the socket is bound to a network interface. Optional.

Parameters

function callback(Socket socket, string addr, unsigned port)A callback that will be called when the socket is bound. It can be used to determine the local address and port of the socket.

Return value

SocketA reference to the object itself. Useful for method chaining.
 // Create a UDP socket and write the bound port to the log
Network.socket("udp")
    .onbind(function(socket, addr, port) {
        log("socket bound to port UDP/" + port);
    });
onconnect
Sets a callback function that is invoked when a TCP or TLS connection has been established after calling connect. Optional.

Parameters

function callback(Socket socket, string addr, unsigned port)A callback that will be invoked when the socket is connected. The additional parameters represent the address and port of the remote endpoint.

Return value

SocketA reference to the object itself. Useful for method chaining.
// Establish a TCP connection to 10.0.0.1:80
Network.socket("tcp")
    .connect("10.0.0.1", 80)
    .onconnect(function(socket, addr, port) {
        log("connected to " + addr + ":" + port);
    });
onrecv
Sets a callback function that is invoked when data has been received after calling recv. Optional.

Parameters

function callback(Socket socket, Uint8Array data, string addr, unsigned port)A callback that will be invoked when data has been received. Addr and port are only set for UDP sockets.

Return value

SocketA reference to the object itself. Useful for method chaining.
// receive data and write it to the log
socket.recv(1024, true)
    .onrecv(function(socket, data) {
        log("onrecv:");
        hexdump(data);
        socket.recv(1024, true);
    });
// Receive datagrams on UDP port 8000 and send them back to the original sender
Network.socket("udp", null, "8000")
    .onbind(function(socket, addr, port) {
        socket.recv(1024, true);
    });
    .onrecv(function(socket, data, addr, port) {
        socket.send(data, addr, port);
        socket.recv(1024, true);
    });
onsend
Sets a callback function that is invoked when data has been completely sent after calling send. This function is useful for implementing flow-control. Optional.

Parameters

function callback(Socket socket)A callback that will be invoked when data has been sent.

Return value

SocketA reference to the object itself. Useful for method chaining.
socket.send(new Uint8Array([0]))
    .onsend(function(socket, data) {
        // data has been sent, ready to send the next chunk
    });
onclose
Sets a callback function that is invoked when the socket has been closed. After the callback the Socket object is deleted implicitly and can't be used anymore. Optional.

Parameters

function callback(Socket socket, error) A callback that will be invoked when the socket has been closed.
error is a string representation of shutdownreason_t or null.

Return value

SocketA reference to the object itself. Useful for method chaining.
// Establish an outgoing TCP connection, and close it again.
Network.socket("tcp")
    .connect("10.0.0.1", 80)
    .onconnect(function(socket) {
        socket.close();
    })
    .onclose(function(socket, error) {
        log("socket closed");
        if (error) log("error=" + error);
    });
localAddress
Returns the local address the socket is bound to.

Return value

stringThe IP address the socket is bound to.
Network.socket("tcp")
    .connect("10.0.0.1", 80)
    .onconnect(function(socket) {
        log("local " + socket.localAddress() + ":" + socket.localPort());
    });
localPort
Returns the local port the socket is bound to.

Return value

unsignedThe TCP or UDP port the socket is bound to.
Network.socket("tcp")
    .connect("10.0.0.1", 80)
    .onconnect(function(socket) {
        log("local " + socket.localAddress() + ":" + socket.localPort());
    });

Server

This object represents a TCP or TLS server. Use Network.server to create it.

The server opens a TCP port and listens on it for incoming connections. On each incoming connection the onsocket callback is invoked. The callback hands a Socket object to the application that represents the individual connection.

close
Stop listening on the server port and delete the object.

Return value

ServerA reference to the object itself. Useful for method chaining.
// create a TCP server and close it right away
Network.server("tcp").close();
onbind
Sets a callback function that is invoked when the server is bound to a port. Optional.

Parameters

function callback(Server server, string addr, unsigned port)A callback that will be called when the server is bound. It can be used to determine the local address and port of the socket.

Return value

ServerA reference to the object itself. Useful for method chaining.
// Create a TCP server and write the listen port to the log
Network.server("tcp")
    .onbind(function(socket, addr, port) {
        log("server bound to port TCP/" + port);
    });
onsocket

Sets a callback function that is invoked on incoming connections. Optional.
The callback passes a Socket object to the application, that represents the incoming connection.

Usage:

Parameters

function callback(Server server, Socket socket, string addr, unsigned port)A callback that will be invoked when the socket is connected.

Return value

ServerA reference to the object itself. Useful for method chaining.
// TCP server that only accepts local connections
Network.server("tcp", "127.0.0.1", 1000)
    .onsocket(function(server, socket, addr, port) {
        if (addr != "127.0.0.1") socket.close();
        else handleConnection(socket);
    });

function handleConnection(socket) {
    // justs send "Bye!" and close again
    socket.onconnect(function(socket) {
        socket.send(Encoding.stringToBin("Bye!"));
    })
    .onsend(function(socket) {
        socket.close();
    });
}
onclose
Sets a callback function that is invoked when the server port has been closed. After the callback the server object is deleted implicitly and can't be used anymore. Optional.

Parameters

function callback(Server server, error) A callback that will be invoked when the server has been closed.
error is a string representation of shutdownreason_t or null.

Return value

ServerA reference to the object itself. Useful for method chaining.
// Write something to the log if the server has been closed.
Network.server("tcp", null, 1000)
    .onsocket(function(server, socket, addr, port) {
        // handle incoming connections, e.g. reject
        socket.close();
    })
    .onclose(function(socket, error) {
        log("server closed");
        if (error) log("error=" + error);
    });
localAddress
Returns the local address the server is bound to.

Return value

stringThe IP address the server is bound to.
log("server bound to " + socket.localAddress() + ":" + socket.localPort());
localPort
Returns the local port the server is bound to.

Return value

unsignedThe TCP or UDP port the server is bound to.
log("server bound to " + socket.localAddress() + ":" + socket.localPort());

SocketContext

This object encapsulates the context for TLS sockets. It can be created or accessed using Network.socketContext.

It holds the following data:

Socket contexts are referenced by a string ID. They can be assigned to a Server or Socket using that ID, in the Network.server and Network.socket functions.

There is a default context with the ID undefined, that is used for all servers or sockets unless a specific context is specified.

setCertificate
Sets the certificate to be used.

Parameters

string type "client" - sets the certificate for TLS connections in the client role.
"server" - sets the certificate for TLS connections in the server role.
null - sets the same certificate for both roles.
Uint8Array pemData A certificate chain and the corresponding private key in PEM format.
string hostName The host name of the endpoint.
(currently unused by the underlying implementation)

Return value

SocketContextA reference to the object itself. Useful for method chaining.
// change the default certificate for TLS connections
Network.socketContext().setCertificate(null, customCertPemFile);
// LDAPS client socket using a separate context with a specific certificate
Network.socketContext("ldaps").setCertificate("client", ldapsCertPemFile);

Network.socket("tls", null, 0, false, "ldaps")
    .connect("10.0.0.1", 389)
    .onconnect(function(socket) {
        // do something with the connection
    });

Examples

A simple telnet server

In this example we create a very simple telnet server that implements a number of (useless) commands:

For that we create a TCP server listening on port 23 that handles the telnet connections.

// Server
Network.server("tcp", null, 23)
    .onsocket(function(server, socket) {
        telnetConnection(socket);
    });

// Telnet connection
function telnetConnection(socket) {
    var command = "";
    var skip = 0;
    var closed = false;

    socket.onconnect(function(socket) {
            socket.send(Encoding.stringToBin("\Hello!\r\n\r\n> "));
            socket.recv(1);
        })
        .onrecv(function(socket, data) {
            parse(data);
            if (!closed) socket.recv(1);
        })
        .onsend(function(socket) {
            if (closed) socket.close();
        });

    function parse(data) {
        if (data[0] == 255) skip = 3;
        
        if (skip > 0) {
            // just ignore all telnet messages
            skip--;
        }
        else if (data[0] > 31 && data[0] < 127) {
            // add text to command
            command += Encoding.binToString(data);
        }
        else if (data[0] == 13) {
            // execute command on return
            execute();
        }
    }

    function execute() {
        if (command == "random") {
            socket.send(Encoding.stringToBin("" + Random.dword() + "\r\n"));
        }
        else if (command == "exit") {
            socket.send(Encoding.stringToBin("Bye!\r\n\r\n"));
            closed = true;
        }
        else {
            socket.send(Encoding.stringToBin("unknown command\r\n"));
        }

        command = "";
        if (!closed) socket.send(Encoding.stringToBin("\r\n> "));
    }
}

Now we can use a telnet client to connect to our server for testing.

telnet> open 192.168.0.220
Trying 192.168.0.220...
Connected to 192.168.0.220.
Escape character is '^]'.
Hello!

> random
535786860

> random
67404851

> ls -lha
unknown command

> exit
Bye!

Connection closed by foreign host.