fix: tcp concurrent force close when context done

This commit is contained in:
Skyxim 2022-06-25 09:00:35 +08:00
parent 0d55b28805
commit f979491013

View file

@ -4,11 +4,10 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"github.com/Dreamacro/clash/component/resolver"
"net" "net"
"net/netip" "net/netip"
"sync" "sync"
"github.com/Dreamacro/clash/component/resolver"
) )
var ( var (
@ -171,7 +170,10 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
go startRacer(ctx, network+"4", host, opt.direct, false) go startRacer(ctx, network+"4", host, opt.direct, false)
go startRacer(ctx, network+"6", host, opt.direct, true) go startRacer(ctx, network+"6", host, opt.direct, true)
for res := range results { count := 2
for i := 0; i < count; i++ {
select {
case res := <-results:
if res.error == nil { if res.error == nil {
return res.Conn, nil return res.Conn, nil
} }
@ -191,6 +193,9 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
return nil, primary.error return nil, primary.error
} }
} }
case <-ctx.Done():
break
}
} }
return nil, errors.New("never touched") return nil, errors.New("never touched")
@ -225,7 +230,6 @@ func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr
} }
results := make(chan dialResult) results := make(chan dialResult)
tcpRacer := func(ctx context.Context, ip netip.Addr) { tcpRacer := func(ctx context.Context, ip netip.Addr) {
result := dialResult{ip: ip} result := dialResult{ip: ip}
@ -252,13 +256,13 @@ func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr
} }
connCount := len(ips) connCount := len(ips)
for res := range results { for i := 0; i < connCount; i++ {
connCount-- select {
case res := <-results:
if res.error == nil { if res.error == nil {
return res.Conn, nil return res.Conn, nil
} }
case <-ctx.Done():
if connCount == 0 {
break break
} }
} }