Skip to content

Commit f6c53de

Browse files
committed
fix(device): fail fast when a manual device is unreachable
A full sweep of the dynamic port range is slow when the device is simply offline: a Tailscale peer whose client is not connected drops every SYN until each dial times out, so the user waits for the whole scan before learning anything. Derive reachability from the scan's own dials instead of probing a fixed port (the tunnel port is dynamic, so a fixed probe cannot tell "not listening" from "unreachable"): an accepted or refused/RSTed dial proves the host is up, while a full wave of timeouts proves it is not. Abort the sweep after one silent wave and report ErrDeviceUnreachable, turning a multi-second wait into a ~1.5s failure with a message that names the real cause. A live host still scans normally because its first wave always answers. Measured against a Tailscale iPhone (100.65.100.37): offline 1.5s instead of 35s+; online but off Wi-Fi still reports the Wi-Fi cause.
1 parent 8a10093 commit f6c53de

3 files changed

Lines changed: 234 additions & 20 deletions

File tree

‎internal/manager/manual_device_test.go‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,26 @@ func TestPrepareManualDeviceReusesAliveRememberedPort(t *testing.T) {
194194
}
195195
}
196196

197+
// When the remembered port does not answer and the address itself is
198+
// unreachable (Tailscale client not connected), the full scan reports
199+
// ErrDeviceUnreachable and PrepareManualDevice surfaces it, rather than
200+
// swallowing it into a generic "port not found".
201+
func TestPrepareManualDeviceReportsUnreachable(t *testing.T) {
202+
withTunnelProbe(t, func(context.Context, string, DiscoveryProgress) (uint16, *PairingServiceInfo, error) {
203+
return 0, nil, ErrDeviceUnreachable
204+
})
205+
withRememberedPortProbe(t, func(context.Context, string, uint16) (*PairingServiceInfo, error) {
206+
return nil, errors.New("no answer")
207+
})
208+
209+
dm := newDeviceManager()
210+
dev := model.Device{IP: "100.65.100.37", UDID: "AAA", Manual: true, Port: 49152, PortResolvedAt: time.Now().Add(-2 * manualPortTTL)}
211+
err := dm.PrepareManualDevice(context.Background(), &dev)
212+
if !errors.Is(err, ErrDeviceUnreachable) {
213+
t.Fatalf("want ErrDeviceUnreachable, got %v", err)
214+
}
215+
}
216+
197217
// A transient failure on the remembered-port re-check must be retried before
198218
// escalating to a full-range scan, so one dropped handshake on a slow relay
199219
// does not cost a multi-second sweep.

‎internal/manager/pairing_port_discovery.go‎

Lines changed: 103 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,15 @@ var ErrPairingPortNotFound = errors.New("manual pairing port not found")
8484
// the address itself is reachable.
8585
var ErrTunnelPortNotFound = errors.New("manual tunnel port not found: the iPhone must be connected to Wi-Fi for the connection to work")
8686

