Standard library · Network

net.tun

Full device VPN mode: a tun device on Linux, macOS and Windows, split routes, DNS capture and a NAT that hands every TCP connection to a net.tunnel dialer.

import net.tun

net.tun gives a VPN app full device mode: every application on the machine goes through the tunnel, not only the ones that honour the system proxy. It creates a layer 3 tunnel device (/dev/net/tun on Linux, utun on macOS, a Wintun adapter on Windows), points the default routes at it and turns the IP packets that arrive into ordinary TCP connections, which it hands to any net.tunnel dialer: a router with direct, proxy and block rules, a VLESS, VMess, Trojan or Shadowsocks dialer, or a chain.

It has no TCP stack of its own. Like the system stack of sing-tun, it rewrites the addresses of each TCP packet so the connection lands on a local listener, and the kernel does all of TCP. Only IP and TCP headers are touched, with incremental checksum updates, so throughput stays close to the kernel.

app -> 1.1.1.1:443                        kernel TCP
  |  routes 0.0.0.0/1, 128.0.0.0/1             ^
  v                                            |
tun device -> Nat.Rewrite: 172.19.0.2:10000 -> 172.19.0.1:listener
                                               |
listener accepts, Nat.Lookup(10000) = 1.1.1.1:443, sniff SNI, dialer.Dial(host:443)

Things to know:

  • It needs privileges. Root or CAP_NET_ADMIN on Linux, root on macOS, administrator rights and wintun.dll next to the executable on Windows (download it from wintun.net). Call Available first and show its reason.
  • Exclude your servers. Put the VPN server names or addresses in exclude. They are resolved before the routes change and keep a route through the old gateway. For direct rules use Bypass, which binds to the physical interface.
  • TCP and DNS only. UDP queries to port 53 are answered through the dialer over TCP. Other UDP (QUIC, games, calls) and ICMP are dropped, so browsers fall back to TCP. IPv6 is blocked rather than leaked.
  • Routes never replace the default route. Two /1 routes win over it and Stop removes everything it added. If the process is killed, the Linux and Windows device disappears with it; host routes for excluded servers stay until reboot.
  • Linux is tested end to end by tools/interop/tun_e2e.sh in a container. The macOS and Windows device code is type checked for every target.

Full device mode in a VPN app

Build the same router dialer you would give a local SOCKS inbound, but use Bypass() for the direct tag so direct traffic leaves through the physical interface instead of looping back into the tunnel. Pass the VPN server in exclude, start the session when the user flips the switch and stop it when they flip it back or the app quits.

import net.tun
import net.tunnel

func start_full_device(proxy: dyn tunnel.Dialer, server: str): tun.Session:
    av := tun.Available()
    if not av.ok:
        println "full device mode is off:", av.reason
        ret tun.Session {}
    end
    rules := tunnel.ParseRules("domain:ir direct\nprivate direct", "proxy")
    mut router := tunnel.NewRouterDialer(rules.router)
    tunnel.RouterDialerAdd(router, "direct", tun.Bypass())
    tunnel.RouterDialerAdd(router, "block", tunnel.Block())
    tunnel.RouterDialerAdd(router, "proxy", proxy)
    mut servers := Vector {} as Vector<str>
    servers.Push(server)
    s := tun.Start(tun.Options { dialer = router, exclude = servers })
    if not s.ok:
        println "could not start:", s.error
    end
    ret s
end

func main():
    s := start_full_device(tunnel.Direct(), "vpn.example.com")
    if s.ok:
        st := tun.SessionStats(s)
        println st.connections, st.dns_queries
        tun.Stop(s)
    end
end

Show Available().reason next to a disabled switch when the process lacks the rights; a desktop app usually starts a small privileged helper for this mode. Read SessionStats on a timer for the traffic counters.

Handling packets yourself

OpenDevice gives a bare device with no address, routes or stack: each Read returns one IP packet and each Write injects one. Combine it with Parse, Nat and the packet builders to write your own stack, a packet logger or a test harness. Configure the address and routes yourself, or look at what BuildPlan would run.

import mem
import sync
import net.tun

