Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

12.9 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Discovery v2: one UDP socket on DISCOVERY_PORT that sends our
// beacon to every broadcast address, answers probes, sends probes, takes invites, and keeps the
// list of other TwinDesk computers nearby (Macs, PCs, Linux).
//
// Events: 'change' (found list or status changed); 'invite' (device): a Mac asked us to connect.
'use strict';

const dgram = require('dgram');
const os = require('os');
const { execFile } = require('child_process');
const { EventEmitter } = require('events');
const P = require('../shared/protocol.js');

const RETRY_BIND_MS = 5000;

function ipToInt(ip) {
  return ip.split('.').reduce((n, o) => ((n << 8) | Number(o)) >>> 0, 0);
}

function intToIp(n) {
  return [24, 16, 8, 0].map((s) => (n >>> s) & 255).join('.');
}

// The networks a device is seen on (its routes) and the order they are tried in (link.js).
const VIRTUAL = /vEthernet|Hyper-V|WSL|VirtualBox|VMware|Loopback|tun|tap|TAP|VPN|WireGuard|Tailscale|ZeroTier|OpenVPN|Npcap|Bluetooth/i;
const sameNet = (i, address) => ((ipToInt(i.address) ^ ipToInt(address)) & ipToInt(i.netmask)) === 0;
// This PC's adapter on the network `address` is on: {name, address} or null (reached through a router).
function adapterFor(address, list = interfaces()) {
  if (!isIPv4(address)) return null;
  const i = list.find((x) => sameNet(x, address));
  return i ? { name: i.name, address: i.address } : null;
}
// Lower is better: on one of our networks, then a cable, Wi-Fi, others, and VPN or VM adapters last.
function routeRank(r) {
  if (!r.via) return 5;
  return VIRTUAL.test(r.via) ? 4 : /^Ethernet|以太网/i.test(r.via) ? 1 : /^Wi-?Fi|WLAN|无线/i.test(r.via) ? 2 : 3;
}
// Routes in the order they are tried: the preferred address first (when it is there), then by rank.
// routes: [{address, via, local}], prefer: an address or ''.
function orderRoutes(routes, prefer) {
  const list = routes.slice().sort((a, b) => routeRank(a) - routeRank(b) || a.address.localeCompare(b.address));
  const i = prefer ? list.findIndex((r) => r.address === prefer) : -1;
  if (i > 0) list.unshift(list.splice(i, 1)[0]);
  return list;
}

// Non-internal IPv4 interfaces: [{name, address, netmask, broadcast}]
function interfaces() {
  const out = [];
  for (const [name, list] of Object.entries(os.networkInterfaces())) {
    for (const i of list || []) {
      if (i.family !== 'IPv4' || i.internal) continue;
      if (/^169\.254\./.test(i.address)) continue; // link-local: no DHCP answer, nobody to find
      const bc = (ipToInt(i.address) | ~ipToInt(i.netmask)) >>> 0;
      out.push({ name, address: i.address, netmask: i.netmask, broadcast: intToIp(bc) });
    }
  }
  return out;
}

const isIPv4 = (s) => /^(\d{1,3})(\.\d{1,3}){3}$/.test(s) && s.split('.').every((o) => Number(o) < 256);

const DEFAULT_NAME = { mac: 'Mac', win: 'PC', linux: 'Linux' };

// The default gateways (route print), looked up in the background every 30 s: on a phone's
// hotspot that is the phone, which may not get broadcasts its own hotspot passes on, so beacons go
// to it directly too. Never waited for: the beacon goes with what is known.
let cachedGateways = [];
let lastGwCheck = 0;
function defaultGateways() {
  const now = Date.now();
  if (now - lastGwCheck > 30000) {
    lastGwCheck = now;
    execFile('route', ['print', '0.0.0.0'], { windowsHide: true, timeout: 3000 }, (err, out) => {
      if (err) return;
      const gws = [];
      for (const m of String(out).matchAll(/0\.0\.0\.0\s+0\.0\.0\.0\s+([0-9.]+)/g)) {
        if (isIPv4(m[1]) && !m[1].startsWith('127.') && !m[1].startsWith('0.') && !gws.includes(m[1])) gws.push(m[1]);
      }
      cachedGateways = gws;
    });
  }
  return cachedGateways;
}

