UDE

UDP Distributed Ethernet
Login

UDP Distributed Ethernet

UDE is a small, portable alternative to VDE (Virtual Distributed Ethernet). Its virtual switch speaks Ethernet frames over localhost UDP instead of Unix-domain sockets, so it runs unchanged on Linux, the BSDs, macOS and Windows (Winsock). Emulators such as 86Box or QEMU, TAP bridges, and small network services plug into it the way they plug into vde_switch.

UDE has four parts:

Part What it is
libude (include/ude.h) Client library (static libude.a, plus shared libude.so.0 or libude-0.dll): connect to a switch, send and receive frames. It holds the portable socket layer and a transport abstraction that covers UDE/UDP and classic VDE (libvdeplug).
protocol libraries (optional) libude-ipv4 (ARP, IPv4, ICMP), libude-udp, libude-tcp and libude-dhcp (DHCP client and server), layered on libude. A small, portable, event-driven IPv4 host stack that uses no OS IP stack. See Protocol libraries.
udeswitch The switch daemon: MAC learning with aging, flooding, idle-port expiry, hub mode, stats, pcapng capture and monitor (mirror) ports.
tools udelink (a cable between two switches, UDE or VDE, or over a byte stream such as ssh) and udetap (Linux TAP bridge, Linux only), built only on libude; udedhcpd (DHCP server, with network boot information), udetftpd (read-only TFTP server, for network booting), udeping (ICMP ping, or layer-2 ping with -L) and udenc (a clone of OpenBSD netcat, TCP and UDP) and udeslirp (a NAT gateway to the host's network, like QEMU's user-mode networking), built on the protocol libraries; uderouter (an IPv4 router between switches), built on libude-ipv4; udectl (capture control, the port list and MAC table, kicking ports and flushing MACs) and udedump (a monitor port that writes pcapng or prints a summary, like tcpdump).

Plain C99 with no dependencies beyond the platform socket API (libvdeplug is optional). The build uses autosetup, which is vendored in autosetup/, so building needs only a C compiler and GNU make.