func main():
    dev := tun.OpenDevice("salam0", 1500)
    if not dev.ok:
        println dev.error
        ret
    end
    nat := tun.NewNat("172.19.0.1", "172.19.0.2", 7000, 0)
    buf := mem.Allocate(65536 as u64)
    repeat 1000:
        n := dev.Read(buf, 65536, 200)
        if n > 0:
            info := tun.Parse(buf, n)
            println info.src, info.sport, "->", info.dst, info.dport
            if nat.Rewrite(buf, n, sync.NowMs()) == tun.action_reply:
                _w := dev.Write(buf, n)
            end
        end
    end
    mem.Free(buf)
    tun.FreeNat(nat)
    dev.Close()
end

Types

Options

struct Options
Settings for Start.
NameTypeDescription
namestr = ""Interface name. Empty picks salamtun, or the next free utunN on macOS.
addressstr = "172.19.0.1"IPv4 address of the device. The next address must be in the same subnet.
prefixint = 30Prefix length of the device subnet, 30 by default.
mtuint = 1500MTU of the device.
dialerdyn tunnel.DialerWhere captured connections go, usually a net.tunnel router dialer. Without one every connection is refused.
excludeVectorHost names or IPv4 addresses that must keep using the real network, such as the VPN servers. They get host routes through the old gateway, so the dialer does not loop into the tunnel.
auto_routebool = trueAdds the routes. When false only the device and its address are set up.
hijack_dnsbool = trueAnswers every UDP query to port 53 that enters the tunnel, and routes private DNS servers of the machine into the tunnel too.
upstreamstr = "1.1.1.1:53"The DNS server, as host:port, that queries are sent to over TCP through the dialer.
set_system_dnsbool = truePoints the system resolver at the DNS address inside the tunnel (systemd-resolved on Linux, the interface DNS on Windows).
block_ipv6bool = trueStops IPv6 from leaking around the tunnel: unreachable routes on Linux, IPv6 routes into the device on macOS and Windows.
sniffbool = trueReads the first bytes of each connection to find a TLS or HTTP host name, so domain rules of the router work.
sniff_msint = 300How long to wait for those bytes. Protocols where the server speaks first wait this long once.
idle_msint = 600000Idle timeout of a connection in milliseconds.
dial_msint = 10000Connect timeout in milliseconds.
net-tun-Plan.salam
import net.tun

func main():
    gw := tun.ParseLinuxRoutes(
        "Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask\neth0\t00000000\t0101A8C0\t0003\t0\t0\t100\t00000000\n"
    )
    println "linux", gw.ok, gw.ip, gw.iface, gw.index
    mac := tun.ParseMacRoute("    gateway: 10.0.0.1\n  interface: en0\n")
    println "macos", mac.ip, mac.iface
    dns := tun.ParseResolvers("nameserver 192.168.1.1\n")
    println "resolvers", dns.Len(), dns[0]
    println "name ok", tun.ValidName("salamtun"), "next", tun.NextAddress(tun.default_address)
    println "defaults", tun.default_address6, tun.default_upstream
    mut hosts := Vector {} as Vector<str>
    hosts.Push("203.0.113.7")
    opts := tun.Options { name = "salamtun", set_system_dns = false }
    pl := tun.BuildPlan("linux", "salamtun", opts, gw, hosts, dns, "")
    each line in pl.up:
        println "up  ", line
    end
    each line in pl.down:
        println "down", line
    end
    parts := tun.SplitCommand(pl.up[0])
    println "argv", parts.Len(), parts[0]
end
Outputlinux true 192.168.1.1 eth0 0 macos 10.0.0.1 en0 resolvers 1 192.168.1.1 name ok true next 172.19.0.2 defaults fdfe:dcba:9876::1 1.1.1.1:53 up ip addr add 172.19.0.1/30 dev salamtun up ip link set dev salamtun mtu 1500 up up ip route replace 203.0.113.7/32 via 192.168.1.1 dev eth0 onlink up -ip route replace 192.168.1.1/32 dev salamtun up ip route replace 0.0.0.0/1 dev salamtun up ip route replace 128.0.0.0/1 dev salamtun up -ip -6 route replace unreachable ::/1 up -ip -6 route replace unreachable 8000::/1 down -ip route del 203.0.113.7/32 down -ip -6 route del unreachable ::/1 down -ip -6 route del unreachable 8000::/1 argv 6 ip

Gateway

struct Gateway
The default route of the machine: the gateway address and the interface.
NameTypeDescription
okbool = falseFalse when no default route was found.
ipstr = ""The gateway address, empty for a point to point link.
ifacestr = ""The interface name, empty on Windows.
indexint = 0The interface index on Windows, 0 elsewhere.

