@@ -84,6 +84,15 @@ var ErrPairingPortNotFound = errors.New("manual pairing port not found")
8484// the address itself is reachable.
8585var 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.
8897const (
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
0 commit comments