87+
// ErrDeviceUnreachable is returned when every dial in the port scan timed out
88+
// without a single response. A reachable host answers at least one port (an
89+
// open port accepts, a closed port refuses/RSTs), so a range where nothing
90+
// ever answers means the address is not responding at all — for example a
91+
// Tailscale peer whose client is not connected. Reporting this instead of
92+
// "port not found" tells the user the real cause: the device is offline, not
93+
// that its service moved.
94+
var ErrDeviceUnreachable = errors.New("device is unreachable: check that the device is online and, for Tailscale, that its client is connected")
95+
8796
// Discovery stages reported to the caller so the UI can show progress.
8897
const (
8998
DiscoverStageMDNS = "mdns"
@@ -256,14 +265,43 @@ func discoverPortMDNS(ctx context.Context, ip, fqdn string, timeout time.Duratio
256265
return 0, false
257266
}
258267

268+
// scanDialFunc dials one port and returns a nil error when the port is open.
269+
// A non-nil error distinguishes a refusal/reset (the host answered) from a
270+
// timeout (it did not). Replaceable so tests never dial real endpoints.
271+
var scanDialFunc = func(ctx context.Context, ip string, port uint16, timeout time.Duration) error {
272+
dialer := net.Dialer{Timeout: timeout}
273+
conn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(ip, strconv.Itoa(int(port))))
274+
if err != nil {
275+
return err
276+
}
277+
_ = conn.Close()
278+
return nil
279+
}
280+
281+
// unreachableAbortAfter is how many dials must complete with zero responses
282+
// before the scan concludes the address is offline and stops. One full
283+
// concurrent wave (rpDialConcurrency) is enough: a reachable host answers
284+
// within the first round trip — an open port accepts and a closed port
285+
// refuses/RSTs — while an offline overlay peer (Tailscale client not
286+
// connected) drops every SYN until each dial times out. Aborting after one
287+
// silent wave turns a multi-second sweep into a ~1.5s failure without risking
288+
// a false "unreachable" on a live host.
289+
const unreachableAbortAfter = rpDialConcurrency
290+
259291
// scanProbedPorts dials ports in [first,last] in ascending order and probes
260292
// every open port with the RPPairing handshake as soon as its dial succeeds.
261293
// The first probed service satisfying pick wins: discovery returns
262294
// immediately and cancels the remaining work, so services on low ports
263295
// (the common case, since Darwin allocates ephemeral ports ascending) are
264-
// found without scanning the rest of the range. It returns nil when the
265-
// range is exhausted or ctx is cancelled.
266-
func scanProbedPorts(ctx context.Context, ip string, first, last uint16, pick portMatcher, progress DiscoveryProgress) *PairingServiceInfo {
296+
// found without scanning the rest of the range.
297+
//
298+
// It returns nil when the range is exhausted or ctx is cancelled, plus
299+
// hostAnswered: whether any dial got a response at all (an open port accepted,
300+
// or a closed port refused/RSTed). A live host answers at least one port, so
301+
// hostAnswered == false after a full sweep means the address is offline rather
302+
// than merely lacking the service — the caller turns that into
303+
// ErrDeviceUnreachable instead of "port not found".
304+
func scanProbedPorts(ctx context.Context, ip string, first, last uint16, pick portMatcher, progress DiscoveryProgress) (*PairingServiceInfo, bool) {
267305
report := func(stage string, pct int) {
268306
if progress != nil {
269307
progress(stage, pct)
@@ -272,46 +310,73 @@ func scanProbedPorts(ctx context.Context, ip string, first, last uint16, pick po
272310

273311
report(DiscoverStageScanning, 0)
274312
var (
275-
wg sync.WaitGroup
276-
mu sync.Mutex
277-
found *PairingServiceInfo
278-
probed int64
279-
reported int32
313+
wg sync.WaitGroup
314+
mu sync.Mutex
315+
found *PairingServiceInfo
316+
probed int64
317+
reported int32
318+
answered int32
319+
dialed int64
320+
abortOnce sync.Once
280321
)
281322
total := int(last) - int(first) + 1
282323
// Closes when the winner is decided; every goroutine path selects on it
283324
// so in-flight work stops promptly.
284325
won := make(chan struct{})
326+
// Closes when the address is proven offline (one silent wave of dials);
327+
// the derived scanCtx cancels the in-flight dials so wg.Wait returns at
328+
// once instead of waiting out their timeouts.
329+
unreachable := make(chan struct{})
330+
scanCtx, stopScan := context.WithCancel(ctx)
331+
defer stopScan()
285332
sem := make(chan struct{}, rpDialConcurrency)
286333
// Handshake probes are slower than dials; bound them separately so dials
287334
// keep flowing ahead of the probes.
288335
probeSem := make(chan struct{}, rpProbeConcurrency)
289336

290-
dialLoop:
337+
// noteDialDone runs after every completed dial and aborts the sweep once a
338+
// full wave has produced no response at all.
339+
noteDialDone := func() {
340+
if atomic.AddInt64(&dialed, 1) >= unreachableAbortAfter && atomic.LoadInt32(&answered) == 0 {
341+
abortOnce.Do(func() {
342+
close(unreachable)
343+
stopScan()
344+
})
345+
}
346+
}
347+
348+
dials:
291349
for port := int(first); port <= int(last); port++ {
292350
select {
293351
case <-won:
294-
break dialLoop
352+
break dials
353+
case <-unreachable:
354+
break dials
295355
case <-ctx.Done():
296-
break dialLoop
356+
break dials
297357
case sem <- struct{}{}:
298358
}
299359
wg.Add(1)
300360
go func(p uint16) {
301361
defer wg.Done()
302362
defer func() { <-sem }()
303363

304-
dialer := net.Dialer{Timeout: rpDialTimeout}
305-
conn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(ip, strconv.Itoa(int(p))))
306-
if err != nil {
364+
if err := scanDialFunc(scanCtx, ip, p, rpDialTimeout); err != nil {
365+
// A non-timeout error (refused/reset) still proves the host
366+
// is up; a timeout does not. Dials cancelled by our own abort
367+
// prove nothing, so ignore them.
368+
if !isTimeout(err) && !errors.Is(err, context.Canceled) {
369+
atomic.StoreInt32(&answered, 1)
370+
}
307371
n := atomic.AddInt64(&probed, 1)
308372
reportPct(report, &reported, int(n), total)
373+
noteDialDone()
309374
return
310375
}
311-
_ = conn.Close()
312-
376+
atomic.StoreInt32(&answered, 1)
313377
select {
314378
case <-won:
379+
noteDialDone()
315380
return
316381
case probeSem <- struct{}{}:
317382
}
@@ -333,14 +398,23 @@ dialLoop:
333398
}
334399
mu.Unlock()
335400
}()
401+
noteDialDone()
336402
}(uint16(port))
337403
}
338404
wg.Wait()
339405

406+
hostAnswered := atomic.LoadInt32(&answered) == 1
340407
if ctx.Err() != nil && found == nil {
341-
return nil
408+
return nil, hostAnswered
342409
}
343-
return found
410+
return found, hostAnswered
411+
}
412+
413+
// isTimeout reports whether err is a dial timeout (the host did not answer) as
414+
// opposed to a refusal or reset (the host answered and rejected the dial).
415+
func isTimeout(err error) bool {
416+
var nerr net.Error
417+
return errors.As(err, &nerr) && nerr.Timeout()
344418
}
345419

346420
// reportPct throttles scanning progress to 5% steps; report may be nil.
@@ -387,13 +461,23 @@ func discoverPortByService(ctx context.Context, ip, fqdn string, first, last uin
387461
}
388462
}
389463

390-
if si := scanProbedPorts(ctx, ip, first, last, pick, progress); si != nil {
464+
si, hostAnswered := scanProbedPorts(ctx, ip, first, last, pick, progress)
465+
if si != nil {
391466
report(DiscoverStageFound, 100)
392467
return si.Port, si, nil
393468
}
394469
if ctx.Err() != nil {
395470
return 0, nil, ctx.Err()
396471
}
472+
// Nothing answered the whole range. A reachable host answers at least one
473+
// port (accept or refuse/RST), so a silent sweep means the address itself
474+
// is offline — report that rather than a misleading "port not found". The
475+
// tunnel port is dynamic, so this is decided from the scan's own dials,
476+
// never from a fixed port that may simply not be the one in use.
477+
if !hostAnswered {
478+
report(DiscoverStageFailed, 100)
479+
return 0, nil, ErrDeviceUnreachable
480+
}
397481

398482
report(DiscoverStageFailed, 100)
399483
return 0, nil, nil

‎internal/manager/pairing_port_discovery_test.go‎

Lines changed: 111 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ import (
44
"context"
55
"encoding/binary"
66
"encoding/json"
7+
"errors"
78
"io"
89
"net"
910
"strings"
11+
"sync/atomic"
1012
"testing"
1113
"time"
1214
)
@@ -221,7 +223,7 @@ func TestScanProbedPortsStopsEarlyOnLowPort(t *testing.T) {
221223
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
222224
defer cancel()
223225
start := time.Now()
224-
si := scanProbedPorts(ctx, "127.0.0.1", port, 65535, func(si *PairingServiceInfo) bool {
226+
si, _ := scanProbedPorts(ctx, "127.0.0.1", port, 65535, func(si *PairingServiceInfo) bool {
225227
return si.Tunnel
226228
}, nil)
227229
elapsed := time.Since(start)
@@ -249,3 +251,111 @@ func TestSkipMDNSForTailnetIPs(t *testing.T) {
249251
}
250252
}
251253
}
254+
255+
// stubScanDial controls the per-port dial outcome so the scan's reachability
256+
// bookkeeping can be tested without real sockets: open ports accept, and every
257+
// other port fails with the given error (refused or timeout).
258+
func stubScanDial(t *testing.T, openPorts []uint16, otherErr func() error) {
259+
t.Helper()
260+
prev := scanDialFunc
261+
open := make(map[uint16]bool, len(openPorts))
262+
for _, p := range openPorts {
263+
open[p] = true
264+
}
265+
scanDialFunc = func(ctx context.Context, ip string, port uint16, timeout time.Duration) error {
266+
if open[port] {
267+
return nil
268+
}
269+
return otherErr()
270+
}
271+
t.Cleanup(func() { scanDialFunc = prev })
272+
}
273+
274+
// A sweep where every dial is refused (RST) still proves the host is up: the
275+
// scan reports hostAnswered and the caller returns "port not found", not
276+
// unreachable.
277+
func TestScanProbedPortsRefusedMeansHostAnswered(t *testing.T) {
278+
stubScanDial(t, nil, func() error { return &net.OpError{Err: errors.New("connection refused")} })
279+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
280+
defer cancel()
281+
si, answered := scanProbedPorts(ctx, "100.65.100.37", rpPortFirst, rpPortFirst+8, func(*PairingServiceInfo) bool {
282+
return false
283+
}, nil)
284+
if si != nil {
285+
t.Fatalf("no service should be found, got %+v", si)
286+
}
287+
if !answered {
288+
t.Fatal("refused dials prove the host answered")
289+
}
290+
}
291+
292+
// A sweep where every dial times out means the host is offline: hostAnswered
293+
// stays false.
294+
func TestScanProbedPortsAllTimeoutsMeansUnreachable(t *testing.T) {
295+
stubScanDial(t, nil, func() error {
296+
return &net.OpError{Err: &timeoutError{}}
297+
})
298+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
299+
defer cancel()
300+
_, answered := scanProbedPorts(ctx, "100.65.100.37", rpPortFirst, rpPortFirst+8, func(*PairingServiceInfo) bool {
301+
return false
302+
}, nil)
303+
if answered {
304+
t.Fatal("a host that never answers must not count as reachable")
305+
}
306+
}
307+
308+
// timeoutError is a net.Error whose Timeout() is true, mirroring a dial that
309+
// silently drops the SYN.
310+
type timeoutError struct{}
311+
312+
func (timeoutError) Error() string { return "i/o timeout" }
313+
func (timeoutError) Timeout() bool { return true }
314+
func (timeoutError) Temporary() bool { return true }
315+
316+
// discoverPortByService turns an all-timeout sweep into ErrDeviceUnreachable so
317+
// the caller reports an offline device instead of a misleading "port not found".
318+
func TestDiscoverPortByServiceReportsUnreachable(t *testing.T) {
319+
stubScanDial(t, nil, func() error { return &net.OpError{Err: &timeoutError{}} })
320+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
321+
defer cancel()
322+
_, _, err := discoverPortByService(ctx, "100.65.100.37", rpTunnelFQDN, rpPortFirst, rpPortFirst+8, true, func(si *PairingServiceInfo) bool {
323+
return si.Tunnel
324+
}, nil)
325+
if !errors.Is(err, ErrDeviceUnreachable) {
326+
t.Fatalf("want ErrDeviceUnreachable, got %v", err)
327+
}
328+
}
329+
330+
// An offline host (every dial times out) must abort after roughly one silent
331+
// wave instead of sweeping the whole 16k-port range, so the user learns the
332+
// device is unreachable quickly.
333+
func TestScanProbedPortsAbortsEarlyWhenUnreachable(t *testing.T) {
334+
var dials int64
335+
prev := scanDialFunc
336+
scanDialFunc = func(context.Context, string, uint16, time.Duration) error {
337+
atomic.AddInt64(&dials, 1)
338+
return &net.OpError{Err: &timeoutError{}}
339+
}
340+
t.Cleanup(func() { scanDialFunc = prev })
341+
342+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
343+
defer cancel()
344+
start := time.Now()
345+
si, answered := scanProbedPorts(ctx, "100.65.100.37", rpPortFirst, rpPortLast, func(*PairingServiceInfo) bool {
346+
return true
347+
}, nil)
348+
if si != nil {
349+
t.Fatalf("no service expected, got %+v", si)
350+
}
351+
if answered {
352+
t.Fatal("all-timeout host must not be reported as reachable")
353+
}
354+
if elapsed := time.Since(start); elapsed > 2*time.Second {
355+
t.Fatalf("offline sweep should abort early, took %v", elapsed)
356+
}
357+
// It must not have dialed anywhere near the full range.
358+
if got := atomic.LoadInt64(&dials); got > int64(unreachableAbortAfter)+int64(rpDialConcurrency) {
359+
t.Fatalf("dialed %d ports, expected ~%d", got, unreachableAbortAfter)
360+
}
361+
}

0 commit comments

Comments
 (0)
⌂ 换网址