The example for this item is shown with the ones above: net-tun-Plan.salam

Plan

struct Plan
The commands that set the device up and take it down, as text lines. A line that starts with - may fail.
NameTypeDescription
upVectorCommands run by Start, in order.
downVectorCommands run by Stop.

The example for this item is shown with the ones above: net-tun-Plan.salam

Availability

struct Availability
Whether full device mode can start here, and why not.
NameTypeDescription
okbool = falseTrue when Start can work.
reasonstr = ""Why not, in words an app can show: missing privileges, missing /dev/net/tun, missing wintun.dll.
net-tun-Session.salam
import mem
import net.tun
import net.tunnel

func main():
    av := tun.Available()
    if not av.ok:
        println "full device mode is off:", av.reason
        ret
    end
    println "platform", tun.Platform()
    gw := tun.DefaultGateway()
    println "gateway", gw.ip, gw.iface
    println "resolvers", tun.SystemResolvers().Len()
    mut servers := Vector {} as Vector<str>
    servers.Push("vpn.example.com")
    s := tun.Start(tun.Options { dialer = tunnel.Direct(), exclude = servers })
    if not s.ok:
        println "start failed:", s.error, tun.LastError()
        ret
    end
    println "up", s.name, s.address, "dns", s.dns, tun.Running()
    direct := tun.NewBypassDialer()
    c := direct.Dial(tunnel.NewAddr("example.com", 80))
    println direct.Name(), c.Ok()
    c.Close()
    _d := tun.Bypass()
    st := tun.SessionStats(s)
    println st.packets_in,
        st.packets_out,
        st.connections,
        st.active,
        st.dns_queries,
        st.sniffed,
        st.failed,
        st.dropped,
        st.bytes_up,
        st.bytes_down
    tun.Stop(s)
    dev := tun.OpenDevice("salamtest", 1500)
    if dev.ok:
        buf := mem.Allocate(65536 as u64)
        n := dev.Read(buf, 65536, 100)
        if n > 0:
            _w := dev.Write(buf, n)
        end
        mem.Free(buf)
        dev.Close()
    end
end

Stats

struct Stats
Counters of a running session.
NameTypeDescription
packets_ini64 = 0Packets read from the device.
packets_outi64 = 0Packets written to the device.
droppedi64 = 0Packets dropped: UDP other than DNS, ICMP, fragments, unknown connections.
connectionsi64 = 0TCP connections accepted.
activei64 = 0TCP connections being relayed now.
dns_queriesi64 = 0DNS queries forwarded.
sniffedi64 = 0Connections whose host name was found by sniffing.
failedi64 = 0Dials that failed.
bytes_upi64 = 0Bytes sent by applications.
bytes_downi64 = 0Bytes received by applications.

The example for this item is shown with the ones above: net-tun-Session.salam

Device

struct Device
A layer 3 tunnel device: /dev/net/tun on Linux, utun on macOS, a Wintun adapter on Windows. Each read or write is one IP packet.
NameTypeDescription
okbool = falseTrue when the device is open.
errorstr = ""Why opening failed.
namestr = ""The interface name the system gave the device.
mtuint = 1500MTU asked for.
fdi64 = -1File descriptor on Linux and macOS.
sessionvoid*Wintun session on Windows.
adaptervoid*Wintun adapter on Windows.
eventvoid*Wintun read event on Windows.
scratchvoid*Buffer for the packet header of utun on macOS.

The example for this item is shown with the ones above: net-tun-Session.salam

Read

func Read(buf: void*, max: int, timeout_ms: int): int
Reads one packet, waiting at most timeout_ms. Returns its length, 0 on timeout and a negative number when the device is gone.

Write

func Write(ptr: void*, n: int): int
Writes one packet.

Close

func Close()
Closes the device. On Linux and Windows the interface disappears with it.

BypassDialer

struct BypassDialer
A net.tunnel dialer whose sockets are bound to the physical interface (SO_BINDTODEVICE, IP_BOUND_IF or IP_UNICAST_IF), for the direct route while the tunnel owns the default routes. Domain names are resolved by the system, which means through the tunnel DNS.
NameTypeDescription
gatewayGatewayThe physical gateway and interface, saved before the routes changed.
timeout_msint = 10000Connect timeout in milliseconds.

