Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

fix: support IPv6 downloads on selected networks

Anmol Kapil6888ffad8205
diff --git a/README.md b/README.md
index 107c981..1a29a57 100644
--- a/README.md
+++ b/README.md
@@ -106,29 +106,28 @@ Before starting a multi-connection download, Plexo sends a **1-byte ranged GET**
- The probe response provides the total file size (`Content-Range` / `Content-Length`), suggested filename (`Content-Disposition`), and cache validators (`ETag` and `Last-Modified`).
- If the server answers with `200 OK` (ignoring the `Range` header), Plexo falls back to a standard single-connection stream instead of failing.
-### 2. Multi-interface socket binding via `localAddress`
+### 2. Multi-interface socket binding
-Every active network interface on your computer has its own local IP address — Wi-Fi might be `192.168.1.40`, while a USB-tethered phone is `172.20.10.3`.
+Every active network interface on your computer has local IP addresses — Wi-Fi might have both IPv4 and IPv6, while a USB-tethered phone has its own addresses.
-A standard TCP socket leaves interface selection to the operating system's routing table. However, Node.js allows outbound HTTP/HTTPS requests to explicitly bind to a specific local IP using the `localAddress` option:
+A standard TCP socket leaves interface selection to the operating system's routing table. Plexo resolves the server, chooses an address of the same IP family on each selected interface, then binds that address for its HTTP/HTTPS connections. On Linux it also pins the socket to the device.
```js
https.request({
hostname: 'releases.ubuntu.com',
path: '/ubuntu-26.04.1-desktop-amd64.iso',
- localAddress: '172.20.10.3', // Forces this connection through the USB tether
+ localAddress: '172.20.10.3', // Source address on the USB tether
headers: {
Range: 'bytes=8388608-16777215'
}
})
```
-This single option is Plexo's entire multi-network routing engine:
+The interface binding keeps each worker on its selected network:
- **No virtual network adapters or VPN tunnels**
- **No packet bonding or link aggregation**
- **No kernel extensions (`kext`) or root privileges**
-- **Zero native C/C++ dependencies**
### 3. Dynamic work-stealing queue
diff --git a/e2e/download.spec.ts b/e2e/download.spec.ts
index 03b16c5..6138840 100644
--- a/e2e/download.spec.ts
+++ b/e2e/download.spec.ts
@@ -4,6 +4,24 @@ import { BLOCK, expect, LAN_ADDRESS, test } from './fixtures'
// fixtures.ts: completed ⇒ the file's SHA-256 matches the source, nothing stray left behind.
test.describe('happy paths @smoke', () => {
+ test('IPv6-only origin downloads through an IPv6 interface', async ({ plexo, serve }) => {
+ const origin = await serve({ size: 4 * BLOCK, host: '::1' })
+ await plexo.relaunch({ PLEXO_E2E_INTERFACES: 'a=::1' })
+ await plexo.start(origin.url(), origin.sha256)
+ const state = await plexo.waitForStatus('completed')
+ expect(state.chunks.every((chunk) => chunk.retryCount === 0)).toBe(true)
+ expect(origin.chunkRequests().every((request) => request.from === '::1')).toBe(true)
+ })
+
+ test('IPv6 origin reports an incompatible IPv4-only selection immediately', async ({
+ plexo,
+ serve
+ }) => {
+ const origin = await serve({ size: BLOCK, host: '::1' })
+ await expect(plexo.start(origin.url(), origin.sha256)).rejects.toThrow(/No selected network/)
+ expect(await plexo.current()).toBeNull()
+ })
+
for (const [label, size] of [
['1 byte', 1],
['exactly one block', BLOCK],
diff --git a/e2e/network.spec.ts b/e2e/network.spec.ts
new file mode 100644
index 0000000..245fbdc
--- /dev/null
+++ b/e2e/network.spec.ts
@@ -0,0 +1,97 @@
+import { expect, test } from '@playwright/test'
+import { createServer } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import type { NetworkInterfaceInfo } from '../src/shared/types'
+import { requestOnInterface, resolveTarget, routesFor } from '../src/main/network/routes'
+
+const iface: NetworkInterfaceInfo = {
+ id: 'wifi',
+ device: 'wifi',
+ displayName: 'Wi-Fi',
+ kind: 'wifi',
+ addresses: [
+ { address: '192.0.2.2', family: 4 },
+ { address: '2001:db8::2', family: 6 }
+ ]
+}
+
+test('AAAA-only host uses the matching IPv6 address', async () => {
+ const remote = await resolveTarget(new URL('https://ipv6.example.test/file'), async (host) => {
+ expect(host).toBe('ipv6.example.test')
+ return [{ address: '2001:db8::10', family: 6 }]
+ })
+ expect(routesFor(iface, remote)).toEqual([
+ { device: 'wifi', localAddress: '2001:db8::2', remoteAddress: '2001:db8::10', family: 6 }
+ ])
+})
+
+test('IPv4 and bracketed IPv6 literals bypass DNS', async () => {
+ const failLookup = async (): Promise<never> => {
+ throw new Error('DNS should not run for a literal')
+ }
+ expect(await resolveTarget(new URL('http://127.0.0.1/'), failLookup)).toEqual([
+ { address: '127.0.0.1', family: 4 }
+ ])
+ expect(await resolveTarget(new URL('http://[::1]/'), failLookup)).toEqual([
+ { address: '::1', family: 6 }
+ ])
+})
+
+test('AAAA-only hostname connects over IPv6 and keeps its HTTP Host header', async () => {
+ let seenHost = ''
+ const server = createServer((req, res) => {
+ seenHost = req.headers.host ?? ''
+ res.end('ok')
+ })
+ await new Promise<void>((resolve) => server.listen(0, '::1', resolve))
+ try {
+ const port = (server.address() as AddressInfo).port
+ const target = new URL(`http://ipv6.example.test:${port}/file`)
+ const source: NetworkInterfaceInfo = {
+ ...iface,
+ addresses: [{ address: '::1', family: 6 }]
+ }
+ const { res } = await requestOnInterface({
+ target,
+ iface: source,
+ headers: {},
+ timeoutMs: 2000,
+ resolveHost: async () => [{ address: '::1', family: 6 }]
+ })
+ let body = ''
+ for await (const chunk of res) body += chunk
+ expect(body).toBe('ok')
+ expect(seenHost).toBe(`ipv6.example.test:${port}`)
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+})
+
+test('falls back to IPv6 when an IPv4 connection fails before headers', async () => {
+ const server = createServer((_req, res) => res.end('ipv6'))
+ await new Promise<void>((resolve) => server.listen(0, '::1', resolve))
+ try {
+ const port = (server.address() as AddressInfo).port
+ const { res } = await requestOnInterface({
+ target: new URL(`http://dual.example.test:${port}/`),
+ iface: {
+ ...iface,
+ addresses: [
+ { address: '127.0.0.1', family: 4 },
+ { address: '::1', family: 6 }
+ ]
+ },
+ headers: {},
+ timeoutMs: 2000,
+ resolveHost: async () => [
+ { address: '127.0.0.1', family: 4 },
+ { address: '::1', family: 6 }
+ ]
+ })
+ let body = ''
+ for await (const chunk of res) body += chunk
+ expect(body).toBe('ipv6')
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ }
+})
diff --git a/e2e/origin.ts b/e2e/origin.ts
index 74ae47f..b9934cb 100644
--- a/e2e/origin.ts
+++ b/e2e/origin.ts
@@ -50,6 +50,8 @@ export interface LoggedRequest extends OriginRequest {
export interface OriginOptions {
size: number
+ /** Bind only to IPv6 loopback for dual-stack routing regressions. */
+ host?: '0.0.0.0' | '::1'
seed?: number
/** false: ignore Range headers and never advertise Accept-Ranges. */
ranges?: boolean
@@ -118,7 +120,9 @@ export class Origin {
async start(): Promise<this> {
// 0.0.0.0 so requests bound to a LAN address (the second test "network") still arrive.
- await new Promise<void>((resolve) => this.server.listen(0, '0.0.0.0', resolve))
+ await new Promise<void>((resolve) =>
+ this.server.listen(0, this.options.host ?? '0.0.0.0', resolve)
+ )
this.port = (this.server.address() as AddressInfo).port
return this
}
@@ -130,7 +134,7 @@ export class Origin {
}
url(path = '/files/test.bin'): string {
- return `http://127.0.0.1:${this.port}${path}`
+ return `http://${this.options.host === '::1' ? '[::1]' : '127.0.0.1'}:${this.port}${path}`
}
get sha256(): string {
diff --git a/e2e/recovery.spec.ts b/e2e/recovery.spec.ts
index c5ff8ae..d7b52b8 100644
--- a/e2e/recovery.spec.ts
+++ b/e2e/recovery.spec.ts
@@ -11,6 +11,22 @@ import { seededBytes, sha256 } from './origin'
const SIZE = 32 * BLOCK
test.describe('restart @smoke', () => {
+ test('IPv6 download survives quit and relaunch', async ({ plexo, serve }) => {
+ await plexo.relaunch({ PLEXO_E2E_INTERFACES: 'a=::1' })
+ const origin = await serve({ size: SIZE, host: '::1' })
+ const reached = origin.hold(8 * BLOCK)
+ const id = await plexo.start(origin.url(), origin.sha256)
+ await reached
+
+ await plexo.quit()
+ origin.release()
+ await plexo.launch()
+ expect((await plexo.current())?.status).toBe('paused')
+
+ await plexo.api.resumeDownload(id)
+ await plexo.waitForStatus('completed')
+ })
+
test('normal quit mid-download → relaunch paused → resume', async ({ plexo, serve }) => {
const origin = await serve({ size: SIZE })
const reached = origin.hold(10 * BLOCK + 500)
diff --git a/src/main/download/chunkDownloader.ts b/src/main/download/chunkDownloader.ts
index fb5002a..07cc7ee 100644
--- a/src/main/download/chunkDownloader.ts
+++ b/src/main/download/chunkDownloader.ts
@@ -1,8 +1,8 @@
import { createWriteStream, type WriteStream } from 'node:fs'
-import { request as httpRequest, type ClientRequest, type IncomingMessage } from 'node:http'
-import { request as httpsRequest } from 'node:https'
+import type { ClientRequest, IncomingMessage } from 'node:http'
import { URL } from 'node:url'
-import { routeFrom } from '../network/deviceBinding'
+import type { NetworkInterfaceInfo } from '../../shared/types'
+import { requestOnInterface } from '../network/routes'
import { testKnobs } from '../testKnobs'
import { compareVersion, type FileVersion, type VersionCheck } from './fileVersion'
@@ -11,8 +11,7 @@ export interface ChunkDownloadOptions {
rangeStart: number
/** null = open-ended range, download to end of file. */
rangeEnd: number | null
- /** Local IP of the network interface this chunk's connection binds to. */
- localAddress: string
+ interfaceInfo: NetworkInterfaceInfo
destinationPath: string
/** true when resuming a paused chunk — appends to the existing part file instead of overwriting it. */
append: boolean
@@ -97,7 +96,7 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {
url,
rangeStart,
rangeEnd,
- localAddress,
+ interfaceInfo,
destinationPath,
append,
onProgress,
@@ -174,19 +173,20 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {
}
const attempt = (targetUrl: URL, redirectsLeft: number): void => {
- const requester = targetUrl.protocol === 'https:' ? httpsRequest : httpRequest
- const sentAt = Date.now()
-
- const req: ClientRequest = requester(
- {
- method: 'GET',
- hostname: targetUrl.hostname,
- port: targetUrl.port || undefined,
- path: `${targetUrl.pathname}${targetUrl.search}`,
- ...routeFrom(localAddress, targetUrl),
- headers
- },
- (res: IncomingMessage) => {
+ void requestOnInterface({
+ target: targetUrl,
+ iface: interfaceInfo,
+ headers,
+ signal,
+ timeoutMs: STALL_TIMEOUT_MS
+ })
+ .then(({ req, res, sentAt }) => {
+ if (settled) {
+ req.destroy()
+ return
+ }
+ currentReq = req
+ req.on('error', fail)
const status = res.statusCode ?? 0
if (status >= 300 && status < 400) {
@@ -308,15 +308,8 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {
fileStream.once('close', () => finish(resolve))
fileStream.end()
})
- }
- )
-
- currentReq = req
- req.on('error', fail)
- req.setTimeout(STALL_TIMEOUT_MS, () =>
- fail(new Error('Connection stalled: no response from server'))
- )
- req.end()
+ })
+ .catch(fail)
}
attempt(new URL(url), MAX_REDIRECTS)
@@ -329,21 +322,18 @@ export function fetchRange(
url: string,
start: number,
end: number,
- localAddress: string
+ interfaceInfo: NetworkInterfaceInfo
): Promise<{ body: Buffer; version: FileVersion }> {
return new Promise((resolve, reject) => {
const attempt = (target: URL, redirectsLeft: number): void => {
- const requester = target.protocol === 'https:' ? httpsRequest : httpRequest
- const req = requester(
- {
- method: 'GET',
- hostname: target.hostname,
- port: target.port || undefined,
- path: `${target.pathname}${target.search}`,
- ...routeFrom(localAddress, target),
- headers: { 'User-Agent': 'Plexo/1.0', Range: `bytes=${start}-${end}` }
- },
- (res) => {
+ void requestOnInterface({
+ target,
+ iface: interfaceInfo,
+ headers: { 'User-Agent': 'Plexo/1.0', Range: `bytes=${start}-${end}` },
+ timeoutMs: STALL_TIMEOUT_MS
+ })
+ .then(({ req, res }) => {
+ req.on('error', reject)
const status = res.statusCode ?? 0
if (status >= 300 && status < 400 && res.headers.location && redirectsLeft > 0) {
res.resume()
@@ -357,16 +347,14 @@ export function fetchRange(
return
}
const chunks: Buffer[] = []
+ res.setTimeout(STALL_TIMEOUT_MS, () => req.destroy(new Error('Sample request stalled')))
res.on('data', (chunk: Buffer) => chunks.push(chunk))
res.on('error', reject)
res.on('end', () =>
resolve({ body: Buffer.concat(chunks), version: versionOf(res, served) })
)
- }
- )
- req.on('error', reject)
- req.setTimeout(STALL_TIMEOUT_MS, () => req.destroy(new Error('Sample request stalled')))
- req.end()
+ })
+ .catch(reject)
}
attempt(new URL(url), MAX_REDIRECTS)
})
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.ts
index dc1214c..ff3a131 100644
--- a/src/main/download/downloadManager.ts
+++ b/src/main/download/downloadManager.ts
@@ -31,6 +31,12 @@ import {
} from './partFiles'
import { ensureDirectory, reserveDestinationPath } from './paths'
import { pickWork, type SchedulerPolicy, type Work } from './scheduler'
+import {
+ compatibleInterfaces,
+ NoCompatibleRouteError,
+ resolveTarget,
+ targetHost
+} from '../network/routes'
import {
createSimSession,
downloadChunkSimulated,
@@ -136,7 +142,7 @@ interface DownloadRuntime {
}
interface PersistedDownload {
- version: 1
+ version: 2
savedAt: number
state: DownloadState
requestPayload: StartDownloadRequest
@@ -346,7 +352,7 @@ export class DownloadManager {
const persisted = JSON.parse(
await readFile(this.manifestPath(id), 'utf-8')
) as PersistedDownload
- if (persisted.version !== 1 || persisted.state.id !== id || !persisted.state.blocks)
+ if (persisted.version !== 2 || persisted.state.id !== id || !persisted.state.blocks)
return
const state = persisted.state
@@ -448,13 +454,16 @@ export class DownloadManager {
throw new Error('A download is already in progress — finish or remove it first.')
}
- const interfaces = requestPayload.interfaceIds
+ const selected = requestPayload.interfaceIds
.map((interfaceId) => this.getInterfaceById(interfaceId))
.filter((iface): iface is NetworkInterfaceInfo => Boolean(iface))
- if (interfaces.length === 0) {
+ if (selected.length === 0) {
throw new Error('Select at least one network interface')
}
+ const target = new URL(requestPayload.url)
+ const interfaces = compatibleInterfaces(selected, await resolveTarget(target))
+ if (interfaces.length === 0) throw new NoCompatibleRouteError(targetHost(target))
return this.startWithInterfaces(requestPayload, interfaces)
}
@@ -695,9 +704,23 @@ export class DownloadManager {
const selectedIds = new Set(runtime.requestPayload.interfaceIds)
runtime.activeInterfaces = availableInterfaces.filter((iface) => selectedIds.has(iface.id))
+ const selectedAvailable = runtime.activeInterfaces.length > 0
+ if (!isSimulatedUrl(url)) {
+ try {
+ runtime.activeInterfaces = compatibleInterfaces(
+ runtime.activeInterfaces,
+ await resolveTarget(new URL(url))
+ )
+ } catch {
+ runtime.state.error = 'Could not resolve the download host. Try resuming again.'
+ this.pushUpdate(runtime)
+ return
+ }
+ }
if (runtime.activeInterfaces.length === 0) {
- runtime.state.error =
- 'None of the networks selected for this download are currently available. Reconnect one and try again.'
+ runtime.state.error = selectedAvailable
+ ? `No selected network has an address compatible with ${targetHost(new URL(url))}.`
+ : 'None of the networks selected for this download are currently available. Reconnect one and try again.'
this.pushUpdate(runtime)
return
}
@@ -849,6 +872,16 @@ export class DownloadManager {
clearInterval(speedTicker)
}
+ if (
+ runtime.state.status === 'downloading' &&
+ runtime.blocks.some((b) => b.status !== 'completed')
+ ) {
+ runtime.state.status = 'error'
+ runtime.state.error =
+ runtime.state.chunks.find((chunk) => chunk.error)?.error ??
+ 'No network could finish the remaining blocks'
+ }
+
if (runtime.state.status !== 'downloading') {
// Paused, errored, or cancelled — nothing left to do right now.
if (runtime.state.status === 'error' || runtime.state.status === 'cancelled') {
@@ -1116,7 +1149,7 @@ export class DownloadManager {
url: runtime.requestPayload.url,
rangeStart: block.rangeStart + attempt.startOffset,
rangeEnd: block.rangeEnd,
- localAddress: iface.address,
+ interfaceInfo: iface,
destinationPath: attempt.file,
append: attempt.kind === 'primary' && attempt.startOffset > 0,
signal: AbortSignal.any([self.controller.signal, attempt.abort.signal]),
@@ -1362,6 +1395,19 @@ export class DownloadManager {
// failed request. Nothing wrong was written either way.
}
+ if (error instanceof NoCompatibleRouteError) {
+ // A redirect can move this worker to a host its network cannot reach. Return its block
+ // to the shared queue so another compatible worker can finish it.
+ await this.letGo(runtime, chunk, self, attempt, deliveredNothing)
+ chunk.status = 'error'
+ if (runtime.state.chunks.every((entry) => entry.status === 'error')) {
+ runtime.state.status = 'error'
+ runtime.state.error = message
+ }
+ this.scheduleUpdate(runtime)
+ return 'stop'
+ }
+
// A hedge is optional work: when it fails, the block is exactly where it was.
if (attempt.kind === 'hedge') {
await this.letGo(runtime, chunk, self, attempt, deliveredNothing)
@@ -1555,7 +1601,7 @@ export class DownloadManager {
runtime.requestPayload.url,
block.rangeStart,
block.rangeStart + local.length - 1,
- iface.address
+ iface
)
// A reply from a server still presenting an accepted label proves nothing here.
if (compareVersion([seen], remote.version).kind !== 'same') continue
@@ -1749,7 +1795,7 @@ export class DownloadManager {
const path = this.manifestPath(runtime.state.id)
const temporaryPath = `${path}.tmp`
const persisted: PersistedDownload = {
- version: 1,
+ version: 2,
savedAt: Date.now(),
state: structuredClone(runtime.state),
requestPayload: runtime.requestPayload,
diff --git a/src/main/download/probe.ts b/src/main/download/probe.ts
index f815f7e..7d9f8cf 100644
--- a/src/main/download/probe.ts
+++ b/src/main/download/probe.ts
@@ -30,7 +30,7 @@ function requestOneByte(url: URL): Promise<ProbeResponse> {
const req = requester(
{
method: 'GET',
- hostname: url.hostname,
+ hostname: url.hostname.replace(/^\[|\]$/g, ''),
port: url.port || undefined,
path: `${url.pathname}${url.search}`,
headers: { 'User-Agent': USER_AGENT, Range: 'bytes=0-0' }
diff --git a/src/main/download/simDownload.ts b/src/main/download/simDownload.ts
index 60ef6b1..7fdc226 100644
--- a/src/main/download/simDownload.ts
+++ b/src/main/download/simDownload.ts
@@ -66,7 +66,7 @@ export async function createSimSession(
id,
device: id,
displayName: config.label,
- address: id,
+ addresses: [],
kind: config.kind
}
})
@@ -84,7 +84,7 @@ const DEFAULT_SPEED_BYTES_PER_SEC = 3 * 1024 * 1024
* simulated network's configured speed so the UI has something real to show — a chunk grid or
* speed readout that jumped from 0 to 100% instantly would defeat the point of simulating it. */
export function downloadChunkSimulated(options: ChunkDownloadOptions): Promise<void> {
- const { url, rangeStart, rangeEnd, localAddress, destinationPath, append, onProgress, signal } =
+ const { url, rangeStart, rangeEnd, interfaceInfo, destinationPath, append, onProgress, signal } =
options
return new Promise((resolve, reject) => {
@@ -99,7 +99,7 @@ export function downloadChunkSimulated(options: ChunkDownloadOptions): Promise<v
return
}
- const network = session.networks.get(localAddress)
+ const network = session.networks.get(interfaceInfo.id)
if (network && Math.random() * 100 < network.faultRatePercent) {
reject(new Error(`Simulated drop on ${network.label}`))
return
diff --git a/src/main/network/deviceBinding.ts b/src/main/network/deviceBinding.ts
index e5d6b86..a1d671d 100644
--- a/src/main/network/deviceBinding.ts
+++ b/src/main/network/deviceBinding.ts
@@ -1,7 +1,7 @@
import type { ClientRequestArgs } from 'node:http'
import { connect, isIP, Socket, type SocketConstructorOpts } from 'node:net'
-import { networkInterfaces } from 'node:os'
-import { connect as tlsConnect } from 'node:tls'
+import { checkServerIdentity, connect as tlsConnect } from 'node:tls'
+import type { NetworkRoute } from './routes'
// Linux picks a socket's outgoing interface from the routing table alone: binding to an
// interface's IP (Node's `localAddress`) still sends the packets out the default route, where the
@@ -10,6 +10,7 @@ import { connect as tlsConnect } from 'node:tls'
// Unprivileged since Linux 5.7. macOS and Windows already route by source address.
const AF_INET = 2
+const AF_INET6 = 10
const SOCK_STREAM = 1
const SOCK_CLOEXEC = 0o2000000
const SOL_SOCKET = 1
@@ -26,8 +27,8 @@ interface Libc {
let libc: Libc | null = null
let support: Promise<boolean> | null = null
-function openOnDevice(lib: Libc, device: string): number {
- const fd = lib.socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0)
+function openOnDevice(lib: Libc, device: string, family: 4 | 6): number {
+ const fd = lib.socket(family === 6 ? AF_INET6 : AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0)
if (fd < 0) throw new Error(`socket() failed (errno ${lib.errno()})`)
if (
lib.setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, device, Buffer.byteLength(device) + 1) !== 0
@@ -53,7 +54,7 @@ export function deviceBindingSupported(): Promise<boolean> {
errno: () => koffi.errno()
}
// Loopback always exists, so this only fails when the kernel refuses (EPERM before 5.7).
- candidate.close(openOnDevice(candidate, 'lo'))
+ candidate.close(openOnDevice(candidate, 'lo', 4))
libc = candidate
return true
} catch (error) {
@@ -64,24 +65,17 @@ export function deviceBindingSupported(): Promise<boolean> {
return support
}
-/** The interface to pin a connection to `host` to, if any. Loopback traffic never touches a
- * network, and a socket pinned to one can't reach it. */
-function deviceFor(localAddress: string, host: string): string | undefined {
- if (host === 'localhost' || host.startsWith('127.')) return undefined
- for (const [device, addresses] of Object.entries(networkInterfaces())) {
- if (addresses?.some((addr) => addr.address === localAddress)) return device
+/** A TCP connection through the already chosen device, to a numeric remote address. */
+export function connectRoute(route: NetworkRoute, port: number): Socket {
+ const { device, localAddress, remoteAddress, family } = route
+ const loopback = remoteAddress === '::1' || remoteAddress.startsWith('127.')
+ if (!libc || loopback) {
+ return connect({ host: remoteAddress, port, localAddress, family })
}
- return undefined
-}
-
-/** A TCP connection to host:port that leaves through the interface owning `localAddress`. */
-export function connectFrom(localAddress: string, host: string, port: number): Socket {
- const device = libc && deviceFor(localAddress, host)
- if (!libc || !device) return connect({ host, port, localAddress, family: 4 })
let fd: number
try {
- fd = openOnDevice(libc, device)
+ fd = openOnDevice(libc, device, family)
} catch (error) {
// The interface vanished since it was listed — surface it like any other connect error.
const socket = new Socket()
@@ -89,38 +83,41 @@ export function connectFrom(localAddress: string, host: string, port: number): S
return socket
}
// manualStart: a socket wrapped around an fd starts reading at once, before it's connected.
- // No localAddress: the device already picks the source IP, and a second bind would fail.
+ // Bind both the device and source address: an interface may have several IPv6 addresses.
return new Socket({ fd, manualStart: true } as SocketConstructorOpts).connect({
- host,
+ host: remoteAddress,
port,
- family: 4
+ localAddress,
+ family
})
}
-/** Options that route an http(s) request for `target` through the interface owning
- * `localAddress`. Spread them after `port`. */
+/** Convert an explicit route into request options without changing the URL's HTTP authority. */
export function routeFrom(
- localAddress: string,
+ route: NetworkRoute,
target: URL
): Pick<
ClientRequestArgs,
'localAddress' | 'family' | 'createConnection' | 'port' | 'defaultPort'
> {
- // localAddress is always an IPv4 interface address, so the remote host has to resolve to
- // IPv4 too, or binding fails with EINVAL when DNS hands back an IPv6 address instead.
- if (!libc || !deviceFor(localAddress, target.hostname)) return { localAddress, family: 4 }
-
const secure = target.protocol === 'https:'
const defaultPort = secure ? 443 : 80
const port = Number(target.port) || defaultPort
- const host = target.hostname
+ const host = target.hostname.replace(/^\[|\]$/g, '')
return {
- // Without an agent, Node can't infer the scheme's port and would write it into Host.
+ localAddress: route.localAddress,
+ family: route.family,
port,
defaultPort,
createConnection: () => {
- const socket = connectFrom(localAddress, host, port)
- return secure ? tlsConnect({ socket, servername: isIP(host) ? undefined : host }) : socket
+ const socket = connectRoute(route, port)
+ return secure
+ ? tlsConnect({
+ socket,
+ servername: isIP(host) ? undefined : host,
+ checkServerIdentity: (_name, cert) => checkServerIdentity(host, cert)
+ })
+ : socket
}
}
}
diff --git a/src/main/network/interfaces.ts b/src/main/network/interfaces.ts
index a85b63e..a540fa3 100644
--- a/src/main/network/interfaces.ts
+++ b/src/main/network/interfaces.ts
@@ -1,7 +1,7 @@
import { execFile } from 'node:child_process'
import { networkInterfaces } from 'node:os'
import { promisify } from 'node:util'
-import type { NetworkInterfaceInfo, NetworkInterfaceKind } from '../../shared/types'
+import type { NetworkAddress, NetworkInterfaceInfo, NetworkInterfaceKind } from '../../shared/types'
import { testInterfaces } from '../testKnobs'
const execFileAsync = promisify(execFile)
@@ -99,9 +99,7 @@ export function ipv4Subnet(address: string, netmask: string): string | null {
}
/**
- * Active non-loopback IPv4 interfaces. Each one has its
- * own local IP, which is what lets us bind a download's outgoing connection
- * to a specific interface (see deviceBinding's `routeFrom`).
+ * Active non-loopback interfaces, with every usable local address on each device.
*/
export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {
const overridden = testInterfaces()
@@ -114,10 +112,24 @@ export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {
for (const [device, addresses] of Object.entries(all)) {
if (!addresses) continue
- const ipv4 = addresses.find(
- (addr) => addr.family === 'IPv4' && !addr.internal && !addr.address.startsWith('169.254.')
- )
- if (!ipv4) continue
+ const usable: NetworkAddress[] = addresses
+ .filter(
+ (addr) =>
+ !addr.internal &&
+ (addr.family === 'IPv4' || addr.family === 'IPv6') &&
+ !addr.address.startsWith('169.254.') &&
+ !addr.address.toLowerCase().startsWith('fe80:')
+ )
+ .map((addr) => ({
+ address: addr.address,
+ family: addr.family === 'IPv6' ? 6 : 4,
+ netmask: addr.netmask,
+ subnet:
+ addr.family === 'IPv4' && addr.netmask
+ ? (ipv4Subnet(addr.address, addr.netmask) ?? undefined)
+ : undefined
+ }))
+ if (usable.length === 0) continue
const hardwareName = hardwarePorts.get(device)
const adapter = windowsAdapters.get(device)
@@ -125,16 +137,13 @@ export async function listActiveInterfaces(): Promise<NetworkInterfaceInfo[]> {
// NDIS media: 1 = wireless LAN, 9 = native 802.11, 14 = Ethernet (802.3).
if (adapter?.NdisPhysicalMedium === 1 || adapter?.NdisPhysicalMedium === 9) kind = 'wifi'
else if (kind === 'other' && adapter?.NdisPhysicalMedium === 14) kind = 'ethernet'
- const subnet = ipv4.netmask ? (ipv4Subnet(ipv4.address, ipv4.netmask) ?? undefined) : undefined
result.push({
id: device,
device,
displayName: hardwareName ?? adapter?.InterfaceDescription ?? device,
- address: ipv4.address,
+ addresses: usable,
kind,
- mac: ipv4.mac && ipv4.mac !== '00:00:00:00:00:00' ? ipv4.mac : undefined,
- subnet,
- netmask: ipv4.netmask
+ mac: addresses.find((addr) => addr.mac && addr.mac !== '00:00:00:00:00:00')?.mac
})
}
diff --git a/src/main/network/latency.ts b/src/main/network/latency.ts
index f52732b..ce266bc 100644
--- a/src/main/network/latency.ts
+++ b/src/main/network/latency.ts
@@ -1,5 +1,5 @@
import type { NetworkInterfaceInfo } from '../../shared/types'
-import { connectFrom } from './deviceBinding'
+import { connectRoute } from './deviceBinding'
const PROBE_HOSTS = ['1.1.1.1', '8.8.8.8']
const PROBE_PORT = 443
@@ -7,10 +7,15 @@ const TIMEOUT_MS = 2000
/** Rough per-interface latency: time to open a TCP connection to a reliable
* host, sourced from that interface's local address. null means unreachable. */
-function measureLatencyToHost(localAddress: string, host: string): Promise<number | null> {
+function measureLatencyToHost(iface: NetworkInterfaceInfo, host: string): Promise<number | null> {
return new Promise((resolve) => {
const start = Date.now()
- const socket = connectFrom(localAddress, host, PROBE_PORT)
+ const localAddress = iface.addresses.find((address) => address.family === 4)?.address
+ if (!localAddress) return resolve(null)
+ const socket = connectRoute(
+ { device: iface.device, localAddress, remoteAddress: host, family: 4 },
+ PROBE_PORT
+ )
let settled = false
const finish = (result: number | null): void => {
@@ -27,9 +32,9 @@ function measureLatencyToHost(localAddress: string, host: string): Promise<numbe
})
}
-async function measureLatency(localAddress: string): Promise<number | null> {
+async function measureLatency(iface: NetworkInterfaceInfo): Promise<number | null> {
for (const host of PROBE_HOSTS) {
- const latency = await measureLatencyToHost(localAddress, host)
+ const latency = await measureLatencyToHost(iface, host)
if (latency !== null) return latency
}
return null
@@ -39,7 +44,7 @@ export async function measureLatencies(
interfaces: NetworkInterfaceInfo[]
): Promise<Record<string, number | null>> {
const entries = await Promise.all(
- interfaces.map(async (iface) => [iface.id, await measureLatency(iface.address)] as const)
+ interfaces.map(async (iface) => [iface.id, await measureLatency(iface)] as const)
)
return Object.fromEntries(entries)
}
diff --git a/src/main/network/routes.ts b/src/main/network/routes.ts
new file mode 100644
index 0000000..960f243
--- /dev/null
+++ b/src/main/network/routes.ts
@@ -0,0 +1,131 @@
+import { lookup } from 'node:dns/promises'
+import { request as httpRequest, type ClientRequest, type IncomingMessage } from 'node:http'
+import { request as httpsRequest } from 'node:https'
+import { isIP } from 'node:net'
+import type { IpFamily, NetworkInterfaceInfo } from '../../shared/types'
+import { routeFrom } from './deviceBinding'
+
+export interface NetworkRoute {
+ device: string
+ localAddress: string
+ remoteAddress: string
+ family: IpFamily
+}
+
+export type RemoteAddress = { address: string; family: IpFamily }
+
+/** URL.hostname brackets IPv6 literals; sockets and isIP expect the unbracketed address. */
+export function targetHost(target: URL): string {
+ return target.hostname.replace(/^\[|\]$/g, '')
+}
+
+export async function resolveTarget(
+ target: URL,
+ resolveHost: (host: string) => Promise<RemoteAddress[]> = async (host) =>
+ (await lookup(host, { all: true, order: 'verbatim' })) as RemoteAddress[]
+): Promise<RemoteAddress[]> {
+ const host = targetHost(target)
+ const literalFamily = isIP(host)
+ if (literalFamily) return [{ address: host, family: literalFamily as IpFamily }]
+ return resolveHost(host)
+}
+
+/** Preserve DNS and OS address order; each route always has matching IP families. */
+export function routesFor(
+ iface: NetworkInterfaceInfo,
+ remoteAddresses: RemoteAddress[]
+): NetworkRoute[] {
+ return remoteAddresses.flatMap((remote) =>
+ iface.addresses
+ .filter((local) => local.family === remote.family)
+ .map((local) => ({
+ device: iface.device,
+ localAddress: local.address,
+ remoteAddress: remote.address,
+ family: remote.family
+ }))
+ )
+}
+
+export function compatibleInterfaces(
+ interfaces: NetworkInterfaceInfo[],
+ remoteAddresses: RemoteAddress[]
+): NetworkInterfaceInfo[] {
+ return interfaces.filter((iface) => routesFor(iface, remoteAddresses).length > 0)
+}
+
+export class NoCompatibleRouteError extends Error {
+ constructor(host: string) {
+ super(`No selected network has an address compatible with ${host}`)
+ }
+}
+
+/** Try another compatible route only if no response headers have arrived yet. */
+interface RequestOptions {
+ target: URL
+ iface: NetworkInterfaceInfo
+ headers: Record<string, string>
+ signal?: AbortSignal
+ timeoutMs: number
+ /** Test seam for an AAAA-only hostname without modifying system DNS. */
+ resolveHost?: (host: string) => Promise<RemoteAddress[]>
+}
+
+export async function requestOnInterface({
+ target,
+ iface,
+ headers,
+ signal,
+ timeoutMs,
+ resolveHost
+}: RequestOptions): Promise<{ req: ClientRequest; res: IncomingMessage; sentAt: number }> {
+ const routes = routesFor(iface, await resolveTarget(target, resolveHost))
+ if (routes.length === 0) throw new NoCompatibleRouteError(targetHost(target))
+ const deadline = Date.now() + timeoutMs
+ let lastError: Error = new Error('Connection failed')
+
+ for (const route of routes) {
+ if (signal?.aborted) throw new DOMException('Aborted', 'AbortError')
+ const remaining = deadline - Date.now()
+ if (remaining <= 0) break
+
+ try {
+ return await new Promise((resolve, reject) => {
+ const requester = target.protocol === 'https:' ? httpsRequest : httpRequest
+ const sentAt = Date.now()
+ const req = requester(
+ {
+ method: 'GET',
+ hostname: targetHost(target),
+ path: `${target.pathname}${target.search}`,
+ headers,
+ ...routeFrom(route, target)
+ },
+ (res) => {
+ clearTimeout(timer)
+ signal?.removeEventListener('abort', onAbort)
+ resolve({ req, res, sentAt })
+ }
+ )
+ const onAbort = (): void => {
+ req.destroy(new DOMException('Aborted', 'AbortError'))
+ }
+ const timer = setTimeout(
+ () => req.destroy(new Error('Connection stalled: no response from server')),
+ remaining
+ )
+ req.once('error', (error) => {
+ clearTimeout(timer)
+ signal?.removeEventListener('abort', onAbort)
+ reject(error)
+ })
+ signal?.addEventListener('abort', onAbort, { once: true })
+ req.end()
+ })
+ } catch (error) {
+ if (signal?.aborted) throw new DOMException('Aborted', 'AbortError')
+ lastError = error instanceof Error ? error : new Error(String(error))
+ }
+ }
+ throw lastError
+}
diff --git a/src/main/testKnobs.ts b/src/main/testKnobs.ts
index 97a5d37..8072ba1 100644
--- a/src/main/testKnobs.ts
+++ b/src/main/testKnobs.ts
@@ -1,4 +1,5 @@
import { app } from 'electron'
+import { isIP } from 'node:net'
import type { NetworkInterfaceInfo } from '../shared/types'
// Overrides for the end-to-end suite (e2e/), read from the environment. A packaged build ignores
@@ -46,9 +47,8 @@ export function testInterfaces(): NetworkInterfaceInfo[] | null {
id,
device: id,
displayName: id,
- address,
- kind: inferredKind,
- subnet: subnet || undefined
+ addresses: [{ address, family: isIP(address) === 6 ? 6 : 4, subnet: subnet || undefined }],
+ kind: inferredKind
}
})
}
diff --git a/src/renderer/src/components/NetworkCard.tsx b/src/renderer/src/components/NetworkCard.tsx
index 3227018..3cb9937 100644
--- a/src/renderer/src/components/NetworkCard.tsx
+++ b/src/renderer/src/components/NetworkCard.tsx
@@ -87,7 +87,7 @@ export function NetworkCard({
</ColorBadge>
</div>
<div className="truncate font-mono text-[10.5px] leading-normal text-muted-foreground">
- {iface.device} · {iface.address}
+ {iface.device} · {iface.addresses[0]?.address}
</div>
<div className="flex items-end justify-between">
<div className="flex flex-col gap-[5px]">
diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsx
index 32e4a2d..766419e 100644
--- a/src/renderer/src/screens/IdleScreen.tsx
+++ b/src/renderer/src/screens/IdleScreen.tsx
@@ -144,10 +144,11 @@ export function IdleScreen(): React.JSX.Element {
const subnets = new Map<string, string[]>()
for (const id of selectedInterfaceIds) {
const iface = interfaces.find((i) => i.id === id)
- if (iface?.subnet) {
- const names = subnets.get(iface.subnet) ?? []
+ const subnet = iface?.addresses.find((address) => address.family === 4)?.subnet
+ if (subnet) {
+ const names = subnets.get(subnet) ?? []
names.push(iface.displayName)
- subnets.set(iface.subnet, names)
+ subnets.set(subnet, names)
}
}
for (const [subnet, names] of subnets.entries()) {
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 404aa6e..f89f96d 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,4 +1,13 @@
export type NetworkInterfaceKind = 'wifi' | 'usb' | 'ethernet' | 'bridge' | 'other'
+export type IpFamily = 4 | 6
+
+export interface NetworkAddress {
+ address: string
+ family: IpFamily
+ netmask?: string
+ /** Used by the existing IPv4 same-subnet warning. */
+ subnet?: string
+}
export type ThemeSource = 'light' | 'dark'
@@ -7,11 +16,9 @@ export interface NetworkInterfaceInfo {
id: string
device: string
displayName: string
- address: string
+ addresses: NetworkAddress[]
kind: NetworkInterfaceKind
mac?: string
- subnet?: string
- netmask?: string
}
export interface ProbeResult {