Funlink
Funlink
Let device players, games and script apps on the same computer find each other. One call to announce, one click for the user to connect.
Users of apps like FapLand, games with EDI mods or script editors normally have to type ports and URLs into their device player. With Funlink, your app tells every interested app on the machine, and optionally on the local network, “I am running and offer this service”. A hub, such as RustyFunPlayer, shows a card: FapLand is running. Connect? One click, and it connects using the protocol you already speak.
Funlink only does discovery. It never carries media, scripts or device commands, so adding it changes nothing about how your app already talks to others.
The documentation was generated with AI assistance and has been thoroughly proofread, but errors or omissions may remain.
Pick your role
Peer: announce your app
You serve something others can connect to: an OFS WebSocket, a Buttplug server, a TCode device, an EDI game.
Hub: find apps
You connect to others: a device player, a script tool. Get notified when a usable app starts or stops.
Play scripts on devices
One call serves your scripts to RustyFunPlayer, which plays them on every connected device, and reports the devices back.
Libraries
Four libraries implement both roles, validate everything and handle timers, rate limits, expiry and goodbyes. All speak the same wire format and are tested against each other. The C library and the Godot add-on are peers only.
| Language | Install | Runtime dependencies |
|---|---|---|
| TypeScript / JavaScript | funlink-0.1.0.tgz from the release | none (Node.js 20+, Electron) |
| Rust | git dependency on tag v0.1.0 | serde, serde_json, getrandom |
| C# / .NET | Funlink.0.1.0.nupkg from the release | none (.NET 8+, AOT friendly) |
| Java | funlink-0.1.0.jar from the release | none (Java 17+) |
| Godot (GDScript, peer only) | funlink-godot-0.1.0.zip from the release | none (Godot 4.2+) |
| C / Arduino (local network peer only) | Funlink-arduino-0.1.0.zip from the release | none (C99, no malloc) |
The libraries are not on public package registries: they install from the GitHub release or from git.
Any other language works too: the protocol is one HTTP POST of a JSON object every 5 seconds. See Without a library.
Who uses it
- RustyFunPlayer is a hub. It offers OFS, FapLand, EDI games, mpv, VLC, MPC, Intiface and TCode serial devices.
- FapLand announces its OFS bridge with ofs-ws-extended.
- Wi-Fi TCode devices can announce themselves with the C library, and Godot games with the Godot add-on.
The libraries are free software under LGPL-3.0-or-later and can be used by applications under any license. Status: v1 draft; the name and port range are provisional.
Install
The libraries are not on npm, crates.io, NuGet or Maven Central. Install them from a GitHub release or straight from the repository. Every release lists the files with their SHA-256 checksums in SHA256SUMS.
Replace 0.1.0 with the latest release.
npm installs the release tarball from its URL and records the URL in package.json and the lock file:
npm install https://github.com/FapLandPartyDev/funlink/releases/download/v0.1.0/funlink-0.1.0.tgz
To build without network access, download funlink-0.1.0.tgz into your project and run npm install ./funlink-0.1.0.tgz.
Cargo finds the crate in the rust directory of the repository:
cargo add funlink --git https://github.com/FapLandPartyDev/funlink --tag v0.1.0
or in Cargo.toml:
[dependencies]
funlink = { git = "https://github.com/FapLandPartyDev/funlink", tag = "v0.1.0" }
Cargo.lock pins the exact commit.
Download Funlink.0.1.0.nupkg from the release into a packages directory next to your solution, then add a nuget.config beside it so every restore finds the package:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="funlink" value="packages" />
</packageSources>
</configuration>
dotnet add package Funlink --version 0.1.0
nuget.org stays available for your other packages.
Maven: download the jars and the pom from the release and install them into your local repository:
mvn install:install-file -Dfile=funlink-0.1.0.jar -DpomFile=funlink-0.1.0.pom \
-Dsources=funlink-0.1.0-sources.jar -Djavadoc=funlink-0.1.0-javadoc.jar
then depend on it as usual:
<dependency>
<groupId>io.github.faplandpartydev</groupId>
<artifactId>funlink</artifactId>
<version>0.1.0</version>
</dependency>
Gradle: put funlink-0.1.0.jar in libs/:
dependencies {
implementation(files("libs/funlink-0.1.0.jar"))
}
The library has no dependencies, so the jar is all you need. On a build server, keep the jar in your repository or in your own Maven repository.
Download Funlink-arduino-0.1.0.zip from the release. It holds the Funlink Arduino library for ESP32, ESP8266, Raspberry Pi Pico W and other boards whose WiFiUDP has beginMulticast().
Arduino IDE: Sketch → Include Library → Add .ZIP Library, then pick the zip.
arduino-cli:
arduino-cli config set library.enable_unsafe_install true
arduino-cli lib install --zip-path Funlink-arduino-0.1.0.zip
PlatformIO: in platformio.ini:
lib_deps = https://github.com/FapLandPartyDev/funlink/releases/download/v0.1.0/Funlink-arduino-0.1.0.zip
Other C projects: add src/funlink_core.c, src/funlink_json.c and src/funlink_dns.c from the zip to your build and include funlink_core.h. The library needs no malloc; you supply sending, a random number and the device’s address as callbacks.
The library is under the LGPL-3.0-or-later with a linking exception, so firmware may link it statically.
Download funlink-godot-0.1.0.zip from the release and unpack it into your project folder:
unzip funlink-godot-0.1.0.zip -d my-game/
It holds addons/funlink/, which must end up next to project.godot. The add-on is plain GDScript for Godot 4.2 or later, so it works in every export without building anything. It registers the FunlinkPeer node; enabling it under Project Settings > Plugins is optional.
Export notes:
- Android needs the INTERNET permission in the export preset.
- Web exports cannot open sockets, so the add-on does nothing there.
Godot .NET projects can use the C# library instead, which also finds hubs.
Announce your app
Your app is a peer when it offers a service other apps can connect to. Announcing takes one call; the library repeats it every 5 seconds and says goodbye when you stop it.
1. Install
Install the library from the GitHub release or from git; Install has the steps for C#, Java and Godot. For a microcontroller, see Announce a Wi-Fi device.
npm install https://github.com/FapLandPartyDev/funlink/releases/download/v0.1.0/funlink-0.1.0.tgz
cargo add funlink --git https://github.com/FapLandPartyDev/funlink --tag v0.1.0
Put Funlink.0.1.0.nupkg in a local package source (how), then:
dotnet add package Funlink --version 0.1.0
// Gradle, with funlink-0.1.0.jar in libs/
implementation(files("libs/funlink-0.1.0.jar"))
For Maven, install the jar and pom into your local repository first (how).
Download Funlink-arduino-0.1.0.zip from the release and add it with Sketch → Include Library → Add .ZIP Library, or list it in PlatformIO’s lib_deps (how).
Download funlink-godot-0.1.0.zip from the release and unpack it into your project, so that addons/funlink/ sits next to project.godot. Godot 4.2 or later; no plugin needs enabling. Godot .NET projects can use the C# library instead.
2. Announce
import { announce } from "funlink";
const funlink = announce({
id: "my-player", // fixed name of your app
name: "My Player",
version: "1.0.0",
services: [{ protocol: "ofs-ws", endpoint: "ws://127.0.0.1:8080/ofs" }],
});
// On exit:
await funlink.close();
#![allow(unused)]
fn main() {
use funlink::{Announcement, Protocol};
let peer = funlink::announce(
Announcement::new("my-player", "My Player")
.version("1.0.0")
.service(Protocol::OfsWs, "ws://127.0.0.1:8080/ofs"),
)?;
// Dropping `peer` says goodbye to every hub.
}
using Funlink;
await using var peer = FunlinkPeer.Announce(
new Announcement("my-player", "My Player",
[new Service(Protocol.OfsWs, "ws://127.0.0.1:8080/ofs")]) { Version = "1.0.0" });
// Disposing `peer` says goodbye to every hub.
import io.github.faplandpartydev.funlink.*;
var announcement = Announcement.of("my-player", "My Player",
Service.of(Protocol.OFS_WS, "ws://127.0.0.1:8080/ofs"))
.withVersion("1.0.0");
try (var funlink = Funlink.announce(announcement)) {
// Run your app. close() says goodbye to every hub.
}
#include <Funlink.h>
Funlink funlink;
void setup() {
// Connect to Wi-Fi first.
funlink.addService("tcode-udp", 8000); // udp://0.0.0.0:8000
if (!funlink.begin("sr6-a41c", "SR6", "1.0.0")) {
Serial.println(funlink_strerror(funlink.lastError()));
}
}
void loop() {
funlink.loop(); // call it often
}
A board has no hub on its own loopback, so the C library announces on the local network: give the port your device listens on, and hubs use the address the announcement came from. Announce a Wi-Fi device has a whole sketch.
# In an autoload, or any node that lives as long as the game.
var funlink := FunlinkPeer.new()
func _ready() -> void:
funlink.app_id = "my-game" # fixed name of your game
funlink.app_name = "My Game"
funlink.app_version = "1.0.0"
funlink.services = [{"protocol": "ofs-ws", "endpoint": "ws://127.0.0.1:8080/ofs"}]
add_child(funlink) # starts announcing
# The node says bye when it leaves the tree or the window closes.
You can also add a FunlinkPeer node in the editor and fill in its properties in the inspector.
That is all. A running RustyFunPlayer now shows a My Player card: 1.0.0 is running. Connect to follow its playback?
An invalid announcement fails at once (FunlinkError, funlink::Error, FunlinkException), so mistakes show up in development, not on users’ machines.
3. Pick good values
| Field | Rule | Tip |
|---|---|---|
id | Stable; 1–64 of A-Z a-z 0-9 . _ - | Use a fixed name for your app, such as my-game or org.example.player. Hubs remember “always connect” and “never ask” by id, and the OFS server derives its port from it. |
name | 1–64 characters | Shown on the card. Use your product name. |
version | Up to 32 characters, optional | Shown next to the name. |
icon | data:image/png;base64,…, square, ≤ 512 px, ≤ 64 KiB, optional | Shown on the card. 128 px is plenty. |
services | 1–8 services | Which protocol and loopback endpoint (127.0.0.1 or [::1]). |
ext | Optional object with reverse-domain keys | App-specific data, such as EDI game paths. |
The library adds the random per-launch session itself.
4. Keep it current
When a service starts, stops or moves to another port, replace the whole announcement; it is sent at once.
funlink.update({ id: "my-player", name: "My Player",
services: [{ protocol: "ofs-ws", endpoint: "ws://127.0.0.1:8081/ofs" }] });
#![allow(unused)]
fn main() {
peer.update(Announcement::new("my-player", "My Player")
.service(Protocol::OfsWs, "ws://127.0.0.1:8081/ofs"))?;
}
peer.Update(new Announcement("my-player", "My Player",
[new Service(Protocol.OfsWs, "ws://127.0.0.1:8081/ofs")]));
funlink.update(Announcement.of("my-player", "My Player",
Service.of(Protocol.OFS_WS, "ws://127.0.0.1:8081/ofs")));
funlink.addService("ofs-ws", 8080, "/ofs"); // announced at once while running
In plain C, call funlink_peer_configure(&peer, &record, now) with the new record; a running peer announces it at once.
funlink.services.append({"protocol": "buttplug-ws", "endpoint": "ws://127.0.0.1:12345"})
funlink.update()
Stop announcing (close or dispose) when you no longer offer any service. Hubs forget an app 15 seconds after its last announcement anyway, so a crash cleans itself up.
5. Optional: show “Connected to …”
Each hub answers with its name and whether it is connected to you. Use it to show status in your own UI.
const funlink = announce(announcement, {
onHubs: (hubs) => {
const connected = hubs.find((h) => h.state === "connected");
statusLabel.text = connected ? `Connected to ${connected.hub.name}` : "";
},
});
#![allow(unused)]
fn main() {
let peer = funlink::Announcer::builder(announcement)
.on_hubs(|hubs| {
for h in hubs {
println!("{}: {}", h.hub.name, h.state);
}
})
.start()?;
}
await using var peer = FunlinkPeer.Announce(announcement,
onHubs: hubs => Console.WriteLine(string.Join(", ", hubs.Select(h => $"{h.Hub.Name}: {h.State}"))));
try (var funlink = Funlink.announce(announcement,
hubs -> hubs.forEach(h -> System.out.println(h.hub().name() + ": " + h.state())))) {
// ...
}
void loop() {
funlink.loop();
if (const char *hub = funlink.connectedHub()) {
Serial.printf("Connected to %s\n", hub);
}
}
funlink.hub() returns the most relevant hub with its name, ID, address and state.
funlink.hubs_changed.connect(func(hubs: Array) -> void:
for hub in hubs:
if hub.state == "connected":
$Status.text = "Connected to " + hub.hub.name)
| State | Meaning |
|---|---|
available | The hub may offer you to its user. |
connected | The hub is connected to one of your services. |
dismissed | The user said “Not now”; you won’t be offered again until your app restarts. |
unsupported | The hub cannot use any of your services. |
Next: choose the right protocol, test it and add the badge to your app’s page.
Find apps (build a hub)
Your app is a hub when it connects to other apps: a device player, a script tool. The hub listens on the first free port from 37420 to 37429 and tells you when a usable app appears, changes or leaves.
Start a hub
import { startHub } from "funlink";
const hub = await startHub({
name: "My Player",
version: "1.0.0",
supports: ["buttplug-ws", "tcode-ws"],
onEvent: (event) => {
if (event.type === "found" && event.peer.state === "available") offer(event.peer);
if (event.type === "lost") withdraw(event.peer);
},
});
// On exit:
await hub.close();
#![allow(unused)]
fn main() {
use funlink::{Hub, HubEvent, PeerState, Protocol};
let hub = Hub::builder("My Player")
.version("1.0.0")
.supports([Protocol::ButtplugWs, Protocol::TcodeWs])
.start(|event| match event {
HubEvent::Found(peer) if peer.state == PeerState::Available => offer(peer),
HubEvent::Lost { peer, .. } => withdraw(peer),
_ => {}
})?;
// Dropping `hub` stops it.
}
using Funlink;
await using var hub = await FunlinkHub.StartAsync(
new HubOptions("My Player", [Protocol.ButtplugWs, Protocol.TcodeWs]) { Version = "1.0.0" },
e =>
{
switch (e)
{
case PeerFound { Peer.State: PeerState.Available } found: Offer(found.Peer); break;
case PeerLost lost: Withdraw(lost.Peer); break;
}
});
try (var hub = Funlink.hub(
HubOptions.of("My Player", Protocol.BUTTPLUG_WS, Protocol.TCODE_WS).withVersion("1.0.0"),
event -> {
if (event instanceof HubEvent.Found found && found.peer().state() == PeerState.AVAILABLE) offer(found.peer());
if (event instanceof HubEvent.Lost lost) withdraw(lost.peer());
})) {
// Run your app.
}
The C library is a peer only: hubs run on a computer. Use one of the four libraries there.
The Godot add-on is a peer only. A Godot .NET project can use the C# library, which also runs hubs.
Callbacks run on a background thread (Rust, C#, Java) or the event loop (TypeScript). Hand work to your UI thread as usual.
Events
| Event | When |
|---|---|
found | An app announced itself for the first time, or after a restart. |
updated | Its name, services, icon or state changed. |
lost | It left: bye, expired (15 s without announce) or restarted (new session; a found follows). |
Each event carries a Peer: the announced record (id, name, version, icon, services, ext) plus:
usable: the announced services your hubsupports, in announced order. Connect tousable[0].state:available,connected,dismissedorunsupported(nothing usable).origin: the web page’s origin, only when you allow browsers.
Ask the user, then connect
A hub must not connect just because an app announced itself. Show a prompt, then record the user’s answer:
async function onAnswer(peer: Peer, answer: "connect" | "dismiss") {
if (answer === "dismiss") return hub.setState(peer, "dismissed");
await connect(peer.usable[0].endpoint); // your existing connection code
hub.setState(peer, "connected");
}
#![allow(unused)]
fn main() {
if accepted {
connect(&peer.usable[0].endpoint)?; // your existing connection code
hub.set_state(&peer, PeerState::Connected);
} else {
hub.set_state(&peer, PeerState::Dismissed);
}
}
if (accepted)
{
await ConnectAsync(peer.Usable[0].Endpoint); // your existing connection code
hub.SetState(peer, PeerState.Connected);
}
else hub.SetState(peer, PeerState.Dismissed);
if (accepted) {
connect(peer.usable().get(0).endpoint()); // your existing connection code
hub.setState(peer, PeerState.CONNECTED);
} else {
hub.setState(peer, PeerState.DISMISSED);
}
The C library is a peer only: hubs run on a computer. Use one of the four libraries there.
The Godot add-on is a peer only. A Godot .NET project can use the C# library, which also runs hubs.
The peer sees the state in its next answer. dismissed lasts until the peer restarts; set available again when you disconnect.
Good prompt behavior, as the specification asks:
- Prompt at most once per launch of a peer, and not while you are already connected to a source.
- Offer Always connect and Never ask and store them by peer
id(and origin, for browsers).
What the library already does
Validation, Host checks against DNS rebinding, rate limits (200 ms per app, 64 apps), 96 KiB body limit, expiry after 15 s, restart detection and, on Linux, refusing other users’ processes. Web pages are rejected unless you opt in (allowBrowsers / allow_browsers / AllowBrowsers / withBrowsers); then each peer carries its origin and you must show it in the prompt.
Running two hubs
Ten ports allow several hubs at once (for example RustyFunPlayer and your app). Each hub gets every announcement independently. Coordinating which hub uses a service is not part of v1.
Once your hub works, add the “Funlink hub” badge to its page.
Choose a protocol
Each service names a protocol, so a hub knows whether it can use it. Use a registered name when one fits; the libraries type them, so a typo does not compile.
| You offer… | Protocol | Endpoint example | RustyFunPlayer does |
|---|---|---|---|
| The OpenFunscripter WebSocket API (media + scripts) | ofs-ws | ws://127.0.0.1:8080/ofs | Adds an OFS source and follows your playback. |
| OFS API plus device state and range edits | ofs-ws-extended and ofs-ws, same endpoint | ws://127.0.0.1:8080/ofs | Same, and reports its devices to you. See the guide. |
| A Buttplug server (like Intiface) | buttplug-ws | ws://127.0.0.1:12345 | Adds a Buttplug output. |
| VLC’s HTTP interface | vlc-http | http://127.0.0.1:8080 | Adds a VLC source. |
| MPC-HC / MPC-BE web interface | mpc-http | http://127.0.0.1:13579 | Adds an MPC source. |
| mpv’s JSON IPC socket | mpv-ipc | unix://127.0.0.1/run/user/1000/mpv.sock | Adds an mpv source. |
| A game that calls an EDI server | edi | http://127.0.0.1:5000/ | Serves EDI for the game. See the guide. |
| A TCode device on a serial port | tcode-serial | serial://127.0.0.1/dev/ttyACM0 | Adds a serial output. |
| A TCode device over WebSocket, TCP or UDP | tcode-ws, tcode-tcp, tcode-udp | ws://127.0.0.1:8000/ws | Registered; not offered by RustyFunPlayer yet. |
| Whirligig’s timecode server | whirligig-tcp | tcp://127.0.0.1:2000 | Registered; not offered by RustyFunPlayer yet. |
Endpoints must be absolute URLs on a loopback host (127.0.0.0/8 or [::1]), with a scheme that matches the protocol. The full table with schemes is in the specification.
Features
A service may list up to 16 features, short strings for optional capabilities a hub can check. Unknown features are ignored.
Your own protocol
If nothing fits, name it explicitly. The name becomes x-<vendor>-<name>; peers refuse any other unregistered name.
import { customProtocol } from "funlink";
const sync = customProtocol("acme", "sync-ws"); // "x-acme-sync-ws"
#![allow(unused)]
fn main() {
let sync = funlink::Protocol::custom("acme", "sync-ws")?; // x-acme-sync-ws
}
var sync = Protocol.Custom("acme", "sync-ws"); // x-acme-sync-ws
var sync = Protocol.custom("acme", "sync-ws"); // x-acme-sync-ws
// x-acme-sync-ws at ws://0.0.0.0:9000/sync; unregistered protocols name their scheme.
funlink.addService("x-acme-sync-ws", 9000, "/sync", nullptr, "ws");
funlink.services = [{"protocol": "x-acme-sync-ws", "endpoint": "ws://127.0.0.1:9000/sync"}]
Want a name registered? Open an issue with a short description and a link to the protocol’s documentation.
Local network
Funlink also works between machines: a player on a Steam Deck can offer its OFS API to RustyFunPlayer on the desktop, and a Wi-Fi stroker can offer TCode over UDP. On the local network, peers announce over two transports at once:
- DNS-SD (multicast DNS, what Bonjour and Avahi speak) as
_funlink._udp.local; - the Funlink beacon, the record as JSON in a UDP datagram on port 37420.
Hubs listen on both and merge what they hear. The specification has the wire format; the libraries implement both transports without extra dependencies, and devices without a library follow Announce a Wi-Fi device.
Both sides opt in: a peer only announces on the network, and a hub only listens there, when you turn lan on.
Announce on the network
Turn on lan. Loopback announcing continues as before; the library also writes a network copy of the record in which every endpoint host is 0.0.0.0. Hubs replace that host with the address the packet came from.
import { announce } from "funlink";
const funlink = announce(
{
id: "my-player",
name: "My Player",
services: [{ protocol: "ofs-ws", endpoint: "ws://127.0.0.1:8080/ofs" }],
},
{ lan: true },
);
#![allow(unused)]
fn main() {
use funlink::{Announcement, Announcer, Protocol};
let peer = Announcer::builder(
Announcement::new("my-player", "My Player").service(Protocol::OfsWs, "ws://127.0.0.1:8080/ofs"),
)
.lan(true)
.start()?;
}
await using var peer = FunlinkPeer.Announce(
new Announcement("my-player", "My Player",
[new Service(Protocol.OfsWs, "ws://127.0.0.1:8080/ofs")]),
options: new AnnounceOptions { Lan = true });
try (var funlink = Funlink.announcer(Announcement.of("my-player", "My Player",
Service.of(Protocol.OFS_WS, "ws://127.0.0.1:8080/ofs"))).lan(true).start()) {
// Run your app.
}
The C library always announces on the local network, over the beacon and DNS-SD:
funlink.addService("tcode-udp", 8000);
funlink.begin("sr6-a41c", "SR6", "1.0.0"); // both transports
funlink.begin("sr6-a41c", "SR6", "1.0.0", FUNLINK_TRANSPORT_BEACON); // beacon only, e.g. to keep ESPmDNS
funlink.lan = true
funlink.lan_hosts = ["192.168.2.40"] # optional: hubs on other subnets
Set both before the node enters the tree. Godot cannot share a UDP port, so the add-on never binds port 37420 and answers no queries; hubs find the game by its next announce, within 5 seconds. It announces over the beacon only, not over DNS-SD.
Your service must then listen on the network too, for example on 0.0.0.0:8080, not only on 127.0.0.1. Anyone on the network can connect to it, so protect it as such.
The network record leaves out the icon and services whose endpoints are not network sockets (unix, serial), and carries ext only in the beacon. It must fit in 1200 bytes, each DNS TXT string in 255 bytes, and features must not contain commas; otherwise announcing fails with invalid_announce. Hubs on other machines answer with a status, which appears in the announcer’s list of hubs like a loopback hub’s answer.
Find peers on the network
const hub = await startHub({
name: "My Player",
supports: ["tcode-udp", "ofs-ws"],
lan: true,
queryHosts: ["192.168.2.20"], // optional: peers on another subnet
onEvent: (event) => { /* event.peer.address is set for network peers */ },
});
hub.search(); // ask again now, for a "Search" button
#![allow(unused)]
fn main() {
let hub = Hub::builder("My Player")
.supports([Protocol::TcodeUdp, Protocol::OfsWs])
.lan(true)
.query_hosts(["192.168.2.20".parse()?]) // optional: peers on another subnet
.start(|event| { /* event.peer().address is Some for network peers */ })?;
hub.search();
}
await using var hub = await FunlinkHub.StartAsync(
new HubOptions("My Player", [Protocol.TcodeUdp, Protocol.OfsWs])
{
Lan = true,
QueryHosts = [IPAddress.Parse("192.168.2.20")], // optional: peers on another subnet
},
e => { /* e.Peer.Address is set for network peers */ });
hub.Search();
var options = HubOptions.of("My Player", Protocol.TCODE_UDP, Protocol.OFS_WS)
.withLan(true)
.withQueryHosts(InetAddress.getByName("192.168.2.20")); // optional: peers on another subnet
try (var hub = Funlink.hub(options, event -> { /* peer().address() is present for network peers */ })) {
hub.search();
}
The C library is a peer only: hubs run on a computer. Use one of the four libraries there.
The Godot add-on is a peer only. A Godot .NET project can use the C# library, which also runs hubs.
A network peer’s address is the IP its packets came from, and the endpoints in its services already use that address. Loopback peers have no address. Events, expiry after 15 seconds and setState work as for loopback peers.
What the library checks for you: only loopback, private, link-local and unique-local source addresses count; endpoints always point at the sender; at most 64 network peers and 8 per address; a peer on this machine that also announces over loopback appears once, as a loopback peer.
What your hub must do: ask before connecting, show the peer’s address in the prompt, and remember Always connect and Never ask per address and id. Do not act on ext data that names files, programs or processes; it describes another machine. A peer with Wi-Fi and Ethernet may appear once per address; offer it once.
Firewalls
The network transports need UDP ports 5353 (DNS-SD) and 37420 (beacon) open for incoming packets on the hub’s machine:
- Linux: open both ports, for example with
networking.firewall.allowedUDPPortson NixOS. - macOS: the first start asks for permission to find devices on the local network. A bundled app needs
NSLocalNetworkUsageDescriptionand_funlink._udpinNSBonjourServicesin itsInfo.plist. - Windows: the first start shows a firewall prompt; an installer can add the rule instead.
Guest networks and some routers block traffic between devices. Then only queryHosts with the peer’s address can reach it, if anything does.
Testing
avahi-browse -rt _funlink._udp (Linux) or dns-sd -B _funlink._udp (macOS) lists network peers. Set FUNLINK_LAN_PORT to move the beacon to another port, so experiments do not reach the hubs on your network.
Test your integration
Against RustyFunPlayer
- Install and start RustyFunPlayer and leave Settings → Funlink → Offer to connect running apps on.
- Start your app.
- Within 5 seconds a card appears: Your App is running. Connect to follow its playback? (the wording depends on the protocol).
- Click Connect. Your app’s state turns
connected.
No card?
| Check | Fix |
|---|---|
| Your service’s protocol | RustyFunPlayer offers only the protocols marked in Choose a protocol. Others answer unsupported. |
| A source is already playing | Hubs do not prompt while connected to a source. Disconnect it, or use Always connect. |
| You answered Never for this app earlier | Remove it under Settings → Funlink → Never ask again. |
| The announcement is rejected | Read the error body; see Errors. The libraries reject invalid records before sending. |
| You announce from a browser page | RustyFunPlayer refuses web pages. Announce from Node.js, Electron’s main process or a native app. |
On the local network
- In RustyFunPlayer, turn on Settings → Funlink → Find apps and devices on the local network.
- Let the firewall of the computer running RustyFunPlayer accept UDP ports 37420 and 5353. On NixOS, set
programs.rustyfunplayer.funlinkLan.openFirewall = true. - Start your app or device on another machine of the same network. The card names its address.
No card? Settings → Doctor shows whether RustyFunPlayer listens on the local network and how many apps and devices it hears. Wi-Fi access points with client isolation and guest networks drop multicast; enter the device’s address under Also ask these addresses instead. avahi-browse -rt _funlink._udp lists peers that announce over DNS-SD.
Without any hub
Run a hub of your own in a test and check that it finds your app. Set FUNLINK_PORT so tests do not meet a real hub on 37420–37429:
FUNLINK_PORT=37491 npm test
With FUNLINK_PORT set, hubs bind and peers send to that single port only. Java also reads the system property funlink.port.
A minimal TypeScript test:
import { announce, startHub } from "funlink";
process.env.FUNLINK_PORT = "37491";
const found = new Promise((resolve) => {
void startHub({ name: "Test hub", supports: ["ofs-ws"],
onEvent: (e) => e.type === "found" && resolve(e.peer) });
});
const peer = announce({ id: "test", name: "Test",
services: [{ protocol: "ofs-ws", endpoint: "ws://127.0.0.1:8080/ofs" }] });
console.log(await found);
await peer.close();
By hand
See what a hub answers with curl:
curl -sS -X POST http://127.0.0.1:37420/funlink/v1/announce \
-H 'Content-Type: application/json' \
-d '{"id":"test","session":"abcdefgh","name":"Test","services":[{"protocol":"ofs-ws","endpoint":"ws://127.0.0.1:8080/ofs"}]}'
A 200 answer names the hub, the protocols it supports and your state. Try ports 37421 and up if another program holds 37420.
Once it works, add the badge to your app’s page.
Show that you support Funlink
Users can’t tell from the outside whether an app speaks Funlink. If yours does, put a badge where people decide what to download: your EroScripts post, your README, your website or your store page. It tells them that your app and their other apps find each other without typing ports and URLs.
Pick your badge
Funlink included: your app announces itself, so hubs offer to connect to it. Use it for games, script apps and devices.
Funlink hub: your app finds announced apps and connects to them. Use it for device players such as RustyFunPlayer.
An app that does both may show both badges.
EroScripts
Forums such as EroScripts usually accept PNG uploads but not SVG, so use the PNG. It is drawn at twice its display size so it stays sharp on high-resolution screens:
- Download the PNG of your badge.
- Drag it into the post editor.
- Change the size in the inserted line to
264x96:

Put it near the top of your post, next to the download link, and mention in a sentence what it means for your users, for example: “Supports Funlink: RustyFunPlayer offers to connect as soon as the game starts.”
READMEs and websites
Link the badge to this site, so curious users find out what it means:
[](https://faplandpartydev.github.io/funlink/)
<a href="https://faplandpartydev.github.io/funlink/">
<img src="https://faplandpartydev.github.io/funlink/badges/funlink-hub.svg" width="264" height="96" alt="Funlink hub">
</a>
Copying the files into your own repository works just as well.
License
The badges are free to use, copy and modify without asking or giving credit. They are dedicated to the public domain under CC0 1.0. Showing a badge does not mean that the Funlink project reviewed or endorses your app; please only show it when your app supports Funlink.
Send scripts to a device player
Your app plays media with funscripts (a game, a video site wrapper, an editor) and you want devices to follow it, without writing device code. The library’s OFS server does it in one call: it serves the OpenFunscripter WebSocket API, speaks ofs-ws-extended and announces itself over Funlink. RustyFunPlayer shows a Connect card, follows your playback and drives every device the user has, on every axis, with the user’s limits.
1. Start the server
import { serveOfs } from "funlink";
const ofs = await serveOfs({
id: "my-game", // stable per installation
name: "My Game",
version: "1.0.0",
onEvent: (event) => {
if (event.type === "devices") showDevices(event.state.outputs);
if (event.type === "command") handleCommand(event.name, event.data); // change_play, change_time, …
},
});
// On exit:
await ofs.close();
#![allow(unused)]
fn main() {
use funlink::ofs::{OfsEvent, OfsServer};
let ofs = OfsServer::builder("My Game")
.id("my-game") // stable per installation
.version("1.0.0")
.start(|event| match event {
OfsEvent::Devices { state, .. } => show_devices(&state.outputs),
OfsEvent::Command { name, data, .. } => handle_command(&name, &data),
_ => {}
})?;
// Dropping `ofs` stops it.
}
using Funlink;
await using var ofs = await OfsServer.StartAsync(
new OfsServerOptions("My Game") { Id = "my-game", Version = "1.0.0" },
e =>
{
switch (e)
{
case OfsDevicesChanged d: ShowDevices(d.State.Outputs); break;
case OfsCommand c: HandleCommand(c.Name, c.Data); break;
}
});
import io.github.faplandpartydev.funlink.*;
try (var ofs = Ofs.serve(OfsOptions.of("My Game").withId("my-game").withVersion("1.0.0"), event -> {
if (event instanceof OfsEvent.Devices d) showDevices(d.state().outputs());
if (event instanceof OfsEvent.Command c) handleCommand(c.name(), c.data());
})) {
// Run your app.
}
The OFS server is not part of the C library: microcontrollers are the devices, not the player.
The OFS server is not part of the Godot add-on. A Godot .NET game can use the C# library’s OfsServer; a GDScript game can serve the OFS WebSocket API itself with WebSocketPeer and announce it with the add-on.
| Option | Default | Meaning |
|---|---|---|
id | required | Your app’s fixed Funlink id, such as my-game. It also picks the port. |
name, version | – | Shown on the player’s card and sent in the handshake. |
path | /ofs | WebSocket path. |
announce | on | Announce over Funlink. Turn off to only serve. |
extended | on | Speak ofs-ws-extended. Off serves plain OFS only. |
The server listens on 127.0.0.1 only and refuses web pages and, on Linux, other users.
Port
You do not choose a port: it is derived from the id, so your app gets the same port on every machine and other apps rarely collide. my-game always serves on 21976. If that port is busy, the next free one is used. ofsPort(id) (default_port, DefaultPortFor, defaultPort) tells you the number up front, for example to show it in your settings. The rule is part of the ofs-ws-extended specification.
Players find you through Funlink, so users never type the port. Only if a user must pin one, pass manualPort (manual_port, ManualPort, withManualPort); it is used exactly and fails if taken.
2. Tell it what plays
Call the setters whenever something changes. The server keeps the latest state and replays it to every player that connects later.
ofs.setMedia("/videos/round.mp4"); // null when nothing plays
ofs.setDuration(60);
ofs.setScript("round.funscript", script); // the parsed funscript object
ofs.setScript("round.twist.funscript", twist); // more axes: name them like files
ofs.setPlaying(true);
ofs.setTime(video.currentTime); // as often as you like
ofs.setSpeed(1);
ofs.removeScript("round.twist.funscript");
ofs.clearScripts();
#![allow(unused)]
fn main() {
ofs.set_media(Some("/videos/round.mp4")); // None when nothing plays
ofs.set_duration(60.0)?;
ofs.set_script("round.funscript", script)?; // serde_json::Value
ofs.set_script("round.twist.funscript", twist)?;
ofs.set_playing(true);
ofs.set_time(position)?;
ofs.set_speed(1.0)?;
ofs.remove_script("round.twist.funscript");
ofs.clear_scripts();
}
ofs.SetMedia("/videos/round.mp4"); // null when nothing plays
ofs.SetDuration(60);
ofs.SetScript("round.funscript", script); // JsonElement
ofs.SetScript("round.twist.funscript", twist);
ofs.SetPlaying(true);
ofs.SetTime(position);
ofs.SetSpeed(1);
ofs.RemoveScript("round.twist.funscript");
ofs.ClearScripts();
ofs.setMedia("/videos/round.mp4"); // null when nothing plays
ofs.setDuration(60);
ofs.setScript("round.funscript", script); // Map/List as parsed JSON
ofs.setScript("round.twist.funscript", twist);
ofs.setPlaying(true);
ofs.setTime(position);
ofs.setSpeed(1);
ofs.removeScript("round.twist.funscript");
ofs.clearScripts();
The OFS server is not part of the C library: microcontrollers are the devices, not the player.
The OFS server is not part of the Godot add-on. A Godot .NET game can use the C# library’s OfsServer; a GDScript game can serve the OFS WebSocket API itself with WebSocketPeer and announce it with the add-on.
Name multi-axis scripts like files: round.funscript (stroke), round.twist.funscript, round.roll.funscript, … The player maps them to its axes.
3. Show and adjust devices
Players that speak ofs-ws-extended report their devices: the devices event carries each output’s kind, status, update rate and per-axis travel range, plus what plays. players lists the connected players with their latest state.
Move a device’s travel range, for example from your own settings screen:
ofs.setRange(undefined, "serial:0", "L0", 0.1, 0.9); // undefined = every extended player
#![allow(unused)]
fn main() {
ofs.set_range(None, "serial:0", "L0", 0.1, 0.9)?; // None = every extended player
}
ofs.SetRange(null, "serial:0", "L0", 0.1, 0.9); // null = every extended player
ofs.setRange("serial:0", "L0", 0.1, 0.9); // or setRange(playerId, …)
The OFS server is not part of the C library: microcontrollers are the devices, not the player.
The OFS server is not part of the Godot add-on. A Godot .NET game can use the C# library’s OfsServer; a GDScript game can serve the OFS WebSocket API itself with WebSocketPeer and announce it with the add-on.
The player applies the change like its own slider and reports it in the next devices event. Players without the extension simply get plain OFS.
4. Live scripts (generated on the fly)
Scripts don’t have to be files. For motion your app creates while it runs, for example from game state, open a live script and push actions as you go. Players that support funscript_append, such as RustyFunPlayer, extend the script in place without restarting the motion; others get the whole script again, a few times a second.
const live = ofs.liveScript("game.funscript");
ofs.setPlaying(true);
setInterval(() => {
const now = clock.ms(); // your media time in ms
ofs.setTime(now / 1000);
live.push(now + 200, intensity()); // ~200 ms ahead, pos 0–100
}, 100);
// Later:
live.remove();
#![allow(unused)]
fn main() {
let live = ofs.live_script("game.funscript")?;
ofs.set_playing(true);
loop {
let now = clock_ms();
ofs.set_time(now as f64 / 1000.0)?;
live.push(now + 200, intensity())?; // ~200 ms ahead, pos 0–100
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
using var live = ofs.CreateLiveScript("game.funscript");
ofs.SetPlaying(true);
while (running)
{
var now = clock.Milliseconds;
ofs.SetTime(now / 1000.0);
live.Push(now + 200, Intensity()); // ~200 ms ahead, pos 0–100
await Task.Delay(100);
}
try (var live = ofs.liveScript("game.funscript")) {
ofs.setPlaying(true);
while (running) {
long now = clock.millis();
ofs.setTime(now / 1000.0);
live.push(now + 200, intensity()); // ~200 ms ahead, pos 0–100
Thread.sleep(100);
}
}
The OFS server is not part of the C library: microcontrollers are the devices, not the player.
The OFS server is not part of the Godot add-on. A Godot .NET game can use the C# library’s OfsServer; a GDScript game can serve the OFS WebSocket API itself with WebSocketPeer and announce it with the add-on.
atis media time in milliseconds and must increase with every push;posis 0–100.- Push a little ahead of
setTime(100–250 ms) so the player can move smoothly towards the next point. - Use one live script per axis:
game.funscript,game.twist.funscript, … - Old actions are trimmed after
maxActions(8000 by default, which keeps each message under the 256 KiB limit).clear()empties the script,remove()ends it. - Players that connect later get the script so far, then the new actions.
Events
| Event | When |
|---|---|
connected | A player opened the socket; it has already received the current state. |
hello | The player speaks ofs-ws-extended; its name and version are known. |
devices | A device report arrived (state.outputs, state.axes, state.playback). |
command | The player asks you to change_play, change_time or change_playbackspeed. Apply it if you want; the server does not. |
disconnected | The player left. |
Without the library
The protocol is small enough to serve yourself. The rest of this page shows what the OFS server does on the wire.
Serve the OFS WebSocket API
Listen on 127.0.0.1 (for example ws://127.0.0.1:8080/ofs). Each message is one JSON text frame. Send these events whenever something changes:
| Event | data |
|---|---|
media_change | { "path": "/videos/round.mp4" }, or { "path": null } when nothing plays |
funscript_change | { "name": "round.funscript", "funscript": { ... } }, the whole script |
funscript_remove | { "name": "round.funscript" } |
project_change | {}: forget all scripts |
play_change | { "playing": true } |
time_change | { "time": 12.3 } in seconds |
duration_change | { "duration": 60.0 } |
playbackspeed_change | { "speed": 1.0 } |
Name multi-axis scripts like files: round.funscript (stroke), round.twist.funscript, round.roll.funscript, … The player maps them to its axes.
A minimal server with Node.js and ws:
import { WebSocketServer } from "ws";
const server = new WebSocketServer({ host: "127.0.0.1", port: 8080, path: "/ofs" });
const send = (name: string, data: unknown) =>
server.clients.forEach((c) => c.send(JSON.stringify({ type: "event", name, data })));
server.on("connection", (socket) => {
// Bring a new player up to date.
socket.send(JSON.stringify({ type: "event", name: "media_change", data: { path: "/videos/round.mp4" } }));
socket.send(JSON.stringify({ type: "event", name: "funscript_change",
data: { name: "round.funscript", funscript: script } }));
});
// From your player:
video.on("play", () => send("play_change", { playing: true }));
video.on("pause", () => send("play_change", { playing: false }));
video.on("timeupdate", () => send("time_change", { time: video.currentTime }));
The player may send change_play, change_time and change_playbackspeed commands with the same shapes; you may ignore them.
Announce it
import { announce } from "funlink";
const funlink = announce({
id: installId,
name: "My Game",
services: [{ protocol: "ofs-ws", endpoint: "ws://127.0.0.1:8080/ofs" }],
});
The user clicks Connect on the card and playback starts following your app.
Show and adjust devices
With ofs-ws-extended the player also reports its devices on the same socket, and your app can change their travel ranges, for example to show “Handy connected, stroke 10–90 %” in your settings.
-
Announce the same endpoint twice, extended first:
services: [ { protocol: "ofs-ws-extended", endpoint: "ws://127.0.0.1:8080/ofs" }, { protocol: "ofs-ws", endpoint: "ws://127.0.0.1:8080/ofs" }, ], -
Answer the player’s hello:
socket.on("message", (raw) => { const message = JSON.parse(String(raw)); if (message.type === "command" && message.name === "device_hello") { socket.send(JSON.stringify({ type: "event", name: "device_hello", data: { protocol: 1, application: "My Game", version: "1.0.0" } })); } if (message.type === "command" && message.name === "device_state") { showDevices(message.data.outputs); // status, rate and axis ranges per output } }); -
Move a range:
socket.send(JSON.stringify({ type: "event", name: "device_set_range", data: { output: "serial:0", axis: "L0", minimum: 0.1, maximum: 0.9 } }));
Players that do not know the extension keep the plain OFS behavior, so step 3 never breaks anything. Field details are in the ofs-ws-extended reference.
Announce an EDI game
Games with an EDI mod call an EDI server over HTTP to play named scenes. RustyFunPlayer can be that server. When the game announces itself, RustyFunPlayer offers to play it, starts serving EDI on the game’s port and loads its gallery.
Announce the edi service on the port the game calls, and tell the hub where the game is installed with the org.rustyfunplayer.edi extension:
{
"id": "castle-of-temptation",
"name": "Castle of Temptation",
"services": [{ "protocol": "edi", "endpoint": "http://127.0.0.1:5000/" }],
"ext": {
"org.rustyfunplayer.edi": {
"root": "/games/Castle",
"executable": "/games/Castle/Castle.exe",
"config": "/games/Castle/Edi/EdiConfig.json"
}
}
}
ext field | Meaning |
|---|---|
root | The game folder. |
executable | The game’s program, inside root. |
config | The game’s EdiConfig.json, inside root. RustyFunPlayer recognizes the game by it, so your card replaces the one its own game detector shows. |
Paths are absolute paths of the host system. Under Wine or Proton, translate Z:\games\Castle to /games/Castle first.
announce({
id: "castle-of-temptation",
name: "Castle of Temptation",
services: [{ protocol: "edi", endpoint: "http://127.0.0.1:5000/" }],
ext: { "org.rustyfunplayer.edi": { root, executable, config } },
});
#![allow(unused)]
fn main() {
funlink::announce(
Announcement::new("castle-of-temptation", "Castle of Temptation")
.service(Protocol::Edi, "http://127.0.0.1:5000/")
.ext("org.rustyfunplayer.edi", serde_json::json!({
"root": root, "executable": executable, "config": config,
})),
)?;
}
FunlinkPeer.Announce(new Announcement("castle-of-temptation", "Castle of Temptation",
[new Service(Protocol.Edi, "http://127.0.0.1:5000/")])
{
Ext = new Dictionary<string, JsonElement>
{
["org.rustyfunplayer.edi"] = JsonSerializer.SerializeToElement(new { root, executable, config }),
},
});
Funlink.announce(Announcement.of("castle-of-temptation", "Castle of Temptation",
Service.of(Protocol.EDI, "http://127.0.0.1:5000/"))
.withExt("org.rustyfunplayer.edi", Map.of("root", root, "executable", executable, "config", config)));
EDI games run on the computer and announce over loopback, which the C library does not do. Use one of the other libraries, the Godot add-on, or plain HTTP.
var funlink := FunlinkPeer.new()
func _ready() -> void:
var executable := OS.get_executable_path()
var root := executable.get_base_dir()
funlink.app_id = "castle-of-temptation"
funlink.app_name = "Castle of Temptation"
funlink.services = [{"protocol": "edi", "endpoint": "http://127.0.0.1:5000/"}]
funlink.ext = {"org.rustyfunplayer.edi": {
"root": root, "executable": executable, "config": root.path_join("Edi/EdiConfig.json")}}
add_child(funlink)
Under Wine or Proton, OS.get_executable_path() returns a Windows path; translate it first.
Unity games can do this from a BepInEx plugin; any HTTP client works, see Without a library.
Announce a Wi-Fi device
A device on the local network, such as an ESP32 stroker that takes TCode over UDP, announces itself without a library: it sends the beacon and registers a DNS-SD service. A hub with local network discovery turned on, such as RustyFunPlayer, then offers to play on it.
Hubs only listen on the local network when their user turned that on, and they always ask before they connect to a device there.
The C library does all of this for Arduino boards (ESP32, ESP8266, Pico W) and other C firmware, with fixed buffers and fuzzed parsers. The rest of this page shows what it sends, for firmware that cannot use it.
With the C library
Install Funlink-arduino-0.1.0.zip from the release (how), then:
#include <Funlink.h>
const uint16_t TCODE_PORT = 8000; // where the device takes TCode over UDP
Funlink funlink;
WiFiUDP tcode;
char id[32];
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin("your-network", "your-password"); // gitleaks:allow (placeholder)
while (WiFi.status() != WL_CONNECTED) delay(100);
WiFi.setSleep(false); // ESP32: modem sleep misses multicast queries
// A stable id from the MAC address; the session changes at every boot by itself.
uint8_t mac[6];
WiFi.macAddress(mac);
snprintf(id, sizeof id, "sr6-%02x%02x%02x", mac[3], mac[4], mac[5]);
tcode.begin(TCODE_PORT);
funlink.addService("tcode-udp", TCODE_PORT);
if (!funlink.begin(id, "SR6", "1.0.0")) {
Serial.println(funlink_strerror(funlink.lastError()));
}
}
void loop() {
funlink.loop();
int size = tcode.parsePacket();
if (size > 0) {
// ... read the TCode and drive the motors ...
}
}
The zip’s examples/TCodeUdpDevice sketch also works on ESP8266 and reports the connected hub.
#include "funlink_core.h"
static funlink_peer peer; /* about 3.3 KB: keep it static */
void funlink_setup(uint32_t now_ms) {
funlink_platform platform = {0};
platform.send = my_send; /* sends a datagram from the given socket */
platform.random = my_random32;
platform.local_address = my_ipv4; /* for the mDNS A record */
funlink_service service = {"tcode-udp", NULL, 8000, NULL, NULL};
funlink_record record = {0};
record.id = "sr6-a41c";
record.name = "SR6";
record.services = &service;
record.service_count = 1;
funlink_peer_init(&peer, &platform);
if (funlink_peer_configure(&peer, &record, now_ms) == FUNLINK_OK) funlink_peer_start(&peer, now_ms);
}
/* Hand every received datagram to funlink_peer_on_datagram(), call
funlink_peer_poll() every few milliseconds and funlink_peer_stop() on exit. */
Three sockets: port 37420 joined to 239.255.37.20, port 5353 joined to 224.0.0.251, and one on a random port that sends and receives hub answers. The repository’s c/test/posix_peer.c is a complete Linux host.
Without the library
What the device sends
- Its record, with
0.0.0.0as the host of every endpoint. The hub uses the address the packet came from instead, so the record does not need to know the device’s IP address. - No
icon; keep the record under 1200 bytes. - A stable
id, for example derived from the chip’s MAC address, and a new randomsessionat every boot.
ESP32 (Arduino)
The sketch below does both transports. Replace SR6, the port and the TCode handling with your device’s.
#include <WiFi.h>
#include <WiFiUdp.h>
#include <ESPmDNS.h>
const uint16_t TCODE_PORT = 8000; // where the device takes TCode over UDP
const uint16_t FUNLINK_PORT = 37420;
const IPAddress FUNLINK_GROUP(239, 255, 37, 20);
const IPAddress BROADCAST(255, 255, 255, 255);
WiFiUDP sender; // sends announces from a random port; hub status replies arrive here
WiFiUDP listener; // port 37420: hub queries
String id;
char session[17];
String announce;
uint32_t lastAnnounce = 0;
IPAddress lastAsker;
uint32_t lastAnswer = 0;
void sendAnnounce(IPAddress to, uint16_t port) {
sender.beginPacket(to, port);
sender.print(announce);
sender.endPacket();
}
void setup() {
WiFi.begin("ssid", "password");
while (WiFi.status() != WL_CONNECTED) delay(100);
WiFi.setSleep(false); // modem sleep misses multicast queries
id = "sr6-" + String((uint32_t)ESP.getEfuseMac(), HEX);
snprintf(session, sizeof session, "%08lx%08lx",
(unsigned long)esp_random(), (unsigned long)esp_random());
announce = String("{\"funlink\":1,\"type\":\"announce\",\"id\":\"") + id +
"\",\"session\":\"" + session +
"\",\"name\":\"SR6\",\"version\":\"1.0.0\",\"services\":[{\"protocol\":\"tcode-udp\","
"\"endpoint\":\"udp://0.0.0.0:" + TCODE_PORT + "\"}]}";
sender.begin(0);
listener.beginMulticast(FUNLINK_GROUP, FUNLINK_PORT);
// DNS-SD: _funlink._udp.local with the record in TXT.
MDNS.begin((String("funlink-") + session).c_str());
MDNS.setInstanceName(String("SR6 ") + String(session).substring(0, 8));
MDNS.addService("funlink", "udp", TCODE_PORT);
MDNS.addServiceTxt("funlink", "udp", "v", "1");
MDNS.addServiceTxt("funlink", "udp", "id", id);
MDNS.addServiceTxt("funlink", "udp", "s", session);
MDNS.addServiceTxt("funlink", "udp", "n", "SR6");
MDNS.addServiceTxt("funlink", "udp", "ver", "1.0.0");
MDNS.addServiceTxt("funlink", "udp", "p0",
String("tcode-udp udp://0.0.0.0:") + TCODE_PORT);
}
void loop() {
// Announce every 5 seconds to the group and as a broadcast.
if (millis() - lastAnnounce >= 5000 || lastAnnounce == 0) {
lastAnnounce = millis();
sendAnnounce(FUNLINK_GROUP, FUNLINK_PORT);
sendAnnounce(BROADCAST, FUNLINK_PORT);
}
// Answer a hub's query, only to the hub, at most once per second per hub.
if (listener.parsePacket() > 0) {
char buffer[256];
int length = listener.read(buffer, sizeof buffer - 1);
buffer[length > 0 ? length : 0] = 0;
IPAddress hub = listener.remoteIP();
uint16_t port = listener.remotePort();
bool query = strstr(buffer, "\"funlink\":1") && strstr(buffer, "\"type\":\"query\"");
if (query && (hub != lastAsker || millis() - lastAnswer >= 1000)) {
delay(random(20, 121));
sendAnnounce(hub, port);
lastAsker = hub;
lastAnswer = millis();
}
}
// Hubs answer each announce with a status; read it to show "connected".
if (sender.parsePacket() > 0) {
sender.flush();
}
// ... handle TCode on TCODE_PORT ...
}
ESPmDNS answers queries with its own TTLs, which is fine: hubs only treat a TTL of 0 as a goodbye and otherwise forget a device 15 seconds after they last heard of it.
Check it
On Linux, avahi-browse -rt _funlink._udp lists the device with its TXT record. To see the beacon, listen on the port:
socat -u UDP4-RECVFROM:37420,reuseaddr,ip-add-membership=239.255.37.20:0.0.0.0,fork -
In RustyFunPlayer, turn on Settings > Funlink > Find apps and devices on the local network. On NixOS, also set programs.rustyfunplayer.funlinkLan.openFirewall = true; so the firewall lets the packets in.
Security
Anyone on the network can send these packets, and anyone can connect to the device’s TCode port. Hubs therefore ask before every new device and remember answers per address. Keep such devices on a home network you trust, and do not forward their ports to the internet.
Godot game
The Godot add-on announces a game to Funlink hubs such as RustyFunPlayer. It is plain GDScript for Godot 4.2 or later: copy it in, add one node, and hubs offer the player a one-click Connect to the services your game runs, such as an OFS WebSocket or a Buttplug server.
1. Add the add-on
Download funlink-godot-0.1.0.zip from the release and unpack it so that addons/funlink/ sits next to project.godot. Enabling it under Project Settings > Plugins is optional.
2. Announce
Add a FunlinkPeer node to a scene that lives as long as the game, or create one in an autoload:
extends Node
var funlink := FunlinkPeer.new()
func _ready() -> void:
funlink.app_id = "my-game"
funlink.app_name = "My Game"
funlink.app_version = "1.0.0"
funlink.icon = preload("res://icon.svg")
funlink.services = [{"protocol": "ofs-ws", "endpoint": "ws://127.0.0.1:8080/ofs"}]
add_child(funlink)
The node announces when it enters the tree and every 5 seconds after, also while the game is paused. It says bye when it leaves the tree or the window closes.
When a service starts or stops, change services and call funlink.update().
3. Show the hub’s answer
funlink.hubs_changed.connect(func(hubs: Array) -> void:
var names := hubs.filter(func(hub): return hub.state == "connected").map(func(hub): return hub.hub.name)
$Status.text = "Connected to " + ", ".join(names) if names else "")
Each entry has hub (id, name, maybe version), supported, state and address.
4. Optional: the local network
For a game on a Steam Deck or a standalone headset that should reach RustyFunPlayer on a PC, set funlink.lan = true before adding the node, and let your services listen on all interfaces instead of 127.0.0.1. lan_hosts also sends the announce to fixed addresses, such as a hub on another subnet. See Local network for what changes.
Exports
- Android: enable the INTERNET permission in the export preset.
- Web: browsers cannot open these sockets;
start()returnsERR_UNAVAILABLE. - Godot .NET: you may use the C# library instead, which also finds hubs.
License
The add-on is under the LGPL-3.0-or-later with a linking exception, so a game can ship it inside its export without providing the means to relink it. Changes to the add-on itself stay under the LGPL.
Electron app
Run Funlink in Electron’s main process: it needs Node’s HTTP server and runs while windows come and go. Talk to the renderer over IPC.
This example is a device player such as FunSync Player: it drives devices through Buttplug and TCode over WebSocket, so it runs a hub for those two protocols and asks the user before connecting.
// npm install https://github.com/FapLandPartyDev/funlink/releases/download/v0.1.0/funlink-0.1.0.tgz
import { app, BrowserWindow, ipcMain } from "electron";
import { startHub, type Peer } from "funlink";
app.whenReady().then(async () => {
const window = new BrowserWindow();
const hub = await startHub({
name: "FunSync Player",
version: app.getVersion(),
supports: ["buttplug-ws", "tcode-ws"],
onEvent: (event) => {
// Offer each new app once. A `lost` event withdraws the offer.
if (event.type === "found" && event.peer.state === "available") {
window.webContents.send("funlink:offer", event.peer);
}
if (event.type === "lost") window.webContents.send("funlink:withdraw", event.peer.id);
},
});
// The renderer answers the offer with "connect" or "dismiss".
ipcMain.handle("funlink:answer", async (_event, peer: Peer, answer: "connect" | "dismiss") => {
if (answer === "dismiss") {
hub.setState(peer, "dismissed");
return;
}
const [service] = peer.usable;
if (!service) return;
// Hand the endpoint to FunSync's existing connection code, for example:
// if (service.protocol === "buttplug-ws") await connectButtplug(service.endpoint);
// else await connectTcodeWebSocket(service.endpoint);
hub.setState(peer, "connected");
});
app.on("before-quit", () => void hub.close());
});
// If FunSync later offers a service of its own, announcing it is one call:
//
// import { announce, customProtocol } from "funlink";
// const funlink = announce({
// id: "funsync-player",
// name: "FunSync Player",
// services: [{ protocol: customProtocol("funsync", "ws"), endpoint: "ws://127.0.0.1:5123/ws" }],
// });
// app.on("before-quit", () => void funlink.close());
The renderer shows the offer with Connect and Not now and answers through funlink:answer. Remember Always connect choices by peer.id and connect without asking next time.
To announce from Electron instead, call announce() in the main process when your server is listening, and close() in before-quit.
Without a library
Any language that can send HTTP can be a peer: POST the full record to each Funlink port every 5 seconds, and ignore connection errors (no hub on that port).
- Create an
idonce and store it (a UUID). Create a randomsession(8–32 letters and digits) at every launch. - Every 5 seconds,
POST http://127.0.0.1:<port>/funlink/v1/announcewithContent-Type: application/jsonto each port from 37420 to 37429. Use a 1-second timeout. Use127.0.0.1, notlocalhost. - On a clean exit, optionally
POST /funlink/v1/byewith{ "id": …, "session": … }.
while true; do
for port in $(seq 37420 37429); do
curl -sS -m 1 -X POST "http://127.0.0.1:$port/funlink/v1/announce" \
-H 'Content-Type: application/json' \
-d '{"id":"my-tool","session":"abcd1234","name":"My Tool","services":[{"protocol":"ofs-ws","endpoint":"ws://127.0.0.1:8080/ofs"}]}' \
>/dev/null 2>&1 &
done
sleep 5
done
const record = {
id: installId, // stored on first run
session: crypto.randomUUID().replaceAll("-", ""),
name: "My Tool",
services: [{ protocol: "ofs-ws", endpoint: "ws://127.0.0.1:8080/ofs" }],
};
function announce() {
for (let port = 37420; port <= 37429; port++) {
fetch(`http://127.0.0.1:${port}/funlink/v1/announce`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(record),
signal: AbortSignal.timeout(1000),
}).catch(() => {});
}
}
announce();
setInterval(announce, 5000);
import json, secrets, threading, time, urllib.request
record = {
"id": install_id, # stored on first run
"session": secrets.token_hex(8),
"name": "My Tool",
"services": [{"protocol": "ofs-ws", "endpoint": "ws://127.0.0.1:8080/ofs"}],
}
body = json.dumps(record).encode()
def announce_forever():
while True:
for port in range(37420, 37430):
request = urllib.request.Request(
f"http://127.0.0.1:{port}/funlink/v1/announce",
data=body, headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(request, timeout=1).close()
except OSError:
pass
time.sleep(5)
threading.Thread(target=announce_forever, daemon=True).start()
// A MonoBehaviour, for example in a BepInEx plugin. Older Unity versions
// cannot reference the Funlink NuGet package, so this posts by hand.
IEnumerator Announce()
{
var body = System.Text.Encoding.UTF8.GetBytes(recordJson);
while (true)
{
for (var port = 37420; port <= 37429; port++)
{
var request = new UnityWebRequest($"http://127.0.0.1:{port}/funlink/v1/announce", "POST")
{
uploadHandler = new UploadHandlerRaw(body),
downloadHandler = new DownloadHandlerBuffer(),
timeout = 1,
};
request.SetRequestHeader("Content-Type", "application/json");
request.SendWebRequest(); // fire and forget
}
yield return new WaitForSeconds(5);
}
}
/* POSIX: announce once to every Funlink port. Call it every 5 seconds. */
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
static const char *BODY =
"{\"id\":\"my-tool\",\"session\":\"abcd1234\",\"name\":\"My Tool\","
"\"services\":[{\"protocol\":\"ofs-ws\",\"endpoint\":\"ws://127.0.0.1:8080/ofs\"}]}";
void funlink_announce(void) {
for (int port = 37420; port <= 37429; port++) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) continue;
struct timeval timeout = {1, 0};
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout);
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof timeout);
struct sockaddr_in hub = {.sin_family = AF_INET, .sin_port = htons((uint16_t)port)};
hub.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(fd, (struct sockaddr *)&hub, sizeof hub) == 0) {
char request[1024];
int length = snprintf(request, sizeof request,
"POST /funlink/v1/announce HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"
"Content-Type: application/json\r\nContent-Length: %zu\r\n"
"Connection: close\r\n\r\n%s",
port, strlen(BODY), BODY);
send(fd, request, (size_t)length, 0);
char reply[512];
recv(fd, reply, sizeof reply, 0); /* the hub's answer, if you want it */
}
close(fd);
}
}
For a Wi-Fi device, use the C library instead: it announces on the local network.
# Without the add-on: one HTTPRequest per port, every 5 seconds.
extends Node
var body := JSON.stringify({"id": "my-game", "session": "abcd1234", "name": "My Game",
"services": [{"protocol": "ofs-ws", "endpoint": "ws://127.0.0.1:8080/ofs"}]})
func _ready() -> void:
var timer := Timer.new()
timer.wait_time = 5.0
timer.timeout.connect(_announce)
add_child(timer)
timer.start()
_announce()
func _announce() -> void:
for port in range(37420, 37430):
var request := HTTPRequest.new()
request.timeout = 1.0
add_child(request)
request.request_completed.connect(func(_result, _code, _headers, _body): request.queue_free())
if request.request("http://127.0.0.1:%d/funlink/v1/announce" % port,
["Content-Type: application/json"], HTTPClient.METHOD_POST, body) != OK:
request.queue_free()
The Godot add-on does this for you, with a random session, the bye and the local network.
Keep the rules in mind when you write the record by hand: field limits are in the record table, and endpoints must be on a loopback host. A hub answers 400 invalid_announce with a message that names the broken field.
Browsers: a hub may refuse web pages, and RustyFunPlayer does. Announce from a native process.
Funlink v1
Status: draft. The name and port range are provisional.
Funlink lets an application tell other local applications that it is running and which services it offers. A hub such as RustyFunPlayer can then offer the user a one-click “Connect” prompt instead of manual endpoint setup.
Funlink only handles discovery. The actual connection still uses the application’s existing protocol, such as the OFS WebSocket API or Buttplug.
Quick start
To announce your application, send this JSON every 5 seconds:
POST http://127.0.0.1:<port>/funlink/v1/announce
Content-Type: application/json
to each port from 37420 to 37429. Ignore connection errors: no hub is listening on that port. That is all a peer must do.
{
"id": "8d0c6a8e-3f0e-4c38-9a57-2f1d6b0c9e11",
"session": "f3a91c0e5b7d",
"name": "FapLand",
"version": "1.4.0",
"services": [
{ "protocol": "ofs-ws", "endpoint": "ws://127.0.0.1:8080/ofs" }
]
}
Optionally send POST /funlink/v1/bye on a clean exit so the hub removes the
entry immediately.
Terms
- Peer: an application that announces itself, for example FapLand.
- Hub: an application that receives announcements and offers to connect, for example RustyFunPlayer.
- Service: one endpoint that a peer offers, identified by a protocol.
The key words MUST, MUST NOT, SHOULD and MAY are used as in RFC 2119.
Transport
- HTTP/1.1 over TCP on the loopback interface, without TLS.
- Hubs listen on
127.0.0.1and bind the first free port from 37420 to 37429. - Peers connect to
127.0.0.1. They SHOULD NOT uselocalhost, which may resolve to::1first. - Bodies are UTF-8 JSON with
Content-Type: application/json. - If the environment variable
FUNLINK_PORTis set, hubs bind and peers send to that single port only. This is meant for tests and unusual setups.
Announce
POST /funlink/v1/announce
A peer MUST send an announce when it starts and then every 5 seconds while it runs. Each announce carries the complete record; there are no partial updates. Peers SHOULD use a request timeout of about 1 second.
Record
| Field | Required | Type | Rules |
|---|---|---|---|
id | yes | string | Stable for the peer. 1 to 64 characters from A-Z a-z 0-9 . _ -. A fixed name for the application is recommended, such as fapland or org.example.player; it also seeds the OFS port. A random UUID created on first run also works. |
session | yes | string | Random for each launch of the peer. 8 to 32 characters from A-Z a-z 0-9. |
name | yes | string | Display name, 1 to 64 characters. |
version | no | string | Display version, up to 32 characters. |
icon | no | string | data:image/png;base64,..., square, 128 px recommended, at most 512 px on each side. The whole URI is at most 64 KiB. |
services | yes | array | 1 to 8 service objects. |
ext | no | object | Application-specific data. Keys MUST be reverse domain names such as org.fapland. |
Service
| Field | Required | Type | Rules |
|---|---|---|---|
protocol | yes | string | A registered protocol name, or x-<vendor>-<name> for unregistered ones. |
endpoint | yes | string | Absolute URL. The host MUST be a loopback address: 127.0.0.0/8 or [::1]. The scheme MUST match the protocol. |
features | no | array | Up to 16 strings that describe optional capabilities. |
Response
On success the hub answers 200 OK:
{
"hub": { "id": "4b1e...", "name": "RustyFunPlayer", "version": "0.1.0" },
"supported": ["ofs-ws", "buttplug-ws"],
"state": "available"
}
state | Meaning |
|---|---|
available | The hub knows the peer and may offer it to the user. |
connected | The hub is connected to one of the peer’s services. |
dismissed | The user declined for this session. The hub will not prompt again until the session changes. |
unsupported | The hub cannot use any of the announced services. |
Peers MAY ignore the response. Peers that read it can, for example, show “Connected to RustyFunPlayer”.
Bye
POST /funlink/v1/bye
{ "id": "8d0c6a8e-3f0e-4c38-9a57-2f1d6b0c9e11", "session": "f3a91c0e5b7d" }
The hub answers 204 No Content and removes the entry. Sending bye is
optional; without it the entry expires.
Errors
Errors use an HTTP status and this body:
{ "code": "invalid_announce", "message": "services[0].endpoint must use a loopback host" }
| Status | code | Cause |
|---|---|---|
| 400 | invalid_announce | The record does not follow this specification. |
| 403 | forbidden | The Host or Origin header was rejected. |
| 404 | not_found | Unknown path, including unsupported versions. |
| 413 | too_large | The body exceeds 96 KiB. |
| 429 | rate_limited | Requests for the same id less than 200 ms apart, or more than 64 peers. |
Hub rules
A hub:
- MUST forget an entry 15 seconds after its last announce, or immediately on
bye. - MUST treat an announce with the same
idand a newsessionas a restart of that peer. - MUST reject requests whose
Hostheader is not127.0.0.1:<port>,localhost:<port>or[::1]:<port>. This blocks DNS rebinding. - MUST NOT connect to a service because of an announce alone. It connects only
after the user confirms, or after the user earlier chose to always connect
to that
id. - SHOULD prompt at most once per
sessionand SHOULD NOT prompt while it is already connected to a source. - MUST reject bodies larger than 96 KiB.
- SHOULD refuse connections from other users of the machine where the operating system names the owner of a loopback socket, as Linux does.
Browsers
Browser-based peers can announce with fetch. Because the body is JSON, the
browser sends a CORS preflight. A hub that accepts browser peers answers
OPTIONS with Access-Control-Allow-Origin set to the request origin,
Access-Control-Allow-Methods: POST and
Access-Control-Allow-Headers: Content-Type. Browsers may additionally ask
the user for local network access.
When an Origin header is present, the hub MUST show that origin in the
prompt and MUST store “always connect” decisions per origin and id, never per
id alone. A hub MAY reject all browser origins.
Local network
Everything above happens on one machine. A peer on another machine of the local network, such as a TCode device with Wi-Fi or a player on a Steam Deck, announces the same record through two transports instead:
- DNS-SD over multicast DNS (RFC 6762 and RFC 6763), the standard that
Bonjour and Avahi implement, under the service type
_funlink._udp.local. - The Funlink beacon: the record as JSON in a UDP datagram on port 37420, sent to a multicast group and as a broadcast.
Hubs that support the local network listen on both and merge what they hear.
A peer MAY use either transport or both; small firmware may prefer the beacon,
which needs no DNS stack, and DNS-SD makes the peer visible in standard
browsers such as avahi-browse or Bonjour Browser.
Discovery on the local network is a separate choice on both sides. A hub MUST NOT listen on the local network unless its user turned that on, and a peer announces there only when the application asks for it.
Endpoints
A peer does not know which of its addresses a hub reaches it by, so it writes
the host of each endpoint as 0.0.0.0, such as ws://0.0.0.0:8080/ofs. A hub
MUST replace the host of every endpoint with the source address of the packet
that carried the record, whatever host the record names. A record therefore
cannot point a hub at another machine. An IPv6 source address is written in
brackets, with a zone as in RFC 6874, such as ws://[fe80::1%25eth0]:8080/.
Services whose scheme does not name a network socket, such as unix or
serial, MUST be dropped; a record without other services is ignored. The
services of a local network record listen on a network interface, so anyone
on the network can connect to them, and peers SHOULD protect them
accordingly.
Record limits
A local network record is the record of Announce with these differences:
- It has no
icon. - Over DNS-SD it has no
exteither. - The whole record, encoded as described below, fits in 1200 bytes.
DNS-SD
A peer registers one instance of _funlink._udp.local:
- Instance name: the display name, cut to at most 54 bytes at a character
boundary, a space and the first 8 characters of the session, such as
Stroker f3a91c0e. Hubs ignore instance names. - SRV: target
funlink-<session>.local, with an A record of each of the peer’s IPv4 addresses. The port is the port of the first service. Hubs ignore the target and the port. - TXT, with
vfirst. Hubs accept the other keys in any order.
| Key | Required | Value |
|---|---|---|
v | yes | 1 |
id | yes | The record’s id. |
s | yes | The record’s session. |
n | yes | The record’s name. |
ver | no | The record’s version. |
p0 to p7 | p0 | Service N as its protocol, a space and its endpoint, such as ofs-ws ws://0.0.0.0:8080/ofs. |
f0 to f7 | no | The features of service N, separated by commas. |
Services are numbered from 0 without gaps; a hub stops at the first missing
p<N>. Each key=value string is at most 255 bytes, as DNS requires, and
the TXT data is at most 1200 bytes. Features MUST NOT contain commas in a
record announced over DNS-SD.
Timing:
- PTR, SRV and TXT records SHOULD have a TTL of 15 seconds and A records one of 120 seconds. Hubs do not rely on other TTLs than 0, so the defaults of an existing mDNS stack also work.
- A peer announces its records unsolicited when it starts, again 1 second
later, and whenever the record changes. It answers every query for
_funlink._udp.localby multicast after a random delay of 20 to 120 milliseconds, with the PTR record as the answer and the SRV, TXT and A records as additional records. On a clean exit it sends the same records with a TTL of 0. - A hub sends a query for the PTR records of
_funlink._udp.localto224.0.0.251:5353when it starts, 1 second later and then every 5 seconds. It MUST NOT list known answers, so that every peer answers each query. - A hub reads every response that carries a PTR record of
_funlink._udp.localwith the instance’s SRV and TXT records in the same packet, and MAY query SRV and TXT on their own when a response lacks them. A record with a TTL of 0 counts as a bye.
IPv4 is required. Peers and hubs MAY also use [ff02::fb]:5353.
Beacon
Every beacon datagram is one UTF-8 JSON object of at most 1200 bytes with the
fields funlink, which is 1, and type. Receivers MUST ignore datagrams
that are larger, are not such an object, have another funlink value, or
have an unknown type, without answering them.
The beacon uses UDP port 37420, the multicast group 239.255.37.20 and the
limited broadcast address 255.255.255.255. If the environment variable
FUNLINK_LAN_PORT is set, hubs and peers use that port instead; this is
meant for tests.
type | Sender | Other fields |
|---|---|---|
announce | Peer | The record: id, session, name, version, services, ext. |
bye | Peer | id, session. |
query | Hub | None. |
status | Hub | id and session of the peer, then hub, supported and state as in the response to an announce. |
{"funlink":1,"type":"announce","id":"sr6-a41c","session":"f3a91c0e5b7d","name":"SR6","services":[{"protocol":"tcode-udp","endpoint":"udp://0.0.0.0:8000"}]}
A peer:
- binds port 37420 with address reuse (
SO_REUSEADDR, andSO_REUSEPORTwhere it exists), so that several peers and hubs share it, and joins the multicast group on each IPv4 interface; a peer that cannot set address reuse, such as one written in a game engine without that option, MUST NOT bind the port, so that it never keeps a hub on the same machine from listening; it then answers no queries, and hubs find it by its next announce; - sends its datagrams from a second socket on a random port, so that answers reach it and not another program on port 37420;
- sends
announcewhen it starts and then every 5 seconds, each time to the multicast group and to the broadcast address; - answers a
querywith anannouncesent only to the query’s source address and port, after a random delay of 20 to 120 milliseconds, and at most once per second for each source address; - MAY send
byeto the group and the broadcast address on a clean exit.
A hub:
- binds and joins like a peer, and sends from a second socket on a random port;
- sends
queryto the group and the broadcast address when it starts, 1 second later and whenever the user asks to search again; - MAY send
queryto addresses that the user entered, which reaches peers on other subnets. It repeats these queries every 5 seconds, because the announces of such peers do not cross the router; - treats an
announcethat answers its query like any other; - answers each
announcewith astatussent only to its source address and port, at most once per second for each peer. Peers MAY ignore it.
Hub rules for the local network
On top of the hub rules, a hub:
- MUST ignore packets whose source address is not a loopback address, a
private IPv4 address (
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16), a link-local address (169.254.0.0/16,fe80::/10) or a unique local IPv6 address (fc00::/7). - MUST validate the record as an announce, except that endpoint hosts are replaced as described in Endpoints and not checked.
- MUST key entries by source address and
id. The same key heard over DNS-SD and the beacon is one entry; its record is the latest one heard, butextfrom the beacon stays until the beacon record changes or expires. - MUST ignore a local network record with the
idandsessionof a peer that announces over loopback HTTP, and drops such an entry when the loopback announce arrives later. - MUST treat a record with the
idandsessionof an existing entry but from another source address, such as from a peer with Wi-Fi and Ethernet, as a sign of life of that entry only. It neither creates a second entry nor changes the record or address of the first. - MUST forget an entry 15 seconds after it last heard the record by either
transport, or at once on
byeor a DNS-SD TTL of 0. - MUST NOT keep more than 64 entries from the local network, nor more than 8 from one source address, and ignores records for one key and transport that arrive less than 200 milliseconds apart. A peer announces over both transports at once, so the gap does not apply across them.
- MUST NOT act on
extdata of a local network record that names files, programs or processes, because it describes another machine. - MUST show the source address in the prompt and MUST store “always connect”
and “never ask” decisions per address and
id, never peridalone.
Compatibility rules
- Receivers MUST ignore unknown fields, unknown
statevalues, unknown protocols and unknown features. - Fields keep their meaning and type in all v1 revisions.
- Only incompatible changes create a new path, such as
/funlink/v2/. A peer MAY announce to several versions.
Protocol registry
protocol | Endpoint schemes | Description |
|---|---|---|
ofs-ws | ws, wss | OpenFunscripter WebSocket API. |
ofs-ws-extended | ws, wss | OpenFunscripter WebSocket API with device state and range edits. See ofs-ws-extended. Announced beside an ofs-ws service with the same endpoint. |
ofs-ws-fapland | ws, wss | Alias of ofs-ws-extended that FapLand announces. Hubs that support one of the two MUST support both. |
buttplug-ws | ws, wss | Buttplug protocol server, such as Intiface. |
vlc-http | http | VLC HTTP interface. |
mpc-http | http | MPC-HC web interface. |
whirligig-tcp | tcp | Whirligig timecode server. |
tcode-ws | ws, wss | TCode device over WebSocket. |
tcode-tcp | tcp | TCode device over TCP. |
tcode-udp | udp | TCode device over UDP. |
edi | http | A game that expects an EDI server at the endpoint. The hub serves it instead of connecting to it. |
mpv-ipc | unix | An mpv player’s JSON IPC socket. The endpoint’s path is the socket on this machine, such as unix://127.0.0.1/run/user/1000/mpv.sock. |
tcode-serial | serial | A TCode device on a serial port of this machine. The endpoint’s path is the port, such as serial://127.0.0.1/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0. The hub connects an output to it, beside any source. |
New entries are added by request with a short description and a link to the
protocol’s documentation. Names starting with x- need no registration.
Examples
An EDI game
A game with an EDI mod announces the edi service on the port it calls, and
tells RustyFunPlayer where it is installed. The paths are absolute paths of the
host system, so a game under Wine translates its Z:\ paths first. The program
and the configuration lie inside root, and the configuration is the game’s
EdiConfig.json. Use your own id; RustyFunPlayer recognizes the game by its
config, so its card replaces the one for the same game found by
rustyfunplayer-detect.
{
"id": "castle-of-temptation",
"session": "b81c4e0a92d3",
"name": "Castle of Temptation",
"services": [{ "protocol": "edi", "endpoint": "http://127.0.0.1:5000/" }],
"ext": {
"org.rustyfunplayer.edi": {
"root": "/games/Castle",
"executable": "/games/Castle/Castle.exe",
"config": "/games/Castle/Edi/EdiConfig.json"
}
}
}
Shell
curl -sS -X POST http://127.0.0.1:37420/funlink/v1/announce \
-H 'Content-Type: application/json' \
-d '{"id":"test","session":"abcdefgh","name":"Test","services":[{"protocol":"ofs-ws","endpoint":"ws://127.0.0.1:8080/ofs"}]}'
JavaScript (Node.js 18+ and Electron)
The same code runs in a browser, but RustyFunPlayer refuses browser requests (see Browsers).
const record = {
id: installId, // stored on first run
session: crypto.randomUUID().replaceAll("-", ""),
name: "FapLand",
version: "1.4.0",
services: [{ protocol: "ofs-ws", endpoint: "ws://127.0.0.1:8080/ofs" }],
};
function announce() {
for (let port = 37420; port <= 37429; port++) {
fetch(`http://127.0.0.1:${port}/funlink/v1/announce`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(record),
signal: AbortSignal.timeout(1000),
}).catch(() => {});
}
}
announce();
setInterval(announce, 5000);
Python
import json, secrets, time, urllib.request
record = {
"id": install_id, # stored on first run
"session": secrets.token_hex(8),
"name": "Example",
"services": [{"protocol": "ofs-ws", "endpoint": "ws://127.0.0.1:8080/ofs"}],
}
body = json.dumps(record).encode()
def announce():
for port in range(37420, 37430):
request = urllib.request.Request(
f"http://127.0.0.1:{port}/funlink/v1/announce",
data=body,
headers={"Content-Type": "application/json"},
)
try:
urllib.request.urlopen(request, timeout=1).close()
except OSError:
pass
# Run this loop on a background thread in a real application.
while True:
announce()
time.sleep(5)
Implementations
- RustyFunPlayer is a hub.
- FapLand announces its OFS bridge as
ofs-ws. - The libraries in this repository implement both roles.
Planned extensions
These are intentionally left out of v1:
- Coordination between several hubs, so that a service used by one hub is not offered by another.
- A peer request such as “connect me now” for a button in the peer’s UI.
- Pairing with keys, so that a hub can trust a peer on the local network across addresses and connect to it without asking.
- A hub that announces itself on the local network.
ofs-ws-extended v1
Status: draft.
ofs-ws-extended is the OpenFunscripter (OFS) WebSocket API plus device
state. Many apps already send their media and scripts to a device player such as
RustyFunPlayer through the OpenFunscripter (OFS) WebSocket API. This extension
lets the device player tell the app about its devices on the same socket, and
lets the app adjust their travel ranges. An app can then show “Handy connected,
stroke 10–90 %” in its own interface without speaking any device protocol.
Players and apps that do not know the extension keep the plain OFS behavior.
Terms
- App: the program that serves the OFS WebSocket API, for example FapLand.
- Player: the program that connects to it and drives devices, for example RustyFunPlayer.
The key words MUST, MUST NOT, SHOULD and MAY are used as in RFC 2119.
The OFS WebSocket API in short
The app serves a WebSocket, by convention at ws://127.0.0.1:<port>/ofs, and
the player connects to it. Each message is one JSON text frame:
{ "type": "event", "name": "time_change", "data": { "time": 12.3 } }
The app sends events:
name | data |
|---|---|
media_change | { "path": "/videos/round.mp4" }, or null path when nothing plays |
play_change | { "playing": true } |
time_change | { "time": 12.3 } in seconds |
duration_change | { "duration": 60.0 } in seconds |
playbackspeed_change | { "speed": 1.0 } |
funscript_change | { "name": "round.funscript", "funscript": { ... } } with the whole script |
funscript_remove | { "name": "round.funscript" } |
project_change | {}: forget all scripts |
The player may send the commands change_play, change_time and
change_playbackspeed with the same data shapes. An app MAY ignore them.
Port
Apps choose their own port once, derived from their Funlink id, so each app keeps the same port on every machine and two apps rarely collide:
h = 0x811C9DC5 // FNV-1a, 32 bit
for each byte b of the id in UTF-8:
h = (h XOR b) * 0x01000193 mod 2^32
port = 20000 + (h mod 10000)
If the port is taken, the app tries the next one, wrapping from 29999 to 20000, up to 100 times. Example: the id my-game gives port 21976. Apps SHOULD use this rule and SHOULD only offer a fixed port as an advanced setting. Players never rely on the number: they take the endpoint from the Funlink announcement.
Discovery
An app that implements this extension announces its socket over
Funlink twice, as ofs-ws-extended and as ofs-ws, with the same
endpoint:
"services": [
{ "protocol": "ofs-ws-extended", "endpoint": "ws://127.0.0.1:8080/ofs" },
{ "protocol": "ofs-ws", "endpoint": "ws://127.0.0.1:8080/ofs" }
]
Hubs that know the extension use the ofs-ws-extended service and MUST NOT
offer the ofs-ws service with the same endpoint separately. Other hubs ignore
the unknown protocol and connect with plain OFS. An app that serves only plain
OFS announces only ofs-ws.
ofs-ws-fapland is an alias of ofs-ws-extended that FapLand announces
instead, so hubs can present it as FapLand. It means exactly the same, and a
hub that supports one of the two names MUST support both. Other apps use
ofs-ws-extended.
Handshake
Right after connecting, a player that implements the extension sends:
{ "type": "command", "name": "device_hello", "data": { "protocol": 1, "application": "RustyFunPlayer", "version": "0.1.0" } }
An app that implements it answers:
{ "type": "event", "name": "device_hello", "data": { "protocol": 1, "application": "FapLand", "version": "0.6.32" } }
| Field | Type | Rules |
|---|---|---|
protocol | integer | The highest version of this extension the sender speaks. Both sides use the lower of the two values. |
application | string | Display name, up to 200 characters. |
version | string or null | Display version, up to 100 characters. |
features | array of strings, optional | Optional capabilities the sender supports, such as funscript_append. Unknown values are ignored. |
An app that does not know the extension ignores the command, and the session stays plain OFS. The extension is active once the player has the app’s answer.
State
While the extension is active, the player sends device_state at once when an
output, axis or playback value changes, and at least every second so the app
can follow the media position.
{
"type": "command",
"name": "device_state",
"data": {
"outputs": [
{
"id": "serial:0",
"kind": "Serial",
"detail": "/dev/ttyUSB0",
"status": "connected",
"error": null,
"rate": 60,
"axes": [{ "axis": "L0", "enabled": true, "minimum": 0.0, "maximum": 1.0 }]
}
],
"axes": [
{ "axis": "L0", "name": "Up/Down", "script": "round.funscript", "motionProvider": null, "link": null, "syncing": false }
],
"playback": { "media": "round.mp4", "playing": true, "position": 12.3, "duration": 60.0, "speed": 1.0 }
}
}
Each message carries the complete state.
| Field | Rules |
|---|---|
outputs[].id | Stable for the session, up to 100 characters. |
outputs[].kind, detail | Display text for the device type and its address. |
outputs[].status | connected, connecting, disconnecting, disconnected or failed. |
outputs[].error | Display text while failed, otherwise null. |
outputs[].rate | Update rate in Hz, or null. |
outputs[].axes[] | TCode axis (L0, R1, …), whether the output drives it, and its travel range as fractions from 0 to 1. |
axes[] | Every axis the player knows: display name, the script that drives it, a motion provider name, the axis it follows (link), and syncing while it blends back to its script after a seek or media change. |
playback | What the player plays, in seconds. |
At most 64 outputs and 64 axes per message. Receivers MUST ignore unknown
fields and unknown status values.
Live scripts
Scripts that an app generates while it runs, for example from game state, exist only in memory and grow over time. Resending the whole script with funscript_change makes a player treat it as a new script, which can restart its motion. A player that lists funscript_append in its device_hello features accepts appends instead:
{ "type": "event", "name": "funscript_append", "data": { "name": "live.funscript", "actions": [{ "at": 12500, "pos": 80 }, { "at": 12750, "pos": 20 }] } }
| Field | Rules |
|---|---|
name | Script name, as in funscript_change. If the player has no script of that name, it starts one with these actions. |
actions | 1 to 1000 actions in media time: at in milliseconds, pos from 0 to 100. Each at must be later than the script’s last action; earlier ones are ignored. |
The player extends the script in place: it MUST NOT resynchronize, restart or blend the motion because of an append. It MAY drop actions that lie well behind the playback position to bound memory.
Send actions a little ahead of the media time, about 100 to 250 ms, so the player can interpolate towards them. Apps MUST NOT send funscript_append to players that did not list the feature; they send the whole script with funscript_change instead, at most a few times a second. funscript_change and funscript_remove for the same name replace or remove the live script as usual.
Range edits
While the extension is active, the app may move both travel bounds of one output axis:
{ "type": "event", "name": "device_set_range", "data": { "output": "serial:0", "axis": "L0", "minimum": 0.1, "maximum": 0.9 } }
minimum and maximum are fractions from 0 to 1 with minimum < maximum.
The player applies the change like its own range slider and reports it in the
next device_state. It ignores edits for unknown outputs or axes.
Rules
- Messages are at most 256 KiB.
- Apps SHOULD listen on
127.0.0.1only. Where the operating system names the owner of a loopback socket, as Linux does, apps SHOULD refuse players of other users. - New fields may be added within version 1. Incompatible changes raise
protocol.
Library API
The four full libraries share one design: announce for peers, start a hub for hubs, typed protocols, and an error with a spec error code. The table maps the names; details follow per language. Doc comments in each package carry the full API.
| Concept | TypeScript | Rust | C# | Java |
|---|---|---|---|---|
| Announce | announce(a, { onHubs }) | funlink::announce(a) / Announcer::builder(a).on_hubs(f).start() | FunlinkPeer.Announce(a, onHubs) | Funlink.announce(a, onHubs) |
| Update | announcer.update(a) | announcer.update(a)? | peer.Update(a) | announcer.update(a) |
| Stop peer | await announcer.close() | drop / close() | await DisposeAsync() | close() |
| Start hub | await startHub(options) | Hub::builder(name).supports(..).start(f)? | await FunlinkHub.StartAsync(options, f) | Funlink.hub(options, f) |
| Record answer | hub.setState(peer, state) | hub.set_state(&peer, state) | hub.SetState(peer, state) | hub.setState(peer, state) |
| Stop hub | await hub.close() | drop / close() | await DisposeAsync() | close() |
| Serve OFS (ofs-ws-extended) | await serveOfs(options) | OfsServer::builder(name).start(f)? | await OfsServer.StartAsync(options, f) | Ofs.serve(options, f) |
| Feed it | setMedia, setScript, setPlaying, setTime, … | set_media, set_script, … | SetMedia, SetScript, … | setMedia, setScript, … |
| Move a range | setRange(player?, output, axis, min, max) | set_range(..)? | SetRange(..) | setRange(..) |
| Local network peer | announce(a, { lan: true }) | Announcer::builder(a).lan(true).start() | FunlinkPeer.Announce(a, options: new AnnounceOptions { Lan = true }) | Funlink.announcer(a).lan(true).start() |
| Local network hub | lan: true, queryHosts, hub.search() | .lan(true), .query_hosts(..), hub.search() | Lan, QueryHosts, hub.Search() | withLan(true), withQueryHosts(..), hub.search() |
| Network address of a peer | peer.address | peer.address | peer.Address | peer.address() |
| Custom protocol | customProtocol(v, n) | Protocol::custom(v, n)? | Protocol.Custom(v, n) | Protocol.custom(v, n) |
| Error | FunlinkError (.code) | funlink::Error (.code()) | FunlinkException (.Code) | FunlinkException (.code()) |
The C library and the Godot add-on are peers only; they have sections of their own below.
TypeScript
announce(announcement: Announcement, options?: { onHubs?(hubs: HubStatus[]): void; lan?: boolean }): Announcer
// Announcer: session, hubs, update(a), close(); AsyncDisposable
startHub(options: {
name: string; version?: string; id?: string;
supports: Protocol[];
onEvent(event: HubEvent): void;
allowBrowsers?: boolean;
lan?: boolean; queryHosts?: string[];
}): Promise<Hub>
// Hub: info, port, peers, search(), setState(peer, "available" | "connected" | "dismissed"), close(); AsyncDisposable
type HubEvent =
| { type: "found"; peer: Peer }
| { type: "updated"; peer: Peer }
| { type: "lost"; peer: Peer; reason: "bye" | "expired" | "restarted" };
// Peer: id, session, name, version?, icon?, services, ext?, origin?, address?, state, usable
await using works with both objects. Also exported: REGISTERED_PROTOCOLS, DEFAULT_PORTS, isRegistered.
Rust
#![allow(unused)]
fn main() {
Announcement::new(id, name).version(..).icon(..).service(Protocol, endpoint)
.with_service(Service::new(p, e).feature(..)).ext(key, serde_json::Value)
funlink::announce(a) -> Result<Announcer, Error>
Announcer::builder(a).on_hubs(|&[HubStatus]| ..).lan(bool).port(p).start()
// Announcer: session(), hubs(), update(a), close(); says bye on Drop
Hub::builder(name).version(..).id(..).supports([..]).allow_browsers(bool)
.lan(bool).query_hosts([IpAddr]).port(p)
.start(|HubEvent| ..) -> Result<Hub, Error>
// Hub: info(), port(), peers(), search(), set_state(&peer, PeerState) -> Option<Peer>; stops on Drop
// Peer::address: Option<IpAddr>, Some for local network peers
enum HubEvent { Found(Peer), Updated(Peer), Lost { peer, reason: LostReason } } // #[non_exhaustive]
}
Plain threads, no async runtime. Callbacks run on a library thread.
C#
new Announcement(id, name, [new Service(protocol, endpoint) { Features = [..] }])
{ Version = .., Icon = .., Ext = new Dictionary<string, JsonElement> { .. } }
FunlinkPeer.Announce(announcement, Action<IReadOnlyList<HubStatus>>? onHubs = null,
AnnounceOptions? options = null) // new AnnounceOptions { Lan = true }
// FunlinkPeer: Session, Hubs, Update(a); IAsyncDisposable
await FunlinkHub.StartAsync(new HubOptions(name, supports) { Version = .., Id = .., AllowBrowsers = .., Lan = .., QueryHosts = [..] },
Action<HubEvent> onEvent)
// FunlinkHub: Info, Port, Peers, Search(), SetState(peer, PeerState) -> Peer?; IAsyncDisposable
// Peer.Address: IPAddress?, set for local network peers
// Events: PeerFound(Peer), PeerUpdated(Peer), PeerLost(Peer, LostReason)
.NET 8+, no dependencies, trimming and AOT friendly.
Java
Announcement.of(id, name, Service.of(protocol, endpoint), ...)
.withVersion(..).withIcon(..).withServices(..).withExt(key, value)
Funlink.announce(announcement[, Consumer<List<HubStatus>> onHubs]) -> Announcer
Funlink.announcer(announcement).onHubs(..).lan(true).start() -> Announcer
// Announcer: session(), hubs(), update(a), close(); AutoCloseable
Funlink.hub(HubOptions.of(name, protocols...).withVersion(..).withId(..).withBrowsers(bool)
.withLan(bool).withQueryHosts(InetAddress...),
Consumer<HubEvent> onEvent) -> Hub
// Hub: info(), port(), peers(), search(), setState(peer, PeerState) -> Optional<Peer>, close(); AutoCloseable
// Peer.address(): Optional<InetAddress>, present for local network peers
// sealed interface HubEvent: Found(peer), Updated(peer), Lost(peer, reason)
Java 17+, JPMS module io.github.faplandpartydev.funlink. Callbacks run on background threads, one at a time; exceptions go to the thread’s uncaught exception handler.
C and Arduino
A peer for the local network only, without malloc, for ESP32, ESP8266, Pico W and POSIX systems. See its README for the platform callbacks.
// Arduino
Funlink funlink;
funlink.addService(protocol, port[, path, features, scheme]);
funlink.setExt(json);
funlink.begin(id, name[, version, transports]) -> bool // FUNLINK_TRANSPORT_ALL, _BEACON or _MDNS
funlink.loop(); funlink.end();
funlink.connectedHub() -> const char*; funlink.hub() -> const funlink_hub*
funlink.session(); funlink.lastError() -> funlink_err
/* C */
funlink_peer_init(&peer, &platform);
funlink_peer_configure(&peer, &record, now_ms) -> funlink_err
funlink_peer_start(&peer, now_ms) -> funlink_err
funlink_peer_on_datagram(&peer, socket, from_ip, from_port, data, length, now_ms);
funlink_peer_poll(&peer, now_ms);
funlink_peer_stop(&peer, now_ms);
funlink_peer_session(&peer) -> const char*
funlink_strerror(err) -> const char*
Godot
A GDScript node for Godot 4.2 or later that announces over loopback HTTP and, with lan, over the beacon. See Godot game.
FunlinkPeer.new()
# Properties: app_id, app_name, app_version, services (Array of {protocol, endpoint, features?}),
# icon (Texture2D), ext (Dictionary), lan, lan_hosts, autostart
# Methods: start() -> Error, update() -> Error, stop(), is_running()
# Signal: hubs_changed(hubs: Array) # each {hub, supported, state, address}
# Read-only: session, hubs, last_error
OFS server
All four full libraries: options id, name, version, port derived from id (ofsPort / default_port / DefaultPortFor / defaultPort; advanced override manualPort), path (/ofs), announce (on), extended (on); events connected, hello, devices, command, disconnected; players, endpoint, port, hubs. Bad numbers (NaN, infinity) and empty script names are rejected (TypeScript/Rust/Java: invalid_argument error; C#: ArgumentException). See Send scripts to a device player.
Ports
All libraries use 37420–37429, or only FUNLINK_PORT when it is set (Java also -Dfunlink.port=). Rust builders also take .port(p).
Errors
A hub answers a bad request with an HTTP status and a JSON body:
{ "code": "invalid_announce", "message": "services[0].endpoint must use a loopback host" }
The libraries raise the same codes (FunlinkError, funlink::Error, FunlinkException).
| Code | Status | Cause | Fix |
|---|---|---|---|
invalid_announce | 400 | The record breaks a rule; the message names the field. | Check the record limits. Common: endpoint not on 127.0.0.1, wrong scheme for the protocol, id with spaces, unregistered protocol name without x-. |
forbidden | 403 | The Host or Origin header was refused. | Send to 127.0.0.1, not a LAN address. Web pages are refused by hubs that do not accept browsers. |
not_found | 404 | Unknown path or version. | Use /funlink/v1/announce and /funlink/v1/bye. |
too_large | 413 | Body over 96 KiB. | Shrink the icon (≤ 64 KiB) or ext. |
rate_limited | 429 | Same id less than 200 ms apart, or more than 64 apps. | Announce every 5 s; the libraries pace themselves. |
no_port | – | Library only: all ports 37420–37429 are taken, so a hub cannot start. | Close another hub, or set FUNLINK_PORT. |
Connection refused on a port just means no hub listens there; ignore it.
Contributing
The repository holds the specification, the four libraries, the C library for microcontrollers and the Godot add-on. Changes to the wire format go into SPEC.md first, then into every library, which must stay compatible with each other.
Run the tests
| Library | Command |
|---|---|
| TypeScript | cd typescript && npm ci && npm test |
| Rust | cd rust && cargo test |
| C# | cd csharp && dotnet test |
| Java | cd java && mvn verify |
| C | make -C c test sanitize lint |
| Godot | godot --headless --path godot --script res://test/test_record.gd, then bash godot/test/interop/run.sh (needs typescript built) |
Set FUNLINK_PORT to keep tests away from a hub that already runs on your machine.
Register a protocol
Open an issue with the protocol name, its endpoint schemes, a short description and a link to its documentation. Until then, use x-<vendor>-<name>.
Edit this site
The site is built with mdBook from website/:
nix run nixpkgs#mdbook -- serve website --open
The specification pages include SPEC.md and OFS-WS-EXTENDED.md from the repository root, so edit those files directly.
License
The libraries are LGPL-3.0-or-later: applications under any license may use them; changes to the libraries themselves stay under the LGPL. The C library and the Godot add-on add a linking exception, so firmware and games may include them without providing the means to relink.