The example for this item is shown with the ones above: net-tun-Session.salam

Dial

func Dial(target: tunnel.Addr): dyn tunnel.Stream
Connects to an IPv4 target or a name over the physical interface.

Name

func Name(): str
Returns bypass.

Session

struct Session
A running full device session returned by Start.
NameTypeDescription
okbool = falseTrue when the session started.
errorstr = ""Why it did not start.
namestr = ""Interface name.
addressstr = ""Device address.
dnsstr = ""The DNS address inside the tunnel.
idint = 0Session number.

The example for this item is shown with the ones above: net-tun-Session.salam

NatEntry

struct NatEntry
One row of the NAT table: the original source and destination of a TCP connection.
NameTypeDescription
okbool = falseFalse when no connection uses that port.
srcstr = ""The application side address.
sportint = 0The application side port.
dststr = ""The address the application wanted to reach.
dportint = 0The port the application wanted to reach.
net-tun-Nat.salam
import net.tun

func main():
    nat := tun.NewNat("172.19.0.1", "172.19.0.2", 7000, 0)
    out := tun.BuildTcp4(
        "172.19.0.1", 51000, "1.1.1.1", 443, 1 as i64, 0 as i64, tun.tcp_syn, null, 0
    )
    println "forward", nat.Rewrite(out.data, out.len, 0 as i64) == tun.action_reply
    seen := tun.Parse(out.data, out.len)
    println "kernel sees", seen.src, seen.sport, seen.dst, seen.dport
    e := nat.Lookup(seen.sport)
    println "original", e.ok, e.src, e.sport, e.dst, e.dport
    back := tun.BuildTcp4(
        "172.19.0.1",
        nat.Port(),
        "172.19.0.2",
        seen.sport,
        9 as i64,
        2 as i64,
        tun.tcp_syn | tun.tcp_ack,
        null,
        0
    )
    _r := nat.Rewrite(back.data, back.len, 1 as i64)
    app := tun.Parse(back.data, back.len)
    println "app sees", app.src, app.sport, app.dst, app.dport
    dns := tun.BuildUdp4("172.19.0.1", 5353, "172.19.0.2", 53, null, 0)
    println "dns", nat.Rewrite(dns.data, dns.len, 2 as i64) == tun.action_dns
    println "drop", tun.action_drop, "ipv6", tun.action_ipv6
    println "active", nat.Active(), "expired", nat.Sweep(3600000 as i64), "active", nat.Active()
    tun.FreePacket(out)
    tun.FreePacket(back)
    tun.FreePacket(dns)
    tun.FreeNat(nat)
end
Outputforward true kernel sees 172.19.0.2 10000 172.19.0.1 7000 original true 172.19.0.1 51000 1.1.1.1 443 app sees 1.1.1.1 443 172.19.0.1 51000 dns true drop 0 ipv6 3 active 1 expired 1 active 0

Nat

struct Nat
The TCP translation table of the system stack. A connection from the app to dst:dport is rewritten to come from next:nat_port and go to the local listener, so the kernel itself runs TCP; replies get the original addresses back. The same addressing as the system stack of sing-tun.
NameTypeDescription
corevoid*Native state. Create it with NewNat.

The example for this item is shown with the ones above: net-tun-Nat.salam

Rewrite

func Rewrite(ptr: void*, n: int, now_ms: i64): int
Rewrites one packet in place and returns one of the action_ values. now_ms is a clock in milliseconds used for timeouts.

Lookup

func Lookup(nat_port: int): NatEntry
Finds the original addresses of the connection that uses a NAT port. The listener calls it with the peer port of each accepted connection.

Sweep

func Sweep(now_ms: i64): int
Removes idle and closed connections and returns how many were removed.

Active

func Active(): int
Number of connections in the table.

Port

func Port(): int
The port of the local listener.

PacketInfo

struct PacketInfo
What Parse read from one IP packet: version, protocol, addresses, ports, TCP flags and where the payload starts.
NameTypeDescription
validbool = falseFalse when the bytes are not a complete IPv4 or IPv6 packet.
versionint = 04 or 6.
protoint = 0The transport protocol number, for example proto_tcp.
srcstr = ""Source address as text.
dststr = ""Destination address as text.
sportint = 0Source port for TCP and UDP, 0 otherwise.
dportint = 0Destination port for TCP and UDP, 0 otherwise.
flagsint = 0The TCP flag bits, see tcp_syn and the others.
header_lenint = 0Length of the IP header in bytes.
payload_offsetint = 0Offset of the transport payload from the start of the packet.
payload_lenint = 0Length of the transport payload.
totalint = 0Total length of the packet from its header.
fragmentbool = falseTrue for an IPv4 fragment. The stack drops fragments.
net-tun-Packet.salam
import net.tun