class Discovery extends EventEmitter {
  // self: {id, name, fp?, port?}
  constructor(self) {
    super();
    this.reclaim = !!self.rc;
    this.self = { id: self.id, name: self.name, fp: self.fp || '', os: P.OS.WIN, port: self.port || P.PORT };
    // id -> {id, name, os, address, port, fp, lastSeen, invited, routes}. routes: address -> {address,
    // via (this PC's adapter on that network, '' through a router), local, lastSeen}. A computer on a
    // cable and on Wi-Fi is seen on both: each stays until it is quiet for DEVICE_STALE_MS, and
    // `address` is the best of them (orderRoutes), not the one whose beacon came last.
    this.found = new Map();
    this.status = { on: false, error: '' };
    this.waiters = new Map(); // address -> resolve(device) for unicast probes
    this.wantProbes = true; // main turns this off while connected
    this.sock = null;
    this.timers = [];
    this.sendErrors = new Set();
    this.extras = []; // Bluetooth (blepipe.js BleHost, BleGuest): devices near but not on this network, {list(), invite?(id)}
  }

  start() {
    this._bind();
    // One timer for all three (one wakeup every BEACON_MS): the beacon, the stale ones gone, and
    // every PROBE_MS a probe. Beacons stay at BEACON_MS: other computers drop us after DEVICE_STALE_MS.
    let n = 0;
    const every = Math.max(1, Math.round(P.PROBE_MS / P.BEACON_MS));
    this.timers.push(setInterval(() => {
      this._beacon();
      this._prune();
      if (++n % every === 0 && this.wantProbes) this.probe();
    }, P.BEACON_MS));
  }

  stop() {
    for (const t of this.timers) clearInterval(t);
    clearTimeout(this.bindTimer);
    if (this.sock) try { this.sock.close(); } catch (e) { /* closed */ }
    this.sock = null;
  }

  // On the network first; Bluetooth adds the ones it alone sees (ble: true, address 'ble:…').
  list() {
    const out = [...this.found.values()]
      .map(({ id, name, os: o, address, port, fp, invited, routes }) => ({ id, name, os: o, address, port, fp, invited: !!invited, routes: this._routes(routes) }));
    for (const x of this.extras) for (const d of x.list()) if (d.id !== this.self.id && !out.some((o) => o.id === d.id)) out.push({ ...d, invited: !!d.invited });
    return out.sort((a, b) => (b.invited - a.invited) || a.name.localeCompare(b.name));
  }

  get(id) {
    const d = this.found.get(id);
    return d ? { ...d, routes: this._routes(d.routes) } : null;
  }

  // A device's routes for the app, best first: [{address, via, local}].
  _routes(routes) {
    return orderRoutes([...(routes || new Map()).values()].map(({ address, via, local }) => ({ address, via, local })), '');
  }

  // Seen over Bluetooth only (not on this network): the list entry, else null.
  near(id) {
    if (this.found.has(id)) return null;
    for (const x of this.extras) {
      const d = x.list().find((e) => e.id === id);
      if (d) return d;
    }
    return null;
  }

  // The user acted on an invite (paired or cancelled): it is an ordinary entry again.
  clearInvite(id) {
    for (const x of this.extras) if (x.clearInvite) x.clearInvite(id);
    const d = this.found.get(id);
    if (d && d.invited) {
      d.invited = false;
      this.emit('change');
    }
  }

  // Broadcast a probe (everyone answers with a beacon), or unicast it to one address.
  probe(address) {
    const msg = { t: P.T.PROBE, v: P.PROTOCOL_VERSION, id: this.self.id };
    if (address) this._send(msg, address);
    else for (const target of this._targets()) this._send(msg, target);
  }

  // Ask a phone at address to connect to us (the phone tile; a phone has no server to pair with).
  invite(address) {
    if (String(address).startsWith('ble:')) {
      for (const x of this.extras) {
        const d = x.invite && x.list().find((e) => e.address === address);
        if (d) return x.invite(d.id);
      }
      return;
    }
    const { id, name, os: o, port, fp } = this.self;
    this._send({ t: P.T.INVITE, v: P.PROTOCOL_VERSION, id, name, os: o, port, fp }, address);
  }

  // Refresh: what was found is forgotten (an invite stays), and whoever is there answers again.
  refresh() {
    let changed = false;
    for (const [id, d] of this.found) if (!d.invited) changed = this.found.delete(id);
    if (changed) this.emit('change');
    this._beacon();
    this.probe();
    setTimeout(() => this.probe(), 500); // UDP may drop one
  }

  // Ask one address who is there; resolves to the device or null after PROBE_REPLY_MS.
  ask(address) {
    if (!isIPv4(address)) return Promise.resolve(null);
    return new Promise((resolve) => {
      const done = (d) => {
        clearTimeout(timer);
        this.waiters.delete(address);
        resolve(d);
      };
      const timer = setTimeout(() => done(null), P.PROBE_REPLY_MS);
      this.waiters.set(address, done);
      this.probe(address);
      setTimeout(() => this.waiters.has(address) && this.probe(address), 500); // UDP may drop one
    });
  }

