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.

11.4 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 { 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('.');
}

// 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' };

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.LINUX, port: self.port || P.PORT };
    this.found = new Map(); // id -> {id, name, os, address, port, fp, lastSeen, invited}
    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 }) => ({ id, name, os: o, address, port, fp, invited: !!invited }));
    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) {
    return this.found.get(id) || null;
  }

  // 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 */ }
      this._setStatus(false, '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));
    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 d = {
      id: m.id,
      name: typeof m.name === 'string' && m.name ? m.name.slice(0, 100) : DEFAULT_NAME[o],
      os: o,
      address: rinfo.address,
      port,
      fp: P.normFingerprint(m.fp),
      lastSeen: Date.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)
    };
    this.found.set(m.id, d);
    const w = this.waiters.get(rinfo.address);
    if (w) w(d);
    if (m.t === P.T.INVITE) this.emit('invite', d);
    if (!old || 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) {
      if (now - d.lastSeen > P.DEVICE_STALE_MS) {
        this.found.delete(id);
        changed = true;
      }
    }
    if (changed) this.emit('change');
  }
}

// The interface of the default IPv4 route with the lowest metric (/proc/net/route), or ''.
function defaultIface(text) {
  let best = null;
  try {
    for (const line of String(text != null ? text : require('fs').readFileSync('/proc/net/route', 'utf8')).split('\n').slice(1)) {
      const f = line.trim().split(/\s+/);
      if (f.length < 8 || f[1] !== '00000000' || f[7] !== '00000000') continue; // destination and mask 0: a default route
      if (!(parseInt(f[3], 16) & 1)) continue; // RTF_UP
      const metric = Number(f[6]) || 0;
      if (!best || metric < best.metric) best = { name: f[0], metric };
    }
  } catch (_) { /* no /proc */ }
  return best ? best.name : '';
}

const VIRTUAL = /^(docker|br-|veth|virbr|tun|tap|wg|tailscale|zt|vmnet|vboxnet|lxc|lxd|podman|cni|flannel)/;
const kindOf = (name) => (VIRTUAL.test(name) ? 'virtual' : /^wl/.test(name) ? 'wifi' : /^(en|eth)/.test(name) ? 'ethernet' : 'other');

// This computer's addresses, best first (#350): the interface picked in General (prefer, by name),
// then the one on the connected device's network, then the one of the default route, then wired,
// Wi-Fi and the rest, virtual ones last. All of them stay in the list: only the order changes.
function rankAddresses(list, { peer = '', prefer = '', def = '' } = {}) {
  const onPeerNet = (i) => isIPv4(peer) && ((ipToInt(i.address) ^ ipToInt(peer)) & ipToInt(i.netmask)) === 0;
  const rank = (i) => (prefer && i.name === prefer ? 0 : onPeerNet(i) ? 1 : VIRTUAL.test(i.name) ? 6 : def && i.name === def ? 2
    : kindOf(i.name) === 'ethernet' ? 3 : 4);
  return list.map((i, n) => ({ i, n })).sort((a, b) => rank(a.i) - rank(b.i) || a.n - b.n).map((x) => x.i.address);
}

// For General's Network for TwinDesk list: [{name, kind, address}], one per interface (read at most
// every 5 s: it goes out with every state push).
let choices = { at: 0, list: [] };
function ifaceChoices(list) {
  if (!list && Date.now() - choices.at < 5000) return choices.list;
  const fresh = !list;
  list = list || interfaces();
  const seen = new Map();
  for (const i of list) if (!seen.has(i.name)) seen.set(i.name, { name: i.name, kind: kindOf(i.name), address: i.address });
  const out = [...seen.values()];
  if (fresh) choices = { at: Date.now(), list: out };
  return out;
}

module.exports = { Discovery, interfaces, isIPv4, ipToInt, defaultIface, rankAddresses, ifaceChoices };