func main():
    body := "hi"
    pk := tun.BuildTcp4(
        "172.19.0.1", 40000, "93.184.216.34", 443, 1 as i64, 0 as i64, tun.tcp_syn, body as void*,
        2
    )
    info := tun.Parse(pk.data, pk.len)
    println info.valid,
        info.version,
        info.proto == tun.proto_tcp,
        info.src,
        info.sport,
        info.dst,
        info.dport
    println "syn",
        (info.flags & tun.tcp_syn) != 0,
        "ack",
        (info.flags & tun.tcp_ack) != 0,
        "payload",
        info.payload_len,
        "of",
        info.total
    println "checksums ok", tun.ChecksumsOk(pk.data, pk.len)
    p := pk.data as u8*
    p[8] = 32 as u8
    println "after edit", tun.ChecksumsOk(pk.data, pk.len)
    tun.FinishChecksums(pk.data, pk.len)
    println "after finish", tun.ChecksumsOk(pk.data, pk.len)
    println "header sum", tun.Checksum(pk.data, 20)
    println "rfc 1624", tun.ChecksumAdjust(56623, 21845, 12933)
    udp := tun.BuildUdp4("10.0.0.2", 5000, "10.0.0.1", 53, null, 0)
    u := tun.Parse(udp.data, udp.len)
    println "udp", u.proto == tun.proto_udp, u.header_len, u.payload_offset, u.fragment
    println "other flags", tun.tcp_fin, tun.tcp_rst, tun.tcp_psh, tun.proto_icmp, tun.proto_icmp6
    tun.FreePacket(pk)
    tun.FreePacket(udp)
end
Outputtrue 4 true 172.19.0.1 40000 93.184.216.34 443 syn true ack false payload 2 of 42 checksums ok true after edit false after finish true header sum 0 rfc 1624 0 udp true 20 28 false other flags 1 4 8 1 58

Packet

struct Packet
A packet in native memory: a pointer and a length. Free it with FreePacket.
NameTypeDescription
datavoid*Pointer to the bytes, or null when building failed.
lenint = 0Number of bytes.

The example for this item is shown with the ones above: net-tun-Packet.salam

DnsQuestion

struct DnsQuestion
The first question of a DNS query.
NameTypeDescription
okbool = falseFalse when the bytes are not a DNS query.
idint = 0The query id.
namestr = ""The name asked for, without the final dot.
qtypeint = 0The record type, 1 for A and 28 for AAAA.
net-tun-Sniff.salam
import net.tun

func main():
    req := "GET / HTTP/1.1\r\nHost: Example.com:8080\r\n\r\n"
    println "host", tun.SniffHost(req as void*, req.Len())
    q := tun.BuildDnsQuery(42, "salamlang.ir", 1)
    d := tun.ParseDnsQuery(q.data, q.len)
    println "question", d.ok, d.id, d.name, d.qtype
    tun.FreePacket(q)
end
Outputhost example.com question true 42 salamlang.ir 1

Constants and variables

default_address

const default_address: str = "172.19.0.1"
The default device address, 172.19.0.1. The DNS address inside the tunnel is the next one, 172.19.0.2.

The example for this item is shown with the ones above: net-tun-Plan.salam

default_address6

const default_address6: str = "fdfe:dcba:9876::1"
The IPv6 address given to the device on macOS and Windows so that IPv6 traffic reaches the stack and can be refused.

The example for this item is shown with the ones above: net-tun-Plan.salam

default_upstream

const default_upstream: str = "1.1.1.1:53"
The default DNS server that hijacked queries are forwarded to over TCP through the dialer.

The example for this item is shown with the ones above: net-tun-Plan.salam

action_drop

const action_drop: i32 = 0
Rewrite result: drop the packet.

The example for this item is shown with the ones above: net-tun-Nat.salam

action_reply

const action_reply: i32 = 1
Rewrite result: the packet was rewritten in place, write it back to the device.