  _bind() {
    const sock = dgram.createSocket({ type: 'udp4', reuseAddr: true });
    sock.on('message', (buf, rinfo) => this._onMessage(buf, rinfo));
    sock.on('error', (err) => {
      console.error('[discovery]', err.code || err.message);
      if (sock !== this.sock) return;
      this.sock = null;
      try { sock.close(); } catch (e) { /* closed */ }
      // EACCES / EADDRINUSE: another program holds the port for itself (one in WSL with mirrored
      // networking, #124). Tried again below.
      this._setStatus(false, err.code === 'EACCES' || err.code === 'EADDRINUSE'
        ? 'Port ' + P.DISCOVERY_PORT + ' is in use by another program (another copy of TwinDesk, or one in WSL)'
        : 'Can’t listen (' + (err.code || err.message) + ')');
      this.bindTimer = setTimeout(() => this._bind(), RETRY_BIND_MS);
    });
    this.sock = sock;
    sock.bind(P.DISCOVERY_PORT, () => {
      sock.setBroadcast(true);
      this._setStatus(true, '');
      this._beacon();
      this.probe();
    });
  }

  _setStatus(on, error) {
    if (this.status.on === on && this.status.error === error) return;
    Object.assign(this.status, { on, error });
    this.emit('change');
  }

  _targets() {
    const t = new Set(interfaces().map((i) => i.broadcast));
    for (const gw of defaultGateways()) t.add(gw);
    t.add('255.255.255.255');
    return t;
  }

  _beaconMsg() {
    const { id, name, os: o, port, fp } = this.self;
    const msg = { t: P.T.BEACON, v: P.PROTOCOL_VERSION, id, name, port, fp, os: o, role: 'host' };
    if (this.reclaim) msg.rc = 1; // a paired Android may come back by itself (shared/reclaim.js)
    return msg;
  }

  _beacon() {
    const msg = this._beaconMsg();
    for (const target of this._targets()) this._send(msg, target);
  }

  _send(msg, address, port) {
    if (!this.sock) return;
    this.sock.send(Buffer.from(JSON.stringify(msg)), port || P.DISCOVERY_PORT, address, (err) => {
      if (!err) return;
      const key = address + ':' + err.code;
      if (this.sendErrors.has(key)) return;
      this.sendErrors.add(key);
      console.error('[discovery] send to ' + address + ' failed: ' + (err.code || err.message));
    });
  }

  _onMessage(buf, rinfo) {
    let m;
    try {
      m = JSON.parse(buf.toString('utf8'));
    } catch (e) {
      return;
    }
    if (!m || m.v !== P.PROTOCOL_VERSION || typeof m.id !== 'string' || m.id === this.self.id) return;
    if (m.t === P.T.PROBE) return this._send(this._beaconMsg(), rinfo.address, rinfo.port);
    if (m.t !== P.T.BEACON && m.t !== P.T.INVITE) return;
    const port = Number.isInteger(m.port) && m.port > 0 && m.port < 65536 ? m.port : P.PORT;
    // Older beacons came only from Macs.
    const o = Object.values(P.OS).includes(m.os) ? m.os : P.OS.MAC;
    const old = this.found.get(m.id);
    const now = Date.now();
    const routes = new Map(old ? old.routes : []);
    const added = !routes.has(rinfo.address);
    const nic = adapterFor(rinfo.address);
    routes.set(rinfo.address, { address: rinfo.address, via: nic ? nic.name : '', local: nic ? nic.address : '', lastSeen: now });
    const d = {
      id: m.id,
      name: typeof m.name === 'string' && m.name ? m.name.slice(0, 100) : DEFAULT_NAME[o],
      os: o,
      address: orderRoutes([...routes.values()], '')[0].address,
      port,
      fp: P.normFingerprint(m.fp),
      lastSeen: now,
      invited: (old && old.invited) || m.t === P.T.INVITE,
      tv: m.tv === 1, // TwinDesk TV (android-tv/): a phone for the protocol, a TV in the lists (UI.osOf)
      routes,
    };
    this.found.set(m.id, d);
    const w = this.waiters.get(rinfo.address);
    if (w) w(this.get(m.id));
    if (m.t === P.T.INVITE) this.emit('invite', this.get(m.id));
    if (!old || added || old.name !== d.name || old.address !== d.address || old.os !== d.os || old.invited !== d.invited) this.emit('change');
  }

  _prune() {
    const now = Date.now();
    let changed = false;
    for (const [id, d] of this.found) {
      for (const [address, r] of d.routes) {
        if (now - r.lastSeen > P.DEVICE_STALE_MS) { d.routes.delete(address); changed = true; }
      }
      if (!d.routes.size) {
        this.found.delete(id);
      } else {
        const best = orderRoutes([...d.routes.values()], '')[0].address;
        if (best !== d.address) { d.address = best; changed = true; }
      }
    }
    if (changed) this.emit('change');
  }
}

module.exports = { Discovery, interfaces, isIPv4, ipToInt, sameNet, adapterFor, orderRoutes };