Networks and ports
Let a sandbox reach out to the network, and reach services running in it through its ports.
Traffic crosses a sandbox in two directions, set separately:
- Network is the way out: connections the guest opens, such as
apk addor an API call. - Ports connect the sandbox and your machine, the one the client runs on, each on one side: a port in the sandbox is a service listening in the guest, such as a web server or a database, and a port on local is a service on your machine the guest connects to, such as a browser’s debugging port.
Both are set when the sandbox is created.
Network
network is on by default.
The guest reaches public addresses, but not this host’s loopback or private addresses.
Pass network=False to create_sandbox to block its outbound connections and name lookups, for code that should not talk to anything.
sandbox = await client.create_sandbox("alpine:latest", network=False)const sandbox = await client.createSandbox('alpine:latest', { network: false })let sandbox = client .create_sandbox(&SandboxCreateArgs::new("alpine:latest").network(false)) .await?;Ports
A port carries plain TCP, so it reaches any service that listens on one: a web server, SSH, a VNC desktop, a database, or your own protocol. VirtX passes the bytes through without looking at them.
Each port is on one side: on="sandbox", the default, or on="local".
A port is its side and its number, so 8080 in the sandbox and 8080 on local are two ports, and a sandbox can have both.
Either is forwarded by a PortForwarder, and its local end, forwarder.local, is the address on your machine it connects: where you reach a port in the sandbox, or what the sandbox reaches through a port on local.
A port in the sandbox
- Pass
portstocreate_sandboxto open those ports in the sandbox. - Each one comes back in
sandbox.ports. PortForwarder.opentakes the sandbox and the port, and answers once it is open, with a local address, such as127.0.0.1:54123, that any TCP client can connect to. Give itlocal="127.0.0.1:8000"to have it listen at an address of your choosing.
How the forwarding works depends on where the server runs:
- A server on your machine, started with
Client.spawn, already listens on a local address for each port, the port’surl, so the forwarder just gives you that address, unless you ask for another. - A server over HTTP is reached through a WebSocket.
The forwarder listens on a local port, and opens a WebSocket to
/sandboxes/{id}/ports/{port}for each connection made to it, with the client’s credentials. The server passes the bytes between that WebSocket and the port in the sandbox.
Because everything goes through the server’s own HTTP address, the server’s machine needs no other port open.
A sandbox found again with get_sandbox, list_sandbox or find_sandbox, from this program or another, forwards its ports as the one create_sandbox answered does.
In the example below, the sandbox opens port 8000 and runs an HTTP server on it, and the forwarder makes it reachable at a local address that a browser or curl can open:
from virtx import PortForwarder
sandbox = await client.create_sandbox("alpine:latest", ports=[8000])await sandbox.exec(["httpd", "-f", "-p", "8000"]) # started, left running
with await PortForwarder.open(sandbox, 8000) as forwarder: print(f"http://{forwarder.local}")const { PortForwarder } = require('@brekkylab/virtx')
const sandbox = await client.createSandbox('alpine:latest', { ports: [8000] })await sandbox.exec(['httpd', '-f', '-p', '8000']) // started, left running
const forwarder = await PortForwarder.open(sandbox, 8000)console.log(`http://${forwarder.local}`)forwarder.close()let sandbox = client .create_sandbox(&SandboxCreateArgs::new("alpine:latest").port(8000)) .await?;sandbox.exec(&SandboxExecArgs::new(["httpd", "-f", "-p", "8000"])).await?; // started, left running
let forwarder = PortForwarder::open(&sandbox, 8000, PortSide::Sandbox, None).await?;println!("http://{}", forwarder.local());drop(forwarder);Each entry of sandbox.ports names its port, its side, on, and its label, in the order they were asked for.
A port given twice on one side, or port 0, is refused.
A connection made while nothing listens on the port in the guest is closed at once, as a closed port’s would be: start the service before connecting.
Through a server over HTTP, the forwarder says what it saw: a connection whose WebSocket is refused, or closed before the port sent a byte, with the reason the server gave if it gave one, is kept as the forwarder’s last error, and logged as a warning that names the port and what the server answered.
A port that took the connection and closed it without a word ends the same way, so the message says what happened to the connection, not what runs in the sandbox.
Read it after a connection dies with forwarder.last_error in Python, forwarder.lastError in Node.js and forwarder.last_error() in Rust: an error whose message names the port, with the status the server refused the WebSocket with, if it did.
It is the last failure, not whether the port is reached now: it is none until a connection fails, and none again once a later connection reaches the port, so a program that retries while its service starts reads none once one gets through.
The warning goes to the virtx logger in Python, as a VirtxWarning through process.emitWarning in Node.js, and to the log crate under the target virtx in Rust.
Ports are given only when the sandbox is created, and stay until it is removed. Closing a forwarder stops forwarding on this machine; the port in the sandbox stays open, and another forwarder can reach it again.
A server on this machine answers each port with a loopback address already, which a TCP client can also reach as it is.
A server over HTTP answers none, so use a PortForwarder either way.
A port on local
A port on local is the other way round: a process in the sandbox reaches a TCP port on your machine, such as a browser’s debugging port or adb’s server, while the service stays where it is.
- Pass it in
portswithon="local". Inside the sandbox, it is reached at10.0.2.2:<port>. PortForwarder.openwithon="local"takes the sandbox and the port, and carries each connection a process makes to it to its local end,127.0.0.1:<port>on your machine or thehost:portyou give it aslocal, for as long as you hold the forwarder.
It is carried through a WebSocket, over stdio and over HTTP alike, as a port in the sandbox is.
The forwarder keeps one open to /sandboxes/{id}/client-ports/{port}.
When a process connects, the server tells the forwarder over it, and the forwarder connects to its local end and carries the bytes; it opens another WebSocket at once for the next connection.
The process’s connect waits until the local end is reached, and succeeds then.
It is refused, as one to a port nothing listens on is, when no forwarder is open, when the local end is not reached, or when no forwarder takes it within a few seconds.
10.0.2.2 at a port the sandbox was not made with on local is refused too: it never reaches the server’s own network.
A port on local, like a port in the sandbox, does not need network.
In the example below, the sandbox has no network, and reads what a browser started on your machine with --remote-debugging-port=9222 says about itself:
from virtx import PortForwarder, PortSpec
sandbox = await client.create_sandbox( "alpine:latest", network=False, ports=[PortSpec(9222, on="local")])
async with await PortForwarder.open(sandbox, 9222, on="local"): await sandbox.exec(["wget", "-qO-", "http://10.0.2.2:9222/json/version"]).complete(print=True)const { PortForwarder } = require('@brekkylab/virtx')
const sandbox = await client.createSandbox('alpine:latest', { network: false, ports: [{ port: 9222, on: 'local' }],})
const forwarder = await PortForwarder.open(sandbox, 9222, { on: 'local' })await sandbox.exec(['wget', '-qO-', 'http://10.0.2.2:9222/json/version']).complete({ print: true })forwarder.close()let cdp = PortSpec::new(9222).on(PortSide::Local);let sandbox = client .create_sandbox(&SandboxCreateArgs::new("alpine:latest").network(false).port(cdp)) .await?;
let forwarder = PortForwarder::open(&sandbox, 9222, PortSide::Local, None).await?;let fetch = ["wget", "-qO-", "http://10.0.2.2:9222/json/version"];sandbox.exec(&SandboxExecArgs::new(fetch)).complete(true).await?;drop(forwarder);PortForwarder.open answers once the port is taken, so a process started after it reaches the port at once.
A port the sandbox was not made with on local is refused with 404.
To carry the connections somewhere else than 127.0.0.1:<port>, such as a device on your network, give the local end, host:port.
The sandbox still sees the port it was made with:
forwarder = await PortForwarder.open(sandbox, 9222, on="local", local="192.168.0.20:9222")const forwarder = await PortForwarder.open(sandbox, 9222, { on: 'local', local: '192.168.0.20:9222' })let forwarder = PortForwarder::open(&sandbox, 9222, PortSide::Local, Some("192.168.0.20:9222")).await?;The forwarder works for any sandbox with the port, made by this program or found again with get_sandbox, find_sandbox or list_sandbox, and several forwarders, of one program or of several, may take a port at once: each connection goes to one of them.
Closing the forwarder, or dropping it in Rust, lets the port go, and closes the connections it carries.
It also ends once the sandbox is removed: wait_closed() waits for that and answers why, a 404 once the sandbox is gone (waitClosed() in Node.js).
What fails on the way, such as a local end not reached, is its last error and logged as a warning, as a port in the sandbox’s failures are.
A port on local gives the sandbox’s processes whatever the program behind it gives: a browser’s debugging port reaches everything that browser is signed in to, and adb’s server reaches the device.
Hand it only a port you would let that code use.
Anyone who can reach the sandbox, any member of its project, can open a forwarder for its port too, and the connections are shared out among every forwarder open: one on their machine would get some of them.
For uses of each, see Driving your browser from a sandbox and Driving an Android device from a sandbox.
What a port is for
A port in ports is a number, a port in the sandbox, or a spec with its side and a label of up to 128 characters saying what it is for.
The label comes back with the port wherever the sandbox is found again, so it is what tells its ports apart there:
from virtx import PortSpec
sandbox = await client.create_sandbox( "node:22", ports=[PortSpec(5173, label="dev server")],)
found = await client.get_sandbox(sandbox.id)print(found.ports[0].label) # dev serverconst sandbox = await client.createSandbox('node:22', { ports: [{ port: 5173, label: 'dev server' }],})
const found = await client.getSandbox(sandbox.id)console.log(found.ports[0].label) // dev serverlet dev_server = PortSpec::new(5173).label("dev server");let sandbox = client .create_sandbox(&SandboxCreateArgs::new("node:22").port(dev_server)) .await?;
let found = client.get_sandbox(sandbox.id()).await?;println!("{:?}", found.info().ports[0].label); // Some("dev server")Troubleshooting
-
400,invalid,ports: … is not a port, or is given twiceCause: Port
0, or a port listed twice on one side.Fix: List each port once per side, from 1 to 65535.
-
400,invalid,ports: …'s label is past 128 charactersCause: The label is too long.
Fix: Shorten it to 128 characters.
-
404fromPortForwarder.openwithon="local"Cause: The sandbox wasn’t made with that port on local.
Fix: Create the sandbox with the port in
ports, asPortSpec(port, on="local"). -
A connection closes at once, and the forwarder’s last error is set
Cause: Nothing listens on the port in the sandbox yet, or, for a port on local, nothing listens at the forwarder’s local end.
Fix: Start the service first, then connect again.
Next
- Running commands: start the service a port reaches.
- Driving your browser from a sandbox: use a port on local to give an agent your browser.