The example for this item is shown with the ones above: net-tun-Nat.salam

action_dns

const action_dns: i32 = 2
Rewrite result: a UDP query to port 53, answer it yourself.

The example for this item is shown with the ones above: net-tun-Nat.salam

action_ipv6

const action_ipv6: i32 = 3
Rewrite result: an IPv6 packet. The stack answers a TCP SYN with a reset so the app falls back to IPv4 at once.

The example for this item is shown with the ones above: net-tun-Nat.salam

proto_icmp

const proto_icmp: i32 = 1
IP protocol number of ICMP for IPv4 (1).

The example for this item is shown with the ones above: net-tun-Packet.salam

proto_tcp

const proto_tcp: i32 = 6
IP protocol number of TCP (6).

The example for this item is shown with the ones above: net-tun-Packet.salam

proto_udp

const proto_udp: i32 = 17
IP protocol number of UDP (17).

The example for this item is shown with the ones above: net-tun-Packet.salam

proto_icmp6

const proto_icmp6: i32 = 58
IP protocol number of ICMPv6 (58).

The example for this item is shown with the ones above: net-tun-Packet.salam

tcp_fin

const tcp_fin: i32 = 1
TCP flag bit FIN: the sender has finished sending.

The example for this item is shown with the ones above: net-tun-Packet.salam

tcp_syn

const tcp_syn: i32 = 2
TCP flag bit SYN: opens a connection.

The example for this item is shown with the ones above: net-tun-Packet.salam

tcp_rst

const tcp_rst: i32 = 4
TCP flag bit RST: resets a connection.

The example for this item is shown with the ones above: net-tun-Packet.salam

tcp_psh

const tcp_psh: i32 = 8
TCP flag bit PSH.

The example for this item is shown with the ones above: net-tun-Packet.salam

tcp_ack

const tcp_ack: i32 = 16
TCP flag bit ACK: the acknowledgement number is valid.

The example for this item is shown with the ones above: net-tun-Packet.salam

Functions

Available

func Available(): Availability
Checks that full device mode can start: the system is supported, the tunnel driver is there and the process has the rights it needs.

The example for this item is shown with the ones above: net-tun-Session.salam

Platform

func Platform(): str
linux, macos, windows or other.

The example for this item is shown with the ones above: net-tun-Session.salam

DefaultGateway

func DefaultGateway(): Gateway
The default gateway of the machine. While a session runs it returns the one saved before the routes changed.

The example for this item is shown with the ones above: net-tun-Session.salam

SystemResolvers

func SystemResolvers(): Vector<str>
IPv4 DNS servers of the machine.

The example for this item is shown with the ones above: net-tun-Session.salam

NewBypassDialer

func NewBypassDialer(): BypassDialer
A BypassDialer for the current physical interface.

The example for this item is shown with the ones above: net-tun-Session.salam

Bypass

func Bypass(): dyn tunnel.Dialer
The same as NewBypassDialer, as a dyn tunnel.Dialer ready for a router.

The example for this item is shown with the ones above: net-tun-Session.salam

OpenDevice

func OpenDevice(name: str, mtu: int): Device
Opens a bare tunnel device without addresses, routes or stack, for programs that handle packets themselves.

The example for this item is shown with the ones above: net-tun-Session.salam

Running

func Running(): bool
True while a session runs.

The example for this item is shown with the ones above: net-tun-Session.salam

LastError

func LastError(): str
The error of the last failed Start.

The example for this item is shown with the ones above: net-tun-Session.salam

Start

func Start(opts: Options): Session
Creates the device, sets its address, routes and DNS, and starts the stack. One session at a time.

The example for this item is shown with the ones above: net-tun-Session.salam

SessionStats

func SessionStats(s: Session): Stats
Counters of a session.

The example for this item is shown with the ones above: net-tun-Session.salam

Stop

func Stop(s: Session)
Stops the stack, runs the teardown commands and closes the device, so the routes are as they were.

The example for this item is shown with the ones above: net-tun-Session.salam

NewNat

func NewNat(address: str, next: str, listen_port: int, idle_ms: int): Nat
Creates a NAT for a device address, the next address of its subnet, the listener port and an idle timeout in milliseconds (0 means ten minutes).

The example for this item is shown with the ones above: net-tun-Nat.salam

FreeNat

func FreeNat(nat: Nat)
Frees a NAT.

