Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 21 additions & 9 deletions src/main/lan/discovery.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import dgram from 'dgram'
import { isPrivateAddress } from './privateAddress'
import { isPrivateAddress, reachableAt } from './privateAddress'
import { announcementsFrom, asksForService, decodePacket, encodeQuery } from './dnsSd'

const GROUP = '224.0.0.251'
Expand All @@ -17,8 +17,7 @@ function closeOnce(socket) {
})
}

export function createDiscovery({ addresses, announcement, onPeer }) {
const socket = dgram.createSocket({ type: 'udp4', reuseAddr: true })
function multicastSender(socket, addresses) {
const sendVia = (address, buf) =>
new Promise((done) => {
try {
Expand All @@ -29,10 +28,21 @@ export function createDiscovery({ addresses, announcement, onPeer }) {
}
})
const send = (buf) => Promise.all(addresses.map((address) => sendVia(address, buf)))
const announce = () => {
const packet = announcement()
if (packet) send(packet)
}
// One packet per interface, each naming that interface's own address.
const sendEach = (build) =>
Promise.all(
addresses.map((address) => {
const packet = build(address)
return packet ? sendVia(address, packet) : null
})
)
return { send, sendEach }
}

export function createDiscovery({ addresses, announcement, onPeer }) {
const socket = dgram.createSocket({ type: 'udp4', reuseAddr: true })
const { send, sendEach } = multicastSender(socket, addresses)
const announce = () => sendEach(announcement)
// A flood of queries gets one answer per gap; dropping the rest would hide this peer for a minute.
let answering = null
const answer = () => {
Expand All @@ -45,7 +55,9 @@ export function createDiscovery({ addresses, announcement, onPeer }) {
if (!isPrivateAddress(rinfo.address)) return
const packet = decodePacket(msg)
if (asksForService(packet)) return answer()
for (const peer of announcementsFrom(packet)) onPeer({ ...peer, address: rinfo.address })
for (const peer of announcementsFrom(packet)) {
onPeer({ ...peer, address: reachableAt(peer.addr, rinfo.address), source: rinfo.address })
}
})
socket.on('error', () => closeOnce(socket))
return new Promise((resolve, reject) => {
Expand All @@ -63,7 +75,7 @@ export function createDiscovery({ addresses, announcement, onPeer }) {
resolve({
announce,
query: () => send(encodeQuery()),
sendRaw: send,
sendEach,
close: () => {
clearTimeout(answering)
return closeOnce(socket)
Expand Down
13 changes: 10 additions & 3 deletions src/main/lan/dnsSd.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,15 @@ function txtData(entries) {
)
}

export function encodeAnnouncement({ fp, name, port, ttl = ANNOUNCE_TTL }) {
const IPV4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/

// addr names the sender's own interface: a router relaying mDNS between subnets
// replaces the packet's source with its own address, which has nothing listening.
export function encodeAnnouncement({ fp, name, port, ttl = ANNOUNCE_TTL, addr }) {
const instance = `${fp}.${SERVICE}`
const txt = txtData(['v=1', `fp=${fp}`, `name=${fitName(name)}`, `port=${port}`])
const fields = ['v=1', `fp=${fp}`, `name=${fitName(name)}`, `port=${port}`]
if (IPV4.test(addr ?? '')) fields.push(`addr=${addr}`)
const txt = txtData(fields)
const srv = Buffer.concat([u16(0), u16(0), u16(port), encodeName(`${fp}.local`)])
return Buffer.concat([
header({ response: true, answers: 3 }),
Expand Down Expand Up @@ -179,7 +185,8 @@ function peerFromTxt(txt, ttl) {
const ok =
txt.v === '1' && FP.test(txt.fp ?? '') && Number.isInteger(port) && port > 0 && port < 65536
if (!ok || typeof txt.name !== 'string') return null
return { fp: txt.fp, name: cleanPeerName(txt.name, NAME_CHARS), port, version: 1, ttl }
const peer = { fp: txt.fp, name: cleanPeerName(txt.name, NAME_CHARS), port, version: 1, ttl }
return IPV4.test(txt.addr ?? '') ? { ...peer, addr: txt.addr } : peer
}

export function announcementsFrom(packet) {
Expand Down
18 changes: 10 additions & 8 deletions src/main/lan/lan.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ const ipv4Addresses = () =>
.filter((a) => a.family === 'IPv4' || a.family === 4)
.map((a) => a.address)

function announcement(ctx, ttl) {
function announcement(ctx, ttl, addr) {
const { settings, server, selfFp } = ctx
return settings.visible && server?.port
? encodeAnnouncement({ fp: selfFp, name: settings.name, port: server.port, ttl })
? encodeAnnouncement({ fp: selfFp, name: settings.name, port: server.port, ttl, addr })
: null
}

Expand All @@ -37,9 +37,12 @@ async function open(ctx) {
})
ctx.discovery = await createDiscovery({
addresses: ctx.addresses,
announcement: () => announcement(ctx),
announcement: (addr) => announcement(ctx, undefined, addr),
onPeer: (peer) => {
if (!ctx.peers.saw(peer, ctx.now())) return
ctx.log?.(
`peer ${peer.fp.slice(0, 8)} at ${peer.address}:${peer.port} (named ${peer.addr ?? 'none'}, sent from ${peer.source})`
)
ctx.peerHandlers.forEach((handle) => handle(peer.fp))
ctx.onChange()
}
Expand All @@ -53,8 +56,7 @@ async function close(ctx) {
Object.assign(ctx, { discovery: null, server: null, addresses: [] })
ctx.peers.clear()
try {
const goodbye = announcement({ ...ctx, discovery, server }, 0)
if (goodbye) await discovery?.sendRaw(goodbye)
await discovery?.sendEach((addr) => announcement({ ...ctx, discovery, server }, 0, addr))
await discovery?.close()
} finally {
await server?.close()
Expand Down Expand Up @@ -105,8 +107,7 @@ async function toggle(ctx, next) {
async function refreshPresence(ctx, before) {
const { settings } = ctx
if (before.visible && !settings.visible) {
const goodbye = announcement({ ...ctx, settings: before }, 0)
if (goodbye) await ctx.discovery?.sendRaw(goodbye)
await ctx.discovery?.sendEach((addr) => announcement({ ...ctx, settings: before }, 0, addr))
} else if (settings.visible !== before.visible || settings.name !== before.name) {
ctx.discovery?.announce()
}
Expand All @@ -120,11 +121,12 @@ async function apply(ctx, next) {
ctx.onChange()
}

export function createLan({ settings, selfFp, onChange, now = Date.now }) {
export function createLan({ settings, selfFp, onChange, log, now = Date.now }) {
const ctx = {
settings,
selfFp,
onChange,
log,
now,
handlers: new Map(),
acceptors: new Map(),
Expand Down
2 changes: 2 additions & 0 deletions src/main/lan/lanIpc.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { registerRevokeIpc, setUpRevoke } from './revokeIpc'
import { getIdentity } from '../share'
import { cancelPairing, registerPairingIpc, setUpPairing } from './pairingIpc'
import { readTrusted } from '../trustedKeys'
import { appendLog } from '../logger'

const settingsFile = () => join(app.getPath('userData'), 'lan.json')
const run = async (cmd, args) => (await promisify(execFile)(cmd, args)).stdout
Expand Down Expand Up @@ -58,6 +59,7 @@ export async function startLanSharing() {
lan = createLan({
settings,
selfFp: identity.pub.fingerprint,
log: (message) => appendLog({ source: 'lan', level: 'info', message }),
// One spoofed packet can carry many records; each would otherwise re-read the trust store.
onChange: coalesce(() => broadcastLan().catch(() => {}), 100)
})
Expand Down
37 changes: 32 additions & 5 deletions src/main/lan/pairing.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ const view = (s) => ({
...(s.role === 'holder' && s.stage === 'show-code' ? { code: s.code } : {})
})

const short = (fp) => fp.slice(0, 8)
const note = (ctx, message) => ctx.log?.(message)
const errorText = (err) =>
[err?.code ?? err?.message, err?.address && `${err.address}:${err.port}`]
.filter(Boolean)
.join(' ')

function finish(ctx, s, stage, { silent = false } = {}) {
if (s.done) return
s.done = true
Expand Down Expand Up @@ -60,8 +67,13 @@ function onAdderFrame(ctx, s, { header }) {
if (header.type === 'add-result' && RESULT_STAGE[header.result])
return finish(ctx, s, header.result === 'expired' ? 'expired' : 'cancelled')
const parsed = header.type === 'add-reply' && parsedOrNull(ctx, header.key)
if (s.stage !== 'connecting' || !parsed || parsed.fp !== s.peerFp)
if (s.stage !== 'connecting' || !parsed || parsed.fp !== s.peerFp) {
note(
ctx,
`add ${short(s.peerFp)}: unexpected ${header.type} at ${s.stage}${parsed ? ` from ${short(parsed.fp)}` : ''}`
)
return finish(ctx, s, 'connection-lost')
}
Object.assign(s, { holderKey: parsed.key, stage: 'enter-code' })
s.expected = pairingCode({
holderFp: s.peerFp,
Expand All @@ -79,9 +91,13 @@ async function add(ctx, peerFp, name) {
try {
s.conn = await ctx.connect(peerFp, {
onFrame: (frame) => onAdderFrame(ctx, s, frame),
onClose: () => finish(ctx, s, 'connection-lost')
onClose: () => {
if (s.stage === 'connecting') note(ctx, `add ${short(peerFp)}: closed before the code step`)
finish(ctx, s, 'connection-lost')
}
})
} catch {
} catch (err) {
note(ctx, `add ${short(peerFp)}: could not connect (${errorText(err)})`)
finish(ctx, s, 'connection-lost', { silent: true })
return { error: 'not-reachable' }
}
Expand Down Expand Up @@ -113,11 +129,22 @@ function cancel(ctx, id) {
return { ok: true }
}

function refusalOf(ctx, header, conn) {
if (!ctx.isVisible()) return 'not visible'
if (isBusy(ctx, 'holder')) return 'busy with another request'
if (!ctx.allowRequest(conn.remote)) return 'rate-limited'
const parsed = parsedOrNull(ctx, header.key)
if (!parsed) return 'unreadable key'
return parsed.fp === ctx.identity.fp ? 'own key' : null
}

function onRequest(ctx, { header }, conn) {
if (!ctx.isVisible() || isBusy(ctx, 'holder') || !ctx.allowRequest(conn.remote))
const refusal = refusalOf(ctx, header, conn)
if (refusal) {
note(ctx, `request from ${conn.remote} refused: ${refusal}`)
return conn.destroy()
}
const parsed = parsedOrNull(ctx, header.key)
if (!parsed || parsed.fp === ctx.identity.fp) return conn.destroy()
const s = open(ctx, {
role: 'holder',
conn,
Expand Down
2 changes: 2 additions & 0 deletions src/main/lan/pairingIpc.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { connectTo } from './server'
import { parseKeyText } from '../keyText'
import { encodePublicKey } from '../sealing'
import { checkedTrustedName, storeTrusted } from '../trustedKeys'
import { appendLog } from '../logger'

const FP = /^[0-9a-f]{32}$/
let pairing = null
Expand All @@ -24,6 +25,7 @@ export function setUpPairing({ lan, identity, onTrustChanged }) {
const limit = createRateLimit({ limit: 3, windowMs: 60_000 })
const settings = () => lan.settings()
pairing = createPairing({
log: (message) => appendLog({ source: 'lan', level: 'info', message }),
identity: {
fp: identity.pub.fingerprint,
keyText: encodePublicKey(identity.pub),
Expand Down
2 changes: 2 additions & 0 deletions src/main/lan/privateAddress.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,5 @@ export function privateInterfaceAddresses(table) {
}
return out
}

export const reachableAt = (named, source) => (named && isPrivateAddress(named) ? named : source)
19 changes: 19 additions & 0 deletions tests/main/lan/dnsSd.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,22 @@ describe('hostile packets', () => {
expect(peer.name).toBe('ecilA')
})
})

describe('the address an announcement names', () => {
it("carries the sender's own address, which a relaying router would otherwise replace", () => {
const packet = encodeAnnouncement({ fp: FP, name: 'Ben', port: 4000, addr: '192.168.2.14' })
expect(announcementsFrom(decodePacket(packet))[0]).toMatchObject({
addr: '192.168.2.14',
port: 4000
})
})

it('names no address when it was not given or is not an IPv4 address', () => {
expect(
announcementsFrom(decodePacket(encodeAnnouncement({ fp: FP, name: 'Ben', port: 4000 })))[0]
.addr
).toBeUndefined()
const odd = encodeAnnouncement({ fp: FP, name: 'Ben', port: 4000, addr: 'evil.example' })
expect(announcementsFrom(decodePacket(odd))[0].addr).toBeUndefined()
})
})
2 changes: 1 addition & 1 deletion tests/main/lan/lan.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ beforeEach(() => {
sockets.discovery = {
announce: vi.fn(),
query: vi.fn(),
sendRaw: vi.fn(async () => {}),
sendEach: vi.fn(async () => {}),
close: vi.fn(async () => {})
}
})
Expand Down
41 changes: 40 additions & 1 deletion tests/main/lan/pairing.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ function peer(fp, name, extra = {}) {
const events = []
const stored = []
const timers = fakeTimers()
const logged = []
const pairing = createPairing({
log: (message) => logged.push(message),
identity: { fp, keyText: `key-${fp}`, name: () => name },
parseKey: (text) => {
if (!text.startsWith('key-')) throw new Error('bad key')
Expand All @@ -63,7 +65,7 @@ function peer(fp, name, extra = {}) {
now: () => 1000,
...extra
})
return { fp, name, pairing, events, stored, timers, last: () => events.at(-1) }
return { fp, name, pairing, events, stored, timers, logged, last: () => events.at(-1) }
}

const A = 'aa'.repeat(16)
Expand Down Expand Up @@ -284,3 +286,40 @@ describe('a hostile network', () => {
expect(ana.last().name).toBe('Ben')
})
})

describe('when adding fails, the log says why', () => {
it('names the connection error and the address it dialled', async () => {
const refused = Object.assign(new Error('connect ECONNREFUSED'), {
code: 'ECONNREFUSED',
address: '192.168.1.1',
port: 51000
})
const ben = peer(B, 'Ben', { connect: async () => Promise.reject(refused) })
await ben.pairing.add(A, 'Ana')
expect(ben.logged.join('\n')).toMatch(/ECONNREFUSED 192\.168\.1\.1:51000/)
})

it('names why a holder turned a request away', () => {
const ana = peer(A, 'Ana', { allowRequest: () => false })
const [conn] = linkedConns('192.168.1.66')
ana.pairing.onRequest(
{ header: { type: 'add-request', key: `key-${B}`, name: 'Ben', commit: 'c' } },
conn
)
expect(ana.logged.join('\n')).toMatch(/192\.168\.1\.66.*rate-limited/)
})

it('names a connection that closed before the code step', async () => {
const ben = peer(B, 'Ben', {
connect: async (_fp, handlers) => {
const [mine] = linkedConns()
mine.handlers = handlers
setTimeout(() => handlers.onClose(mine), 0)
return mine
}
})
await ben.pairing.add(A, 'Ana')
await flush()
expect(ben.logged.join('\n')).toMatch(/closed before/)
})
})
17 changes: 16 additions & 1 deletion tests/main/lan/privateAddress.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
import { isPrivateAddress, privateInterfaceAddresses } from '../../../src/main/lan/privateAddress'
import {
isPrivateAddress,
privateInterfaceAddresses,
reachableAt
} from '../../../src/main/lan/privateAddress'

describe('isPrivateAddress', () => {
it.each([
Expand Down Expand Up @@ -53,3 +57,14 @@ describe('privateInterfaceAddresses', () => {
expect(privateInterfaceAddresses(undefined)).toEqual([])
})
})

describe('reachableAt', () => {
it('prefers the private address an announcement names over the packet source', () => {
expect(reachableAt('192.168.2.14', '192.168.1.1')).toBe('192.168.2.14')
})

it('falls back to the source when the named address is missing or not private', () => {
expect(reachableAt(undefined, '192.168.1.20')).toBe('192.168.1.20')
expect(reachableAt('8.8.8.8', '192.168.1.20')).toBe('192.168.1.20')
})
})
Loading