Documentation. The manual pages are in docs/ (mdoc; make install installs them with the check-in's date and version), starting with ude(7). The guides are in www/, Fossil Markdown with pikchr diagrams: fossil ui serves them at /doc/ckout/www/index.md, and the optional make html and make pdf build static HTML and a PDF (see www/build.md).


Build

./configure            # autosetup; uses tclsh if present, else builds its bundled jimsh
make
make test              # unit tests + end-to-end tests with real processes (~30 s)
make install           # PREFIX via --prefix=..., DESTDIR supported
make html              # optional: www/ and the manual pages as HTML (needs fossil)
make pdf               # optional: the same as one PDF (needs Chrome or WeasyPrint)

Source tarballs come from Fossil's tarball generator (the /tarball page or fossil tarball); there is no make dist.

Out-of-tree builds work too: mkdir build && cd build && ../configure && make.

./configure --help lists every option. These are the ones specific to UDE:

Option Effect
--lib-only build only libude (same as --disable-daemon --disable-tools)
--disable-daemon don't build udeswitch
--disable-tools don't build any of the programs in tools/
--disable-ipv4 don't build libude-ipv4; this also disables libude-udp, libude-tcp, libude-dhcp the IPv4 tools and uderouter
--disable-udp don't build libude-udp; this also disables libude-dhcp and the IPv4 tools
--disable-tcp don't build libude-tcp; this also disables udenc and udeslirp
--disable-dhcp don't build libude-dhcp; this also disables the IPv4 tools (udeping, udenc, udedhcpd, udetftpd, udeslirp)
--disable-shared build only the static libraries (libude.a, libude-ipv4.a, ...); the programs are then linked statically
--static link the programs with the static libraries instead of the shared ones; the shared libraries are still built (add --disable-shared to skip them)
--disable-tap don't build udetap (default: build it if linux/if_tun.h is found)
--disable-vdeplug don't build the vde:// transport (default: build it if libvdeplug is found)
--disable-werror don't build with -Werror (the default is -Wall -Wextra -Werror and more)
CC=clang any C99 compiler; gcc and clang are tested

udetap and the VDE transport are detected: without linux/if_tun.h or libvdeplug, configure leaves them out and says so, and the --disable- options leave them out even where they could be built. --enable-tap and --enable-vdeplug are still accepted and turn a missing header or library into an error.

Shared libraries and the programs

By default the programs are linked with the shared libraries, and each one only with the libraries it uses itself (the rest come in through the libraries' own dependencies):

Program Shared libraries it links
udeswitch, udelink, udetap, udectl, udedump libude
udeping, udedhcpd libude-dhcp, libude-ipv4, libude
udetftpd libude-dhcp, libude-udp, libude-ipv4, libude
udenc, udeslirp libude-tcp, libude-dhcp, libude-udp, libude-ipv4, libude
uderouter libude-ipv4, libude

The shared libraries link each other the same way: libude-udp and libude-tcp need libude-ipv4, which needs libude; libude-dhcp needs libude-udp, libude-ipv4 and libude. Only libude links libvdeplug. On ELF systems configure adds -Wl,--as-needed where the linker has it, so no library is named that is not used, and readelf -d shows exactly these NEEDED entries. No rpath is written into the libraries or the programs (except on macOS, where an installed program gets an rpath to $libdir, as the libraries' install names are @rpath/...).

udeswitch also uses the socket layer and wire protocol of libude, which the shared library does not export; it links those two objects (lib/net_compat.c and lib/proto.c) itself.

./configure --static links the programs with libude.a, libude-ipv4.a, ... as before (the C library stays dynamic). It changes only the programs: the shared libraries are still built and installed for other users, unless --disable-shared is given too. --disable-shared alone implies --static, as there is nothing to link against.

Until make install, a dynamically linked program cannot find its libraries. So in the build tree the real programs go into .libs/, the directory libtool uses for the same purpose, and make writes an sh wrapper with the program's name into the build directory:

#!/bin/sh
# udenc - build-tree wrapper written by make (scripts/mkwrapper.sh).
# It runs .libs/udenc with the shared libraries of this build
# directory. "make install" installs the real program, not this script.
ude_builddir='/home/me/ude/build'
LD_LIBRARY_PATH="$ude_builddir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export LD_LIBRARY_PATH
exec "$ude_builddir/.libs/udenc" "$@"

The wrapper holds the build directory as an absolute path, so ./udenc, build/udenc or the full path work from any directory, in-tree and out-of-tree; it adds to an existing LD_LIBRARY_PATH rather than replacing it, and exec keeps the process id, so signals and kill reach the program. On macOS the wrapper sets DYLD_LIBRARY_PATH too. The tests (make test, tests/run_tests.sh, tests/manual_tap.sh) run the wrappers; under sudo the wrapper sets the path itself after sudo has cleaned the environment. To run a program in a debugger, run .libs/PROGRAM with LD_LIBRARY_PATH set to the build directory. make install installs the real programs from .libs/ and the libraries, never the wrappers. With --static there are no wrappers and the programs are written straight into the build directory.

Windows looks for DLLs next to the .exe first, and the build writes both into the build directory, so MinGW builds have no wrappers: run the .exe files directly, on Windows or under Wine. make install copies the DLLs next to the programs in $bindir.

The build installs ude.pc, so emulators can use pkg-config --cflags --libs ude. Each protocol library has its own pkg-config file whose Requires names the library below it: ude-ipv4 (requires ude), ude-udp and ude-tcp (require ude-ipv4) and ude-dhcp (requires ude-udp). For example, pkg-config --libs ude-dhcp gives -lude-dhcp -lude-udp -lude-ipv4 -lude.

Version information

The version number lives in the VERSION file at the top of the tree (MAJOR.MINOR.PATCH, currently 0.1.0). The Fossil repository has the manifest setting turned on (a repository setting, which fossil clone copies from the server), so every Fossil checkout and every tarball made by Fossil contains manifest and manifest.uuid. As in SQLite and Fossil itself, make runs scripts/mkversion.tcl (with the same tclsh or bundled jimsh that runs configure) to turn those three files into ude_version.h in the build directory, and it regenerates the header whenever any of them changes:

#define UDE_VERSION        "0.1.0"
#define UDE_VERSION_NUMBER 1000      /* major*1000000 + minor*1000 + patch */
#define UDE_SOURCE_ID      "2026-11-29 03:49:08 b4009bb258e463220a7620980cb7a2cc8cd0d50623754872a2e686fbcb845f98"
#define UDE_SCM_DATETIME   "2026-11-29T03:49:08.000Z"

UDE_SOURCE_ID is the check-in time (UTC) followed by the full check-in hash. UDE_VERSION_NUMBER drops leading zeros so that C doesn't read it as octal: 1.2.4 is 1002004. In a plain copy of the tree without the manifest files, the source id and date are "unknown" and the build still works.

ude.h includes ude_version.h, which make install installs next to it. At run time ude_version(), ude_sourceid() and ude_libversion_number() return the values libude was built with, like their sqlite3_* counterparts; they always give the full source id. Every program prints its version with -V or --version, showing the check-in hash cut to 10 digits the way Fossil shows check-in names:

$ udeswitch --version
udeswitch 0.1.0 (2026-11-29 17:27:25 bba2b95814)

Windows (MinGW-w64)

Cross-compiling from Debian or Ubuntu:

sudo apt install gcc-mingw-w64-x86-64     # or gcc-mingw-w64-i686 for 32-bit
./configure --host=x86_64-w64-mingw32     # or --host=i686-w64-mingw32
make            # -> udeswitch.exe udectl.exe udedump.exe udelink.exe udeping.exe
                #    udenc.exe udedhcpd.exe udetftpd.exe udeslirp.exe uderouter.exe,
                #    linked with libude-0.dll libude-ipv4-0.dll libude-udp-0.dll
                #    libude-tcp-0.dll libude-dhcp-0.dll in the same directory,
                #    their import libraries (libude.dll.a, libude-ipv4.dll.a, ...) and .a files
make test       # builds test_core.exe test_pcapng.exe test_impair.exe test_lib.exe test_net.exe test_stack.exe
                # (and the udecat.exe and udetftp.exe test clients)
                # (run them on Windows or under Wine), and checks every
                # .exe and .dll for imports old Windows lacks (see below)

You can also build natively under MSYS2 with ./configure && make (the configure script detects *-mingw*). Windows builds link -lws2_32. They skip udetap (no TAP) and the VDE transport (libvdeplug is POSIX-only). To link against the DLLs, define UDE_USE_DLL (one macro covers every UDE library); the static libraries need nothing extra.

Windows versions

The aim is that a 32-bit build (--host=i686-w64-mingw32) runs on Windows NT 4.0 and Windows 2000 and everything after them, and on Windows 95, 98 and ME as far as possible. A 64-bit build runs on every 64-bit Windows (XP x64 onwards). The code uses only Winsock 2 and Win32 calls that NT 4.0 already has:

make test in a Windows build runs tests/check_imports.sh. It lists every function each program and DLL imports, with the target's objdump (found by configure, or set OBJDUMP=), and fails on any that is not in tests/win_imports.txt, which lists only what NT 4.0 and Windows 95 have. It also checks that the PE headers ask for Windows 4.0 at most (5.2 for 64-bit builds), as MinGW-w64 sets them. Before adding a name to the list, check when Windows got it. A toolchain that targets the UCRT (api-ms-win-crt-*, Windows 10, or 7 with an update) instead of msvcrt.dll fails this check; for old Windows, use one that targets msvcrt.dll, such as Debian's and Ubuntu's gcc-mingw-w64 or MSYS2's MINGW32 environment.

On the older systems:

The 32-bit build has been run on Windows NT 4.0 without a service pack (all programs), and on Windows 95 and 98 (udedhcpd and udeping). Windows 9x needs CreateThread to get a pointer for the thread id, which NT does not; udenc's standard input thread passes one.


Quick start

./udeswitch -v &                                   # 127.0.0.1:7500
./udeping -L -r -m 02:00:00:00:00:02 &             # a layer-2 responder
./udeping -L -m 02:00:00:00:00:01 -c 3 02:00:00:00:00:02   # ping it through the switch

An IPv4 network: switch, DHCP server and two netcats

A UDE switch is an isolated Ethernet: nothing hands out addresses unless a DHCP server runs on it, and there is no router to anywhere else.

./udeswitch &                                      # the "cable"
./udedhcpd -a 10.0.0.1/24 &                        # leases 10.0.0.100-199
./udenc -v -l 9000                                 # terminal 1: gets 10.0.0.100, listens (TCP)
./udenc -v 10.0.0.100 9000                         # terminal 2: type, and it appears in 1
./udeping 10.0.0.100                               # terminal 3: ICMP ping, Ctrl+C to stop

Each client prints the address it got (udenc: 10.0.0.100/24 on c6:1f:...:9e (DHCP from 10.0.0.1, lease 3600 s)) to standard error; udenc does so only with -v, as nc prints nothing by default. Give a client a fixed address with --addr 10.0.0.9/24 (-a for udeping and udedhcpd; no DHCP), or a fixed MAC with --mac and a reservation (udedhcpd -r MAC=ADDR) for a predictable lease.

udeswitch

udeswitch [-p PORT] [-b ADDR] [-P MAXPORTS] [-M MACCAP] [-a MACAGE] [-T PORTIDLE]
          [-m MAXFRAME] [-H] [-R] [-s SECS] [-n NAME] [-w FILE] [-A POLICY] [-C FILE] [-v[v]]
Flag Default Meaning
-p 7500 UDP port
-b 127.0.0.1 bind address. A warning is printed if the address is not in 127.0.0.0/8 (including 0.0.0.0; there is no auth yet)
-P 64 maximum number of ports (clients)
-M 4096 MAC table capacity
-a 300 s MAC aging time (0 = never)
-T 300 s idle timeout before a client is dropped (0 = never). Announced in HELLO_ACK; see Idle timeout and keepalives
-m 1522 largest frame accepted (1514 + 802.1Q tag + 4 bytes slack for senders that include the FCS); at most 65200, so that every frame the switch forwards is captured and mirrored whole (see MIRROR)
-H hub mode: flood every frame (it still never sends back to the ingress port)
-R require HELLO: drop DATA from endpoints that haven't registered
-s dump stats every N seconds. kill -USR1 dumps them on demand (POSIX)
-w capture every frame received, from startup, to FILE in pcapng format (- = standard output). udectl stops, restarts and rotates it. See Capture and monitor ports
-A, --policy none who may send management (udectl) and monitor (udedump) requests: none (nobody), local (loopback peers only) or any (prints a warning). Was -C.
-C, --configuration optional TOML configuration file (or UDE_CONFIG). Command-line options override the file. See ude.conf(5).
-v log events (ports, learning, MAC moves). -vv also logs every frame
-V print the version, check-in date and short hash, then exit (also --version)

SIGINT/SIGTERM (Ctrl+C / Ctrl+Break on Windows) shut the switch down cleanly. With -v it prints final stats on exit.

All the programs accept -V/--version and -h/--help.

udelink [-n NAME] [-l ADDR] [-L ADDR] [-k MS] [-r MS] [-I SPEC] [-A SPEC]
        [-B SPEC] [-S SEED] [-s] [-q] [-v] A B

udelink is a cable between two switches, like dpipe vde_plug = vde_plug for VDE: every frame one side receives is sent to the other, unchanged. A and B are anything ude_open() accepts: a udeswitch (host:port, udp://host:port), a classic vde_switch (vde:///path, when libude is built with libvdeplug), or another libvdeplug URL. Either side may instead be -, standard input and output in vde_plug's stream format: each frame preceded by its length, 2 bytes big-endian. That is what vde_plug URL speaks on its standard input and output, so dpipe and ssh link switches across hosts as with VDE.

udelink 127.0.0.1:7500 127.0.0.1:7600            # two udeswitches
udelink 127.0.0.1:7500 vde:///tmp/vde.ctl        # a udeswitch and a vde_switch
udelink 127.0.0.1:7500 192.0.2.10:7500           # a switch on another host (plain UDP)
dpipe udelink 127.0.0.1:7500 - = ssh host udelink - 127.0.0.1:7500   # over ssh
dpipe udelink 127.0.0.1:7500 - = ssh host vde_plug /tmp/vde.ctl      # to remote VDE
Option Default Meaning
-n NAME udelink:OTHER-SIDE port name on both switches (HELLO NAME, or the VDE port description); at most 31 bytes are kept
-l ADDR, -L ADDR 127.0.0.1 for a loopback switch, else 0.0.0.0 local address[:port] of A's and B's UDP sockets
-k MS 5000 HELLO interval on UDE sides (-1 off, 0 the switch's idle timeout / 2)
-r MS 1000 how often to reopen a side that failed
-I SPEC impair the link both ways (see Link impairment)
-A SPEC, -B SPEC impair only the frames from A to B, or from B to A
-S SEED from the clock seed of the impairment's random numbers (decimal), for runs that repeat exactly
-s print the frame counters per direction on exit
-q, -v only errors; or one line per forwarded frame (implies -s)

Like VDE's wirefilter, udelink can make the cable a bad one: lossy, slow, late, jittery, duplicating or corrupting, for testing how protocols and emulated machines cope. -I SPEC applies to both directions, -A SPEC to frames from A to B, -B SPEC to frames from B to A (wirefilter's LR and RL). SPEC is KEY=VALUE[,KEY=VALUE...]; several options apply in order and each changes only the keys it names, so -I delay=50ms -B delay=0 delays only A to B. Each direction has its own queue and random sequence.

Key Value Meaning
loss percent, 0-100, up to 4 decimals, % optional drop frames at random
burst average burst length, ≥ 1 (decimals allowed) with loss, losses come in bursts (Gilbert-Elliott: the long-run loss rate stays loss)
dup percent send a second copy (both copies then go through rate and delay)
corrupt percent flip one random bit of the frame
delay time: ms by default, or us, ms, s (up to 1 hour) added latency
jitter time uniform random latency of ± this much on top of delay (never below zero)
reorder reorder, reorder=1 or reorder=0 let jitter reorder frames; by default order is kept
rate bit/s; k, M, G = 1000s bandwidth: each frame takes length × 8 / rate on the wire
queue bytes; k, M = 1024s the drop-tail queue in front of rate (default 100 ms worth, at least 3044 bytes: two full frames)
mtu bytes, header included drop longer frames
none clear all keys given so far

A frame goes through the steps in this order: mtu, loss, dup, then for each copy corrupt, rate (wait for the wire; drop if the queue is full) and delay/jitter.

# A 56k modem: 56 kbit/s, 100 ms of latency, a 4 KiB modem buffer.
udelink -I rate=56k,queue=4k,delay=100ms 127.0.0.1:7500 127.0.0.1:7600
# A lossy WAN: 80 ms ± 10 ms, 1% loss in bursts of 3, 0.1% duplicates.
udelink -I delay=80ms,jitter=10ms,loss=1%,burst=3,dup=0.1 -S 42 127.0.0.1:7500 vde:///tmp/sw
# ADSL: 8 Mbit/s down (A to B), 1 Mbit/s up, 20 ms each way.
udelink -I delay=20ms -A rate=8M -B rate=1M 127.0.0.1:7500 127.0.0.1:7600

Capture and monitor ports

There are two ways to see the traffic on a switch, and both write pcapng that Wireshark, tshark and capinfos read:

./udeswitch -A local -w all.pcapng &         # capture from startup; allow udectl
                                             # and udedump from this host
./udectl status                              # capturing to /.../all.pcapng: 120 frames, ...
./udectl capture stop
./udectl capture start                       # appends a new section to all.pcapng
mv all.pcapng all.1.pcapng && ./udectl capture rotate   # logrotate style
./udectl capture rotate /tmp/next.pcapng     # or switch to another file

./udedump                                    # one line per frame, like tcpdump
./udedump -w - | wireshark -k -i -           # live in Wireshark
./udedump -w x.pcapng -c 100                 # 100 frames, then exit
udectl [-s HOST:PORT] [-t MS] [-q] capture start [FILE] | capture stop
       | capture rotate [FILE] | capture status | status
udedump [-s URL] [-w FILE|-] [-c COUNT] [-p] [-q] [-n NAME] [-l LOCAL]

Both are management functions, so the switch refuses them unless it is started with -A local (or -A any); see Security. udeswitch -w needs no -A, but then the capture runs until the switch exits.

Introspection and port management

udectl also shows what the switch knows, and changes it: the ports with their counters, the MAC table, removing ("kicking") a port, and flushing MACs. Like capture control, this needs udeswitch -A local (or -A any).

udectl [-s HOST:PORT] [-t MS] [-q] [-p] ports | macs [PORT] | kick PORT
       | flush [PORT|MAC]
$ ./udectl ports
switch udeswitch: 4 ports (at most 64)
   ID  PEER                   NAME             TYPE      MACS     IDLE   UPTIME   RX FRAMES      RX BYTES   TX FRAMES      TX BYTES  DROPPED
    1  127.0.0.1:40001        vm1              hello        1     1.5s     1.8s           2           120           8           480        0
    2  127.0.0.1:40002        vm2              hello        1     1.4s     1.7s           3           180           2           120        0
    3  127.0.0.1:40003        vm3              hello        1     1.3s     1.6s           4           240           1            60        0
    4  127.0.0.1:40004        -                auto         1     1.5s     1.5s           1            60           0             0        0
$ ./udectl macs
switch udeswitch: 4 MACs in the table (at most 4096)
MAC                 PORT  NAME                 AGE
02:00:00:00:00:aa      4  -                   1.5s
52:54:00:00:00:01      1  vm1                 1.5s
52:54:00:00:00:02      2  vm2                 1.4s
52:54:00:00:00:03      3  vm3                 1.3s
$ ./udectl -p ports | head -1                # for scripts: tab-separated, times in ms
1	127.0.0.1:40001	vm1	hello	1	1509	1809	2	120	8	480	0
$ ./udectl kick vm3                          # or: kick 3, kick 127.0.0.1:40003
kicked port 3 (127.0.0.1:40003 vm3), 1 MAC flushed
$ ./udectl flush 2                           # the MACs of port 2; the port stays
flushed 1 MAC of port 2 (127.0.0.1:40002 vm2)
$ ./udectl flush 52:54:00:00:00:01           # one MAC
flushed 52:54:00:00:00:01 of port 1 (127.0.0.1:40001 vm1)
$ ./udectl flush                             # the whole table
flushed 1 MAC

Network options of udeping, udenc, udedhcpd and udetftpd

The IPv4 programs share these options (common/ude_netcli.c). Without --addr, they get their address by DHCP. udeping and udedhcpd accept the short letters too; udenc takes only the long options, because nc uses those letters for its own options (-s source address, -N shutdown, -v verbose...).

Long option Short (udeping, udedhcpd, udetftpd) Default Meaning
--switch URL -s URL 127.0.0.1:7500 switch (vde:///path with libvdeplug)
--mac MAC -m MAC random MAC address. The default is random, unicast and locally administered (x2:...), so it never collides with UDE's reserved 55:44:45 range
--name NAME -n NAME program name client name for the switch; also the DHCP host name
--addr ADDR[/LEN] -a ADDR[/LEN] DHCP static address (/24 if no length)
--gateway GATEWAY -g GATEWAY none static default gateway (with --addr)
--dns DNS -N DNS none static DNS server, up to 3 times (with --addr)
--dhcp-timeout SECS -T SECS 10 how long to wait for a DHCP lease
--log -v log ARP and DHCP events

Long options take their value as --addr 10.0.0.9 or --addr=10.0.0.9, and may be shortened to any unambiguous prefix (--dhcp).

On exit (end of the run, Ctrl+C) a DHCP client sends DHCPRELEASE.

udeping

udeping [net options] [-c N] [-i SECS] [-W SECS] [-S BYTES] [-t TTL] [-q] HOST
udeping [net options] -r
udeping -L -m MAC [-s URL] [-c N] [-i SECS] [-W SECS] (-r | DSTMAC)

ICMP echo over IPv4, with ping-like output and statistics. -c count (default: until Ctrl+C), -i interval and -W reply timeout in seconds (fractions allowed, default 1), -S payload size (default 56), -t the TTL (default 64; a router where it runs out answers "time to live exceeded"), -q only the summary. The exit status is 0 if any reply came back. -r just keeps an address and answers pings; every libude-ipv4 program answers pings anyway, including udedhcpd and udenc.

udeping 10.0.0.1                          # DHCP, then ping the DHCP server
udeping -a 10.0.0.9/24 -c 3 10.0.0.100    # static address

-L is the older layer-2 ping, kept as a mode: raw Ethernet frames of EtherType 0x88B5 between two libude clients, with no IP at all. It is useful to check a switch path before any addressing exists:

udeping -L -r -m 02:00:00:00:00:02 &                     # responder
udeping -L -m 02:00:00:00:00:01 -c 5 02:00:00:00:00:02   # RTT through the switch

(Before the IPv4 mode existed this was the only mode; its old -d DSTMAC and millisecond -i/-w options became -L ... DSTMAC and seconds.)

udenc

udenc [-46DdhklNnuvz] [-I length] [-O length] [-p source_port]
      [-q seconds] [-s sourceaddr] [-W recvlimit] [-w timeout]
      [network options] [destination] [port]
udenc -l [options] [address] port
udenc [-l] [options] -p port        # listen on port: traditional nc -l -p, and older udenc

A clone of OpenBSD's nc (netcat.c 1.241) on the UDE network, with Debian's -q: TCP by default (libude-tcp), UDP with -u. The options, the messages of -v, the exit status and, above all, when it stops, follow OpenBSD's readwrite() and listen loop, so scripts written for nc behave the same. Addresses are numeric IPv4 only: there is no resolver.

udenc -l 9000 > file                     # receive a file
udenc -N 10.0.0.100 9000 < file          # send it: -N sends FIN after the end of input
udenc -k -l 7000                         # serve one connection after another
udenc -z -v 10.0.0.100 20-25             # which ports are open?
udenc -u -l 9000                         # UDP: talk to the first sender
Option Meaning, as in OpenBSD nc
-4 IPv4 (always; accepted for compatibility)
-D socket debugging: accepted, no effect
-d do not read standard input
-h, --help help (exit status 0; OpenBSD exits 1)
-I length TCP receive buffer, at most 65535 (no window scaling)
-k listen for another connection after the current one; needs -l
-l listen; udenc -l [address] port, where address must be ours or 0.0.0.0
-N shut down the sending side (TCP FIN) after the end of standard input
-n numeric only: accepted, no effect (names are never resolved)
-O length TCP send buffer
-p port source port of a connection; with -l, or without a destination, the port to listen on (see below)
-q seconds Debian: after the end of input, quit seconds later; implies -N; negative = never (default)
-s sourceaddr source address: must be the interface's own address (it has one)
-u UDP
-v verbose: Listening on, Bound on, Connection received on, Connection to ... succeeded!, connect to ... failed: ..., and the address the interface got
-W recvlimit stop after receiving that many packets (reads)
-w timeout connect timeout, and quit after timeout idle seconds; no effect on waiting for a connection in listen mode
-z scan: connect and close, send nothing (TCP only)
-V, --version print the version (-V without a value; -V rtable, nc's routing table, is refused)

Listening on a port: udenc -l 9000, udenc -l -p 9000 and udenc -p 9000 all listen on port 9000, for TCP and with -u. The first is OpenBSD's form. The second is the traditional and Debian nc -l -p form, which OpenBSD nc rejects ("cannot use -p and -l"); udenc before the nc options also used it (udenc -u -l -p 9000). The third, -p with no destination, is a udenc extension: OpenBSD nc prints its usage and traditional nc says "no destination". With -l -p PORT port both ports must agree.

Older udenc options: besides -u HOST PORT, -u -l -p PORT, -q and -v (now nc's verbose; --log logs ARP and DHCP), these short network options still work where they do not clash with nc: -s URL (a value that is not an IPv4 address is the switch; an IPv4 address is nc's source address), -m MAC (a MAC address; nc's minimum TTL is not supported), -a ADDR[/LEN], -g GATEWAY, -T SECS (a number of seconds; nc's TOS is not supported) and -V. -n NAME and -N DNS are now nc's -n and -N flags: use --name and --dns. -t never worked (TCP was "not implemented"); TCP is now the default and -t is nc's telnet option, which is not supported.

Ports can be ranges (lo-hi) when connecting; each port is tried in turn. The network options above (--switch, --addr, --log...) are long options only. These nc options are refused with a clear message, since the stack has nothing they could map to: -6 (no IPv6), -C -c -e -H -K -o -R -Z and -T keyword (TLS, CRLF, TOS), -F (descriptor passing), -i (line delay), -M and -m minttl (TTL), -P -X -x (proxies), -r (random ports), -S (TCP MD5), -t (telnet), -U (Unix sockets), -V rtable (routing tables).

When it stops (end-of-file behaviour, as in OpenBSD readwrite()). There are four directions: standard input, network out, network in, standard output.

Exit status: 1 for bad arguments, a failed bind, or when connecting failed for every port; otherwise 0, including after a reset or an idle -w. Ctrl+C ends it like a signal ends nc (status 130): queued data is still handed to TCP, and it gets about two seconds to go out.

Differences from OpenBSD nc, besides the refused options:

As example code, udenc.c shows a long-running libude program with its own event loop: wait on the switch and standard input at once (common/ude_stdin.c), never longer than ude_ipv4_timeout_ms(), then ude_ipv4_poll(ip, 0); TCP events and datagrams arrive in callbacks.

udedhcpd

udedhcpd -a ADDR/LEN [-p START-END] [-L SECS] [-g ROUTER] [-N DNS]...
         [-r MAC=ADDR]... [-f FILE] [-B ADDR] [-b [CLASS=]FILE]... [-q] [net options]
Flag Default Meaning
-a (required) the server's own address, and the subnet it serves
-p .100-.199 address pool: full addresses or host numbers (-p 50-99). Subnets smaller than a /24 default to every host address
-L 3600 lease time in seconds
-g none router to hand out (option 3). There is none by default: the network is isolated until a router exists
-N none DNS server to hand out (option 6), up to 3 times
-r reservation: always give ADDR to MAC (repeatable; may be outside the pool)
-f none lease file: keep bound leases in FILE across restarts
-B, --next-server none network boot: the TFTP server (siaddr, and option 66 when asked for), e.g. a udetftpd
-b, --boot-file none network boot: the file to boot (the file field, and option 67 when asked for). CLASS= limits it to iPXE (ipxe=) or to a client architecture (option 93): bios=, efi32=, efi64= (7 and 9), arm32=, arm64= or a number (exact). Repeatable; iPXE entries win, then an exact architecture, then efi64 for 7 or 9, then a plain FILE
-q don't log DHCP messages (they are logged by default)

It implements DISCOVER/OFFER/REQUEST/ACK, NAK, RELEASE, DECLINE (the address is set aside for 10 minutes) and INFORM, renewals and INIT-REBOOT. Offers are held for 60 s. It prefers a client's reservation, then its current lease, then the address it asks for, then the first free one. Leases live in memory; the lease table is printed on exit.

With -f FILE, the bound leases are also kept in FILE, so they survive a restart of the server: clients keep their addresses, and new clients don't get an address someone still holds. It is a text file with one lease per line and the expiry as an absolute Unix time:

# udedhcpd lease file v1
# MAC IP EXPIRES HOSTNAME (EXPIRES in Unix time, UTC)
02:00:00:00:00:0a 10.0.0.100 1796000000 alice

The server rewrites it whenever a lease is granted, renewed, released or declined, by writing FILE.tmp, flushing it to disk and renaming it over FILE (MoveFileEx on Windows), so FILE always holds a complete version (except on Windows 95, 98 and ME; see "Windows versions"). At startup it reads the file, skips leases that have expired and lines it can't use (logging them), and writes it back. A missing file is created; a file that doesn't start with the first line above is refused and left alone, so a wrong -f can't destroy anything. Offers are not saved (they last 60 s). The format and the load/save functions are part of libude-dhcp (ude_dhcpd_save_leases, ude_dhcpd_load_leases, ude_dhcpd_restore). The server is an ordinary host on the network: it answers ARP and ping for its own address. It doesn't depend on a router; udeslirp is one, and the two can share a subnet.

udeslirp

udeslirp [-v] [-a ADDR/LEN] [-b ADDR] [-D ADDR[:PORT]] [-R FORWARD]... [-s URL] [-m MAC] [-n NAME]
         [--route NET/LEN:GATEWAY]... [--dns-address ADDR|none] [--host-loopback] [--restrict] [--deny ADDR/LEN]...
         [--no-icmp] [--max-connections N] [--max-udp N]
         [--tcp-timeout SECS] [--udp-timeout SECS] [--connect-timeout SECS] [-C FILE]

A NAT gateway from the UDE network to the host's network, in the manner of QEMU's user-mode networking (SLIRP): no root, no TAP device, no routing or firewall rules. It joins the switch as the gateway, 10.0.2.2/24 by default, and carries the guests' traffic out through ordinary sockets of the host:

DHCP stays a separate program, so a guest may use udedhcpd, a static address, or another DHCP server running in a VM. With udedhcpd on the same subnet (-g the gateway, -N the DNS address, a pool that avoids both), guests are configured by DHCP:

udeswitch &
udedhcpd -a 10.0.2.4/24 -g 10.0.2.2 -N 10.0.2.3 -p 15-99 &
udeslirp -v -R tcp:2222:10.0.2.15:22 &

-C/--configuration FILE (or UDE_CONFIG) reads a TOML file: each long option is also a key of the [udeslirp] table, with _ for - (--switch is connection, --addr is address), booleans have a --no-X form, and forward, route and deny are arrays. --check-config reports unknown keys and --print-config shows the effective options. See ude.conf(5), udeslirp(8) and www/howto/internet.md.

uderouter

uderouter -i SWITCH,ADDR/LEN[,MAC] -i ... [-r NET/LEN:GATEWAY]... [-n NAME]
          [-v] [-q] [--no-icmp-errors] [-C FILE]

An IPv4 router between two or more switches, each a broadcast domain and subnet of its own, with no privileges and no help from the host's network. On each switch named with -i (any URL: 127.0.0.1:7500, vde:///tmp/sw) it is a host with that address, answering ARP and ping, and it forwards unicast IPv4 between them:

udeswitch -p 7500 &
udeswitch -p 7600 &
uderouter -i 127.0.0.1:7500,10.0.1.1/24 -i 127.0.0.1:7600,10.0.2.1/24 &
udedhcpd -s 127.0.0.1:7500 -a 10.0.1.2/24 -g 10.0.1.1 &
udedhcpd -s 127.0.0.1:7600 -a 10.0.2.2/24 -g 10.0.2.1 &

With a leg on udeslirp's subnet and -r default:10.0.2.2, plus udeslirp --route for the subnets behind it, every subnet reaches the outside. Each long option is a key of [uderouter] (interface and route are arrays; connection is ignored). See uderouter(8) and www/howto/multiple-networks.md, which also covers routing with the Linux host through udetap.

udetftpd

udetftpd -a ADDR/LEN -r DIR [-B N] [-W N] [-t SECS] [-R N] [-c N] [-q] [-C FILE] [net options]
Flag Default Meaning
-a (required) the server's own address
-r, --root (required) the directory served
-B, --max-blksize 1468 largest block size a client may negotiate (1468 fills one Ethernet frame)
-W, --max-window 16 largest window (RFC 7440 windowsize) a client may negotiate, up to 64
-t, --timeout 1 seconds before a retransmission, unless the client negotiates its own
-R, --retries 5 retransmissions before a transfer is given up
-c, --max-transfers 64 transfers at once
-q, --quiet don't log requests and transfers (--no-quiet undoes it)
-C, --configuration optional TOML configuration file (or UDE_CONFIG); each long option is a key of [udetftpd], and address and connection stand for --addr and --switch. See ude.conf(5)

A read-only TFTP server (RFC 1350) with option negotiation (RFC 2347: blksize, timeout, tsize and windowsize), octet and netascii modes, and any number of blocks (the block number wraps from 65535 to 0, so a 40 MB initrd works at 512-byte blocks). Each transfer has its own port and keeps its window in memory, so a retransmission never reads the file again. Write requests get an access violation. Names are relative to the root: leading slashes are dropped, \ counts as / (for Windows boot files), and .., : and control characters are refused; on POSIX systems a name must also resolve, symbolic links included, to a regular file inside the root. Together with udedhcpd -B ADDR -b FILE it network boots emulated machines; www/howto/netboot.md boots the Debian installer in QEMU that way.

udetap (Linux only)

sudo ip tuntap add dev ude0 mode tap user $USER     # once
udetap -i ude0 -s 127.0.0.1:7500 &
sudo ip addr add 10.0.0.1/24 dev ude0 && sudo ip link set ude0 up

This was checked by hand: the host kernel answered an ARP request that a test client sent through the switch and udetap. tests/manual_tap.sh (root; not part of make test) goes further: in a throw-away network namespace, Linux gets a lease from udedhcpd with busybox udhcpc, pings udedhcpd and a udeping -r, is pinged by udeping, exchanges UDP with udenc, gets ICMP port unreachable from a closed port, and exchanges 1 MB each way over TCP with udenc in both roles against OpenBSD nc (or socat, with LNC=socat), plus resets for closed ports in both directions. See www/howto/recipes.md for QEMU, VDE and more recipes.

libude in 15 lines

#include <ude.h>
ude_lib_init();
ude_conn_opts o; ude_conn_opts_init(&o); o.name = "86box"; o.hello = 1;
char err[256];
ude_conn *c = ude_open("127.0.0.1:7500", &o, err, sizeof err);   /* or "vde:///tmp/vde.ctl" */
ude_send_frame(c, frame, len);
long n = ude_recv_frame(c, buf, sizeof buf, 10);   /* ms; 0 = poll, -1 = block */
/* or wait on ude_get_fd(c) in your own loop and call ude_service(c) periodically */
ude_close(c);                                        /* sends BYE */
ude_lib_cleanup();

A monitor (what udedump does) opens with o.hello = 0, calls ude_monitor(c, 2000), and then reads every datagram the switch receives, with its ingress port, sender and the switch's timestamp, through ude_recv_mirror(c, buf, sizeof buf, &info, timeout_ms).

libude-udp in 20 lines

#include <ude_dhcp.h>             /* includes ude_udp.h, ude_ipv4.h and ude.h */
static void on_dgram(void *ctx, ude_udp *s, uint32_t ip, uint16_t port,
                     const uint8_t *data, size_t len)
{
    ude_udp_sendto(s, ip, port, data, len);           /* an echo server */
}
...
ude_conn *c = ude_open("127.0.0.1:7500", &o, err, sizeof err);
uint8_t mac[6]; ude_net_random_mac(mac);
ude_ipv4 *ip = ude_ipv4_new(c, mac);                  /* an IPv4 host on the switch */
ude_dhcp_client *dc = ude_dhcp_client_new(ip, "echo");
ude_udp *s = ude_udp_open(ip, 7, on_dgram, NULL);
for (;;)
    ude_ipv4_poll(ip, -1);   /* frames, ARP, ICMP, DHCP timers, UDP callbacks */

Or, with your own event loop: wait on ude_get_fd(c) for at most ude_ipv4_timeout_ms(ip) and then call ude_ipv4_poll(ip, 0); udenc.c does exactly that. A static address is ude_ipv4_configure(ip, &cfg) instead of a DHCP client.


Protocol libraries

libude stays minimal: a switch connection and Ethernet frames. Anything above Ethernet lives in separate, optional libraries layered on top, each with its own public header, static and shared build, pkg-config file and configure switch:

                 libude-dhcp   ude_dhcp.h   DHCP client + server     ude-dhcp.pc
                      |
  libude-tcp     libude-udp    ude_udp.h    UDP sockets              ude-udp.pc
  ude_tcp.h           |
  TCP connections     |
  ude-tcp.pc          |
          \           |
           +---- libude-ipv4   ude_ipv4.h   ARP, IPv4, ICMP          ude-ipv4.pc
                      |
                   libude      ude.h        switch connection        ude.pc
                                            + Ethernet frames
Library Linux Windows Prefix
libude-ipv4 libude-ipv4.so.0, libude-ipv4.a libude-ipv4-0.dll, libude-ipv4.dll.a ude_ipv4_*, ude_inet_*, ude_net_*, UDE_NET_* errors
libude-udp libude-udp.so.0, libude-udp.a libude-udp-0.dll, ... ude_udp_*
libude-tcp libude-tcp.so.0, libude-tcp.a libude-tcp-0.dll, ... ude_tcp_*
libude-dhcp libude-dhcp.so.0, libude-dhcp.a libude-dhcp-0.dll, ... ude_dhcp_* (client), ude_dhcpd_* (server)
libude-ipv6 reserved name, not implemented

Each shared library links against the shared libraries below it that it uses. Programs link only what they use, dynamically unless configured with --static (see Shared libraries and the programs): udeswitch and udetap use libude alone; udeping, udenc and udedhcpd use DHCP, and udenc and udeslirp also use TCP and UDP.

Why DHCP is its own library and not part of libude-udp: it is an application protocol, not transport. Most UDP users (a TFTP server, a game, a test tool) don't need it, and the client and the server share one message codec that belongs to neither. A future router can link libude-dhcp to serve its subnets, and a DHCP-only embedder doesn't drag in anything else.

How the stack works.

libude-tcp

A small TCP after RFC 9293, registered like UDP as a protocol handler and a module of the interface. One callback per connection gets events (CONNECTED, READABLE, WRITABLE, CLOSED, and ACCEPT on a listener), always from ude_ipv4_poll()/ude_ipv4_tick() or frame input and never from inside a ude_tcp_* call, so a callback may call anything. Calls return UDE_NET_* codes in the same style as UDP; failures are UDE_NET_ECONNREFUSED, _ECONNRESET and _ETIMEDOUT.

Function What it does
ude_tcp_connect(ip, dst, port, lport, opts, fn, ctx, &err) active open (local port 0 = ephemeral, from 49152)
ude_tcp_listen(ip, port, backlog, opts, fn, ctx), ude_tcp_accept() passive open; ACCEPT says a connection is ready
ude_tcp_listen_ex(..., flags, ...), ude_tcp_confirm() for routers: UDE_TCP_LISTEN_ANY takes connections to any address and port that reach the stack; UDE_TCP_LISTEN_DEFER hands them over at the SYN and answers only on ude_tcp_confirm() (or a reset on ude_tcp_abort(), nothing on ude_tcp_close())
ude_tcp_send(), ude_tcp_recv() queue data (returns what fit); read (0 = the peer's FIN)
ude_tcp_shutdown() half-close: FIN after the queued data, keep receiving
ude_tcp_close(), ude_tcp_abort() release the handle (graceful, in the background) or reset
ude_tcp_pending(ip) connections still delivering data, to poll before exit
ude_tcp_build(), ude_tcp_parse() the segment codec, with the pseudo-header checksum

What it does:

Limitations, by design for a small emulator-network stack: no window scaling (so at most 64 KB in flight), timestamps, SACK, ECN, urgent data, Nagle algorithm, delayed ACKs, keepalives or path MTU discovery. Out-of-order data is kept as one block beyond the next expected byte; other out-of-order segments are dropped and the peer retransmits them. ICMP destination unreachable ends a connection attempt (as in Linux) but is ignored on an open connection (a soft error, RFC 1122 4.2.3.9). An address that does not answer ARP is noticed only when the SYN retries run out. There is no SO_REUSEADDR: a port in TIME-WAIT can't be reused for the same peer until it ends, but listeners can be reopened at once.


Wire protocol (version 1)

One UDP datagram carries exactly one message. There are two kinds:

DATA: a raw Ethernet frame, with no header

+-----------+-----------+-----------+---------------------+
| dst MAC 6 | src MAC 6 | type/len 2| payload ...         |   14 .. max_frame bytes, no FCS
+-----------+-----------+-----------+---------------------+

CONTROL: an 8-byte header followed by TLVs

 0      1      2      3      4      5      6      7
+------+------+------+------+------+------+------+------+
| 'U'  | 'D'  | 'E'  | ver=1| type |flags |payload len BE|
+------+------+------+------+------+------+------+------+
| TLV: type(1) len(1) value(len) ...                     |

Read as a frame, the magic is destination MAC 55:44:45:xx:xx:xx. That's a group address (the I/G bit of 0x55 is set) in a block that no protocol we know of uses. UDE reserves the whole 55:44:45:00:00:00/24 destination range: datagrams starting with it are always parsed as control and never forwarded, and libude refuses to send such frames. An unknown ver means the datagram is dropped and counted.

type name direction contents / behaviour
0x01 HELLO client → switch optional NAME. Registers (or re-registers) the endpoint. Optional unless the switch runs with -R
0x02 HELLO_ACK switch → client PORT_ID (u32), IDLE_TIMEOUT (u16 s, 0 = ports never expire), MAX_FRAME (u16), NAME
0x03 KEEPALIVE client → switch refreshes the port (and registers it, unless -R). Always accepted and acked, even when the idle timeout is 0
0x04 KEEPALIVE_ACK switch → client PORT_ID
0x05 BYE client → switch removes the port and flushes its MACs at once
0x10-0x12 AUTH_CHALLENGE / RESPONSE / RESULT reserved for authentication (see below). v0 answers with ERROR
0x20 DATA_SEALED reserved: an authenticated or sequenced data frame
0x30 CAPTURE_START manager → switch optional FILE, optional REQUEST_ID. Starts capturing to FILE (truncated), or without FILE appends a new section to the last file. ERROR 6 if already capturing
0x31 CAPTURE_STOP manager → switch optional REQUEST_ID. Stops capturing; stopping when stopped is not an error
0x32 CAPTURE_ROTATE manager → switch optional FILE, optional REQUEST_ID. Moves to FILE, or reopens the same name. ERROR 6 if not capturing
0x33 CAPTURE_STATUS manager → switch optional REQUEST_ID
0x34 CAPTURE_REPLY switch → manager answer to 0x30-0x33: REQUEST_ID (if given), CAPTURE_STATE (u8: 0 stopped, 1 capturing), FILE (the current or last file, if any), FRAMES and BYTES (u64, written to the current file), MONITORS (u16)
0x40 MONITOR client → switch optional NAME. Registers the endpoint as a monitor port, or turns its existing port into one (its MACs are flushed). A later HELLO makes it a normal port again
0x41 MONITOR_ACK switch → client as HELLO_ACK, plus IF_NAME: the interface name the switch uses in its own capture files. From then on the client receives a MIRROR for every datagram the switch receives from other ports
0x42 MIRROR switch → monitor one received datagram with its ingress metadata; see below
0x50 PORT_LIST manager → switch optional REQUEST_ID, optional CURSOR. Asks for a page of the port list
0x51 PORT_LIST_REPLY switch → manager REQUEST_ID, the switch's NAME, PORT_COUNT and MAX_PORTS (u16), then one record per port, each starting with PORT_ID: PEER, NAME (if any), PORT_FLAGS (u8: 1 registered with HELLO, 2 monitor), MAC_COUNT, RX_FRAMES, RX_BYTES, TX_FRAMES, TX_BYTES, RX_DROPPED, AGE_MS (since last heard from), UPTIME_MS. Paged, see below
0x52 MAC_LIST manager → switch optional REQUEST_ID, CURSOR, and a port (PORT_ID, PEER or NAME) to list only its MACs
0x53 MAC_LIST_REPLY switch → manager REQUEST_ID, NAME, MAC_COUNT (the whole table) and MAC_CAPACITY, then per MAC, in MAC order: MAC, PORT_ID, AGE_MS (since last seen as a source). Paged
0x54 PORT_KICK manager → switch optional REQUEST_ID, one of PORT_ID, PEER or NAME. Removes the port and flushes its MACs; its endpoint gets ERROR 9
0x55 MAC_FLUSH manager → switch optional REQUEST_ID; with MAC, that MAC; with PORT_ID, PEER or NAME, that port's MACs; with neither, the whole table
0x56 MGMT_REPLY switch → manager answer to 0x54 and 0x55: REQUEST_ID, the port concerned (PORT_ID, PEER, NAME; none for a whole-table flush), MAC (if one MAC was flushed) and MAC_COUNT (MACs flushed)
0x7F ERROR switch → client ERROR_CODE (u16: 1 port table full, 2 unsupported, 3 HELLO required, 4 denied by -A, 5 bad request, 6 capture file error, 7 no such port or MAC, 8 the name matches more than one port, 9 sent to a client whose port a manager removed), TEXT, and REQUEST_ID if the request had one

TLV types: 1 NAME, 2 PORT_ID, 3 IDLE_TIMEOUT, 4 MAX_FRAME, 5 AUTH_METHODS, 6 NONCE, 7 AUTH_PROOF, 8 ERROR_CODE, 9 TEXT, 10 FILE (a path, 1-255 bytes, no NUL), 11 REQUEST_ID (u32, chosen by the client and echoed), 12 CAPTURE_STATE (u8), 13 FRAMES (u64), 14 BYTES (u64), 15 MONITORS (u16), 16 TIMESTAMP (u64 ns since 1970-01-01 UTC), 17 PEER (IPv4 address and UDP port, 6 bytes; 18 bytes reserved for IPv6), 18 ORIG_LEN (u32), 19 IF_NAME, 20 CURSOR (opaque, at most 16 bytes), 21 PORT_FLAGS (u8), 22 MAC_COUNT (u32), 23 RX_FRAMES, 24 RX_BYTES, 25 TX_FRAMES, 26 TX_BYTES, 27 RX_DROPPED (u64), 28 AGE_MS (u32), 29 UPTIME_MS (u64), 30 PORT_COUNT (u16), 31 MAX_PORTS (u16), 32 MAC (6 bytes), 33 MAC_CAPACITY (u32). All integers are big-endian. Receivers ignore unknown TLVs and unknown control types, which keeps the protocol forward-compatible.

Management requests (0x30-0x33, 0x50, 0x52, 0x54, 0x55) and MONITOR are checked against -A before anything else: with none (the default) every request gets ERROR 4, with local only peers in 127.0.0.0/8 are served, and with any everyone is. Management requests don't register a port. They are answered once and not retransmitted, so a manager that gets no answer may simply ask again (CAPTURE_STATUS is safe to repeat; a repeated CAPTURE_START is refused with ERROR 6). A FILE value is a path on the switch's host. FILE is limited to 255 bytes by the one-byte TLV length; udectl refuses a longer path (after making it absolute), and the switch never sees one. Short names such as /tmp/switch.pcapng are the expected use.

Paged replies. A list reply is at most 1400 bytes (UDE_MGMT_PAGE_MAX), so it fits an Ethernet-sized path without fragmentation; a record is never split. When more follows, the reply carries a CURSOR; the manager sends the same request again with that CURSOR (and a new REQUEST_ID) for the next page. The last page has flag 0x01 (END) in the header and no CURSOR; an empty list is a single END page. The switch keeps no state between pages: the cursor (opaque to managers; today the last port id or MAC sent) says where to go on, and lists are in port-id or MAC order, so a port or MAC added or removed between pages doesn't make the others repeat or vanish. Because the requests change nothing, a manager may resend one that got no answer; PORT_KICK and MAC_FLUSH are sent once (a lost answer to a kick turns into "no such port" when repeated).

MIRROR: what a monitor port receives

+------+------+------+------+------+------+------+------+
| 'U'  | 'D'  | 'E'  | ver=1| 0x42 |flags | TLV len BE   |
+------+------+------+------+------+------+------+------+
| TIMESTAMP (2+8)  PORT_ID (2+4)  PEER (2+6)  [NAME]      |
| [ORIG_LEN (2+4)]                                        |
+---------------------------------------------------------+
| the received datagram, as captured (0..65200 bytes)      |
+---------------------------------------------------------+

Unlike every other control message, the length field covers only the TLVs: the captured bytes follow them, up to the end of the datagram, because a frame is longer than a TLV can be. The fields are exactly what the switch hands to its own capture file, from the same place in the switch (one capture hook feeds both), so they match it:

Size limits. A UDP datagram over IPv4 carries at most 65507 bytes. The largest MIRROR overhead is 307 bytes: the 8-byte header, TIMESTAMP (10), PORT_ID (6), PEER as IPv6 (20), ORIG_LEN (6) and a 255-byte NAME (257); switch port names are actually at most 31 bytes. 65507 − 307 = 65200, so the switch accepts -m up to 65200 and every frame it forwards is mirrored whole. On loopback (MTU 65536) such a datagram is not even fragmented; over a network it is fragmented by IP like any large UDP datagram, and a monitor needs a receive buffer of 64 KiB (libude's is). Over IPv4 a datagram larger than 65507 bytes can't reach the switch, so only datagrams between 65201 and 65507 bytes, which the switch drops as too big, are ever cut.

In libude, ude_recv_mirror() returns the bytes and a ude_mirror_info (timestamp, port, peer, name, lengths), ude_monitor_if_name() the IF_NAME, and ude_recv_frame() on a monitor connection just the bytes.

Idle timeout and keepalives

UDP is connectionless, so a client can vanish (crash, kill -9, a closed emulator) without anything reaching the switch. The switch therefore removes a port, and flushes its MACs, after -T seconds (default 300) without any datagram from it. Every datagram refreshes the port: frames, HELLO and KEEPALIVE alike.

Why raw frames with an optional control channel?


Design notes

include/ude.h            public API: ude_open/send/recv/close, utils
include/ude_transport.h  transport vtable (udp, vde, ...)
lib/net_compat.[ch]      ALL platform #ifdefs: Winsock init, closesocket, socklen_t,
                         errno vs WSAGetLastError, non-blocking, select(),
                         monotonic clock, signals, SIO_UDP_CONNRESET
lib/proto.[ch]           wire protocol: classify, TLV builder/iterator (pure)
lib/conn.c               transport-independent ude_conn layer
lib/transport_udp.c      UDE/UDP transport (HELLO, keepalives, BYE)
lib/transport_vde.c      libvdeplug transport (built if libvdeplug is found; POSIX)
lib/util.c               MAC parse/format, hexdump, frame builder
lib/mgmt.c               management client (ude_mgmt_*: capture, lists, kick, flush)
daemon/mactable.[ch]     MAC -> port hash table (chained, fixed node pool, aging)
daemon/porttable.[ch]    endpoint -> port slots (open-addressed index)
daemon/switch_core.[ch]  forwarding engine; no socket I/O (io.send callback)
daemon/udeswitch.c       socket loop, options, signals, the -w capture file
common/ude_getopt.[ch]   tiny portable getopt for the programs (MSVC has none)
common/ude_cli.[ch]      -V/--version output for the programs
common/ude_netcli.[ch]   shared network options + DHCP/static bring-up (IPv4 tools)
common/ude_stdin.[ch]    wait on stdin and a connection at once (udenc; see below)
common/ude_pcapng.[ch]   pcapng writer (udeswitch -w, udedump; see below)
common/ude_impair.[ch]   link impairment engine (udelink -I/-A/-B)
include/ude_ipv4.h       libude-ipv4 public API
ipv4/ipv4.c              the IPv4 host: ARP cache and queue, IPv4 in/out, ICMP
ipv4/pkt.c ipv4_pkt.h    pure codecs (ARP, IPv4, ICMP), checksums, addresses
ipv4/ude_bytes.h         big-endian load/store, pseudo-header sum (internal)
include/ude_udp.h        libude-udp public API
udp/udp.c                UDP sockets
include/ude_tcp.h        libude-tcp public API
tcp/tcp.c                TCP connections
include/ude_dhcp.h       libude-dhcp public API (client and server)
dhcp/dhcp_msg.[ch]       DHCP message codec (shared by client and server)
dhcp/client.c            DHCP client state machine
dhcp/server.c            DHCP server
tools/                   udectl, udedump, udelink, udeping, udenc, udedhcpd,
                         udeslirp, uderouter, udetap (Linux-only file)
common/ude_route.[ch]    routes, interfaces, TTL and fragmentation for
                         udeslirp and uderouter
common/ude_tftpd.[ch]    the TFTP server engine of udetftpd
tests/udecat.c           internal test and debug client for the end-to-end tests:
                         built by `make test`, never installed
tests/udetftp.c          internal TFTP client for the end-to-end tests, likewise
tests/test_tftp.c        udetftpd's server engine on a simulated network
tests/test_core.c        engine unit tests driven by a fake io (no sockets)
tests/test_pcapng.c      pcapng writer, byte by byte; also a pcapng checker
tests/test_impair.c      udelink's impairment engine on simulated time
tests/test_lib.c         public-API tests (also linked against the .so)
tests/test_net.c         protocol codec tests (ARP, IPv4, ICMP, UDP, DHCP)
tests/test_tcp.c         libude-tcp on a simulated lossy network
tests/test_stack.c       the protocol libraries on a simulated network
tests/test_route.c       routes, interfaces, TTL and fragmentation (ude_route.c)
tests/run_tests.sh       end-to-end: real switch + clients
tests/check_imports.sh   Windows builds: imports and PE versions, against
tests/win_imports.txt    the list of Windows functions old Windows has
tests/manual_tap.sh      manual test against the Linux IP stack (root; not in make test)
scripts/mkversion.tcl    writes ude_version.h from VERSION and Fossil's manifest
scripts/mkwrapper.sh     writes the build-tree wrapper of a dynamically linked program
scripts/mkhtml.sh        "make html": www/ with fossil, the manual pages with mandoc
scripts/mkpdf.sh         "make pdf": the HTML joined into one PDF
docs/                    manual pages (mdoc); docs/mkversion writes their date and version
www/                     guides in Fossil Markdown with pikchr (templates for now)
extsrc/                  unmodified third-party sources (tomlc17, MIT); see extsrc/README

Security: localhost UDP has no filesystem ACLs

udeswitch is open by default: any local process can plug in, and there is no authentication yet. Authentication will be opt-in (a shared-secret challenge-response, enabled by giving the switch a secret), so the default stays open and existing clients keep working.

A VDE switch is a Unix socket directory, so file permissions decide who can plug in. A UDP port on 127.0.0.0/8 can be reached by every local user. v0 limits the exposure: it binds 127.0.0.1 by default, warns if you bind a non-loopback address (anything outside 127.0.0.0/8, including 0.0.0.0), and -R requires HELLO. Unicast replies only reach the socket that owns the endpoint, so nobody can eavesdrop on a port they don't own. But anyone local can join.

Capture and monitor ports are the exception to "no eavesdropping": a monitor sees every frame, and capture requests make the switch write files with its own permissions. So they have their own policy, udeswitch -A:

The same policy covers the port list, the MAC table, kicking and flushing: a manager may see every client's address and name and disconnect any of them, so these are not open by default either. Any peer the policy lets in may use all of them, whether or not it is a port itself, and the requests never make it one. A kicked port is only removed, not banned (see Introspection).

The switch only overwrites or appends to files that are empty or already pcapng, so a request can't destroy an arbitrary file the switch can write, but it can create new files anywhere the switch user can. When authentication arrives, the plan is that an -A auth policy allows these requests only from authenticated endpoints, and that MONITOR and the capture requests may come only after a successful AUTH exchange.

The protocol leaves room for authentication without breaking v1 clients:

  1. Shared-secret challenge-response (CHAP-style), planned first and opt-in. HELLO carries AUTH_METHODS. Only if the switch is given a secret (-k keyfile) does it answer AUTH_CHALLENGE{NONCE_s}. The client replies AUTH_RESPONSE{NONCE_c, AUTH_PROOF = HMAC-SHA256(secret, "UDE1" | NONCE_s | NONCE_c | client endpoint | port id)}, and the switch sends AUTH_RESULT. Only then does the endpoint become a port. DATA from unauthenticated endpoints is dropped (the -R code path already exists). Because loopback endpoints can't be hijacked once bound, authenticating the endpoint once is enough on localhost. HMAC-SHA256 is about 300 lines of portable C, so this stays dependency-free.
  2. Sealed data (DATA_SEALED, 0x20) for use beyond localhost: control header, sequence number, frame, truncated HMAC. This protects integrity and blocks replay. Confidentiality would need an AEAD (e.g. ChaCha20-Poly1305), which is still small enough to vendor.
  3. Linux-only option: peer UID checks. Look up the owner of a source endpoint via sock_diag or /proc/net/udp and apply a UID/GID allow-list. That gives back VDE-like permissions without secrets. It would live behind net_compat or a separate peercred module.

Transport abstraction: tools that work with UDE and VDE

include/ude_transport.h defines a small vtable (match, open, send, recv, fd, service, close). ude_open(url) chooses the first transport whose match() accepts the URL:

Two incompatible libraries are both called libvdeplug, with the same API: vdeplug4 (libvdeplug.so.2, Debian/Ubuntu libvdeplug-dev), whose vde_open() takes URLs, and the classic vde2 library (libvdeplug.so.3, from vde-2 2.3.x source builds), whose vde_open() takes only a plain switch path. configure tells them apart with a link probe (only vdeplug4 exports __vde_version_tag) and reports VDE transport (libvdeplug): yes (vdeplug4) or yes (vde2). On vde2, libude strips the vde:// scheme before calling vde_open(). Plugin URLs such as vxvde:// need vdeplug4 and give a clear error on vde2.

The protocol libraries and the tools built on them (udedhcpd, udeping, udenc, udetftpd and udeslirp) talk to the switch only through ude.h, so each of them runs on either kind of switch with no extra code. Possible future transports: in-process loopback (tests and embedding), a pcap file writer, and sealed UDP.


VDE compatibility

Classic VDE UDE
vde_switch -s /tmp/sw (socket dir) udeswitch -p 7500 (UDP endpoint)
port registration on the ctl stream socket (request port, description) first datagram, or HELLO with NAME → HELLO_ACK with PORT_ID
per-port data socket (Unix datagram, raw frames) the client's UDP endpoint (raw frames)
ctl socket EOF = port gone BYE, or idle timeout (UDP has no EOF), kept alive by KEEPALIVE
vde_plug, libvdeplug URLs libude / ude_open() URLs
wirefilter -l LOSS -L BURST -d DELAY -D DUP -b BANDWIDTH -s SPEED -n NOISE -m MTU -c CHANQUEUE, LR/RL prefixes (dpipe vde_plug = wirefilter = vde_plug) udelink -I loss=…,burst=…,delay=…,jitter=…,dup=…,rate=…,queue=…,corrupt=…,mtu=…, -A/-B per direction (see "Link impairment"). rate with a drop-tail queue stands for both -b and -s; corrupt is a per-frame chance of one flipped bit, not bits per MB; fixed at startup (no wirefilter console); -S for repeatable runs
dpipe vde_plug = vde_plug (cable between switches), vde_plug URL over ssh udelink A B, between any two of udeswitch, vde_switch and a byte stream (-, vde_plug's 2-byte length format, so udelink and vde_plug talk to each other). No STP in either: avoid loops
management console (unixterm, -M): port/print, port/remove, hash/print, hash/delete stats via -s and SIGUSR1; udectl ports, kick, macs, flush (and capture control) over the control channel, refused unless -A allows them. No VDE console syntax: udectl is a client, not a terminal
hub mode (-x), ports, VLANs -H hub mode. VLAN-aware switching isn't implemented yet (tagged frames are forwarded as-is)

Bridging the two worlds:


Testing

make test runs:

The IPv4 parts are skipped when the protocol libraries are disabled.

udecat (tests/udecat.c) is an internal test and debug client, not a tool for users. make test builds it (with a wrapper in a dynamically linked build, like the programs) and make install does not install it. It sends Ethernet frames through libude: send src=MAC dst=MAC [type=0x88b5] [data=TEXT|hex=HEX] [len=N] [count=N] [inc] [nopad] (len pads or cuts the frame to N bytes, up to 65535; count repeats it; inc counts the last two bytes of src up, one per frame), prints the frames it receives (wait MS, listen), and sends HELLO (-H, -n NAME, hello) or leaves without BYE (-B). raw [hex=HEX] [len=N] [count=N] sends a UDP datagram straight to a udeswitch with none of libude's checks, so that runts, a 0-byte datagram or one longer than any frame can be sent. udecat -h lists everything.

A Windows build can't run these on the build machine. Its make test instead runs tests/check_imports.sh on every program, DLL and test program, which fails on an import that Windows NT 4.0 or 95 lacks or on PE headers that ask for a newer Windows (see "Windows versions"). The test programs run under Wine or on Windows.


Roadmap

  1. libvdeplug plugin ude://, which makes UDE usable from QEMU, vde_plug and 86Box (VDE backend) right away.
  2. 86Box integration: a native net_ude.c backend built on libude, which also works on Windows where 86Box has no VDE. Settings: switch address and an optional name.
  3. Authentication (opt-in; the switch stays open by default): HMAC challenge-response, then sealed data (see Security).
  4. Network services on the protocol libraries (each runs on UDE or VDE):
  5. More protocol libraries, names reserved:
    • libude-ipv6: IPv6 with neighbour discovery and SLAAC
  6. Switch features: VLANs (802.1Q-aware ports), per-port mirroring (monitors that see only some ports), IPv6 endpoints, rate limits, a Windows service wrapper, and recvmmsg batching.

Author

Mike Swanson

License

Licensed under the ISC license (see COPYING). The vendored autosetup/ is BSD-2-Clause. The vendored extsrc/tomlc17 is MIT (see extsrc/LICENSE.tomlc17).