The example for this item is shown with the ones above: net-tun-Nat.salam

Checksum

func Checksum(p: void*, n: int): int
The Internet checksum (RFC 1071) of a byte range. A range that already holds a correct checksum gives 0.

The example for this item is shown with the ones above: net-tun-Packet.salam

ChecksumAdjust

func ChecksumAdjust(sum: int, old_word: int, new_word: int): int
Updates a checksum after one 16 bit word changed, without reading the rest of the data (RFC 1624, equation 3). The NAT uses it for every rewritten packet.

The example for this item is shown with the ones above: net-tun-Packet.salam

FinishChecksums

func FinishChecksums(ptr: void*, n: int)
Recomputes the IPv4 header checksum and the TCP or UDP checksum of a packet in place.

The example for this item is shown with the ones above: net-tun-Packet.salam

ChecksumsOk

func ChecksumsOk(ptr: void*, n: int): bool
True when the IPv4 header checksum and the TCP or UDP checksum are both correct.

The example for this item is shown with the ones above: net-tun-Packet.salam

Parse

func Parse(ptr: void*, n: int): PacketInfo
Reads the headers of an IPv4 or IPv6 packet into a PacketInfo.

The example for this item is shown with the ones above: net-tun-Packet.salam

FreePacket

func FreePacket(pk: Packet)
Frees the memory of a Packet.

The example for this item is shown with the ones above: net-tun-Packet.salam

BuildTcp4

func BuildTcp4(src: str, sport: int, dst: str, dport: int, seq: i64, ack: i64, flags: int, data: void*, n: int): Packet
Builds an IPv4 TCP segment with the given addresses, ports, sequence and acknowledgement numbers, flags and payload, with correct checksums.

The example for this item is shown with the ones above: net-tun-Packet.salam

BuildUdp4

func BuildUdp4(src: str, sport: int, dst: str, dport: int, data: void*, n: int): Packet
Builds an IPv4 UDP datagram with correct checksums. The stack uses it for DNS answers.

The example for this item is shown with the ones above: net-tun-Packet.salam

ValidName

func ValidName(name: str): bool
True for an interface name of 1 to 15 letters, digits, - or _.

The example for this item is shown with the ones above: net-tun-Plan.salam

NextAddress

func NextAddress(address: str): str
The IPv4 address after the given one. The stack uses it as the NAT source and the DNS address.

The example for this item is shown with the ones above: net-tun-Plan.salam

ParseLinuxRoutes

func ParseLinuxRoutes(text: str): Gateway
Finds the default gateway in the text of /proc/net/route, preferring the lowest metric.

The example for this item is shown with the ones above: net-tun-Plan.salam

ParseMacRoute

func ParseMacRoute(text: str): Gateway
Reads the output of route -n get default on macOS.

The example for this item is shown with the ones above: net-tun-Plan.salam

ParseResolvers

func ParseResolvers(text: str): Vector<str>
Reads IPv4 DNS servers from resolv.conf text or scutil --dns output.

The example for this item is shown with the ones above: net-tun-Plan.salam

BuildPlan

func BuildPlan(platform: str, dev: str, opts: Options, gw: Gateway, hosts: Vector<str>, resolvers: Vector<str>, exe: str): Plan
Builds the setup and teardown commands for linux, macos or windows. Pure: it runs nothing, so a plan can be shown or tested.

The example for this item is shown with the ones above: net-tun-Plan.salam

SplitCommand

func SplitCommand(line: str): Vector<str>
Splits a plan line into program and arguments; double quotes keep spaces together.

The example for this item is shown with the ones above: net-tun-Plan.salam

SniffHost

func SniffHost(ptr: void*, n: int): str
Finds the host name in the first bytes of a connection: the SNI of a TLS ClientHello or the Host header of an HTTP request. Returns an empty string for anything else or an IP.

The example for this item is shown with the ones above: net-tun-Sniff.salam

ParseDnsQuery

func ParseDnsQuery(ptr: void*, n: int): DnsQuestion
Reads the id and first question of a DNS query.

The example for this item is shown with the ones above: net-tun-Sniff.salam

BuildDnsQuery

func BuildDnsQuery(id: int, name: str, qtype: int): Packet
Builds a DNS query with recursion desired for a name and record type.

The example for this item is shown with the ones above: net-tun-Sniff.salam