Fix lint errors

This commit is contained in:
世界
2026-05-14 22:53:22 +08:00
parent 4b55717612
commit 2c2e08e608
38 changed files with 284 additions and 333 deletions
+2 -1
View File
@@ -30,7 +30,8 @@ type Store struct {
certificatePaths []string
certificateDirectoryPaths []string
watcher *fswatch.Watcher
platform storePlatform
//nolint:unused // populated only on darwin && cgo via the storePlatform embed.
platform storePlatform
}
func NewStore(ctx context.Context, logger logger.Logger, options option.CertificateOptions) (*Store, error) {
+1
View File
@@ -2,6 +2,7 @@
package certificate
//nolint:unused // referenced by Store.platform; populated only in store_darwin.go.
type storePlatform struct{}
func (s *Store) updatePlatformLocked(_ []byte) error {
@@ -532,7 +532,7 @@ func TestAppleTransportRoundTripHTTPS(t *testing.T) {
}
var normalizedValues []string
for _, value := range observed.values {
for _, part := range strings.Split(value, ",") {
for part := range strings.SplitSeq(value, ",") {
normalizedValues = append(normalizedValues, strings.TrimSpace(part))
}
}
@@ -687,7 +687,7 @@ func TestAppleTransportCancellationRecovery(t *testing.T) {
},
})
for index := 0; index < appleHTTPRecoveryLoops; index++ {
for index := range appleHTTPRecoveryLoops {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
request := newAppleHTTPRequestWithContext(t, ctx, http.MethodGet, server.URL("/block"), nil)
response, err := transport.RoundTrip(request)
+4 -9
View File
@@ -10,6 +10,7 @@ import (
"net/http"
"net/http/httptrace"
"net/url"
"slices"
"sort"
"strings"
"sync"
@@ -513,10 +514,7 @@ func (r *directionRunner) swapIntervalProbeValues() []float64 {
}
func (r *directionRunner) setResponsivenessWindow(currentInterval int) {
lower := currentInterval - settings.movingAvgDistance + 1
if lower < 0 {
lower = 0
}
lower := max(currentInterval-settings.movingAvgDistance+1, 0)
r.probeMu.Lock()
r.responsivenessWindow = &intervalWindow{lower: lower, upper: currentInterval}
r.probeMu.Unlock()
@@ -529,10 +527,7 @@ func (r *directionRunner) recordThroughput(interval int, bps float64) {
}
func (r *directionRunner) setThroughputWindow(currentInterval int) {
lower := currentInterval - settings.movingAvgDistance + 1
if lower < 0 {
lower = 0
}
lower := max(currentInterval-settings.movingAvgDistance+1, 0)
r.probeMu.Lock()
r.throughputWindow = &intervalWindow{lower: lower, upper: currentInterval}
r.probeMu.Unlock()
@@ -956,7 +951,7 @@ func measureIdleLatency(ctx context.Context, factory MeasurementClientFactory, c
maxProbeBytes = measurement.bytes
}
}
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
slices.Sort(latencies)
return int32(latencies[len(latencies)/2]), maxProbeBytes, nil
}
+5 -5
View File
@@ -109,12 +109,12 @@ type schCredentials struct {
}
type tlsParameters struct {
cAlpnIds uint32
rgstrAlpnIds uintptr
_ uint32 // cAlpnIds
_ uintptr // rgstrAlpnIds
grbitDisabledProtocols uint32
cDisabledCrypto uint32
pDisabledCrypto uintptr
dwFlags uint32
_ uint32 // cDisabledCrypto
_ uintptr // pDisabledCrypto
_ uint32 // dwFlags
}
type secPkgContextStreamSizes struct {
+3 -7
View File
@@ -5,6 +5,7 @@ package tls
import (
"context"
"crypto/tls"
"slices"
"strings"
"github.com/sagernet/sing-box/adapter"
@@ -70,13 +71,8 @@ func startACME(ctx context.Context, logger logger.Logger, options option.Inbound
Logger: zapLogger,
}
profile := options.Profile
if profile == "" && acmeServer == certmagic.LetsEncryptProductionCA {
for _, domain := range options.Domain {
if certmagic.SubjectIsIP(domain) {
profile = "shortlived"
break
}
}
if profile == "" && acmeServer == certmagic.LetsEncryptProductionCA && slices.ContainsFunc(options.Domain, certmagic.SubjectIsIP) {
profile = "shortlived"
}
acmeConfig := certmagic.ACMEIssuer{
+3 -3
View File
@@ -39,7 +39,7 @@ var (
func TestAppleClientHandshakeAppliesALPNAndVersion(t *testing.T) {
serverCertificate, serverCertificatePEM := newAppleTestCertificate(t, "localhost")
for index := 0; index < appleTLSSuccessHandshakeLoops; index++ {
for index := range appleTLSSuccessHandshakeLoops {
serverResult, serverAddress := startAppleTLSTestServer(t, &stdtls.Config{
Certificates: []stdtls.Certificate{serverCertificate},
MinVersion: stdtls.VersionTLS12,
@@ -201,7 +201,7 @@ func TestAppleClientHandshakeRecoversAfterFailure(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
for index := 0; index < appleTLSFailureRecoveryLoops; index++ {
for index := range appleTLSFailureRecoveryLoops {
failedResult, failedAddress := startAppleTLSTestServer(t, testCase.serverConfig)
failedConn, err := newAppleTestClientConn(t, failedAddress, testCase.clientOptions)
if err == nil {
@@ -271,7 +271,7 @@ func TestAppleClientConfigCloneWithInlineCertificate(t *testing.T) {
t.Fatalf("Clone shares ALPN slice with original: %v", nextProtos)
}
for index := 0; index < appleTLSFailureRecoveryLoops; index++ {
for index := range appleTLSFailureRecoveryLoops {
serverResult, serverAddress := startAppleTLSTestServer(t, &stdtls.Config{
Certificates: []stdtls.Certificate{serverCertificate},
MinVersion: stdtls.VersionTLS12,
-95
View File
@@ -3,79 +3,16 @@ package tls
import (
"context"
"crypto/x509"
"net"
"os"
"strings"
"time"
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/ntp"
"github.com/sagernet/sing/service"
)
type systemTLSConfig struct {
serverName string
nextProtos []string
handshakeTimeout time.Duration
minVersion uint16
maxVersion uint16
insecure bool
anchorOnly bool
certificatePublicKeySHA256 [][]byte
timeFunc func() time.Time
store adapter.CertificateStore
}
func (c *systemTLSConfig) ServerName() string {
return c.serverName
}
func (c *systemTLSConfig) SetServerName(serverName string) {
c.serverName = serverName
}
func (c *systemTLSConfig) NextProtos() []string {
return c.nextProtos
}
func (c *systemTLSConfig) SetNextProtos(nextProto []string) {
c.nextProtos = append([]string(nil), nextProto...)
}
func (c *systemTLSConfig) HandshakeTimeout() time.Duration {
return c.handshakeTimeout
}
func (c *systemTLSConfig) SetHandshakeTimeout(timeout time.Duration) {
c.handshakeTimeout = timeout
}
func (c *systemTLSConfig) STDConfig() (*STDConfig, error) {
return nil, E.New("STDConfig is unsupported for the system TLS engine")
}
func (c *systemTLSConfig) Client(conn net.Conn) (Conn, error) {
return nil, os.ErrInvalid
}
func (c *systemTLSConfig) clone() systemTLSConfig {
return systemTLSConfig{
serverName: c.serverName,
nextProtos: append([]string(nil), c.nextProtos...),
handshakeTimeout: c.handshakeTimeout,
minVersion: c.minVersion,
maxVersion: c.maxVersion,
insecure: c.insecure,
anchorOnly: c.anchorOnly,
certificatePublicKeySHA256: append([][]byte(nil), c.certificatePublicKeySHA256...),
timeFunc: c.timeFunc,
store: c.store,
}
}
type SystemTLSValidated struct {
MinVersion uint16
MaxVersion uint16
@@ -165,38 +102,6 @@ func resolveSystemAnchors(ctx context.Context, options option.OutboundTLSOptions
return nil, store.ExclusiveAnchors(), store, nil
}
func newSystemTLSConfig(ctx context.Context, serverAddress string, options option.OutboundTLSOptions, allowEmptyServerName bool, engineName string) (systemTLSConfig, SystemTLSValidated, error) {
validated, err := ValidateSystemTLSOptions(ctx, options, engineName)
if err != nil {
return systemTLSConfig{}, SystemTLSValidated{}, err
}
var serverName string
if options.ServerName != "" {
serverName = options.ServerName
} else if serverAddress != "" {
serverName = serverAddress
}
if serverName == "" && !options.Insecure && !allowEmptyServerName {
return systemTLSConfig{}, SystemTLSValidated{}, errMissingServerName
}
handshakeTimeout := C.TCPTimeout
if options.HandshakeTimeout > 0 {
handshakeTimeout = options.HandshakeTimeout.Build()
}
return systemTLSConfig{
serverName: serverName,
nextProtos: append([]string(nil), options.ALPN...),
handshakeTimeout: handshakeTimeout,
minVersion: validated.MinVersion,
maxVersion: validated.MaxVersion,
insecure: options.Insecure || len(options.CertificatePublicKeySHA256) > 0,
anchorOnly: validated.Exclusive,
certificatePublicKeySHA256: append([][]byte(nil), options.CertificatePublicKeySHA256...),
timeFunc: ntp.TimeFuncFromContext(ctx),
store: validated.Store,
}, validated, nil
}
func verifySystemTLSPeer(roots *x509.CertPool, serverName string, timeFunc func() time.Time, peerCertificates []*x509.Certificate) error {
if len(peerCertificates) == 0 {
return E.New("no peer certificates")
+108
View File
@@ -0,0 +1,108 @@
//go:build (darwin && cgo) || windows
package tls
import (
"context"
"net"
"os"
"time"
"github.com/sagernet/sing-box/adapter"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/option"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/ntp"
)
type systemTLSConfig struct {
serverName string
nextProtos []string
handshakeTimeout time.Duration
minVersion uint16
maxVersion uint16
insecure bool
anchorOnly bool
certificatePublicKeySHA256 [][]byte
timeFunc func() time.Time
store adapter.CertificateStore
}
func (c *systemTLSConfig) ServerName() string {
return c.serverName
}
func (c *systemTLSConfig) SetServerName(serverName string) {
c.serverName = serverName
}
func (c *systemTLSConfig) NextProtos() []string {
return c.nextProtos
}
func (c *systemTLSConfig) SetNextProtos(nextProto []string) {
c.nextProtos = append([]string(nil), nextProto...)
}
func (c *systemTLSConfig) HandshakeTimeout() time.Duration {
return c.handshakeTimeout
}
func (c *systemTLSConfig) SetHandshakeTimeout(timeout time.Duration) {
c.handshakeTimeout = timeout
}
func (c *systemTLSConfig) STDConfig() (*STDConfig, error) {
return nil, E.New("STDConfig is unsupported for the system TLS engine")
}
func (c *systemTLSConfig) Client(conn net.Conn) (Conn, error) {
return nil, os.ErrInvalid
}
func (c *systemTLSConfig) clone() systemTLSConfig {
return systemTLSConfig{
serverName: c.serverName,
nextProtos: append([]string(nil), c.nextProtos...),
handshakeTimeout: c.handshakeTimeout,
minVersion: c.minVersion,
maxVersion: c.maxVersion,
insecure: c.insecure,
anchorOnly: c.anchorOnly,
certificatePublicKeySHA256: append([][]byte(nil), c.certificatePublicKeySHA256...),
timeFunc: c.timeFunc,
store: c.store,
}
}
func newSystemTLSConfig(ctx context.Context, serverAddress string, options option.OutboundTLSOptions, allowEmptyServerName bool, engineName string) (systemTLSConfig, SystemTLSValidated, error) {
validated, err := ValidateSystemTLSOptions(ctx, options, engineName)
if err != nil {
return systemTLSConfig{}, SystemTLSValidated{}, err
}
var serverName string
if options.ServerName != "" {
serverName = options.ServerName
} else if serverAddress != "" {
serverName = serverAddress
}
if serverName == "" && !options.Insecure && !allowEmptyServerName {
return systemTLSConfig{}, SystemTLSValidated{}, errMissingServerName
}
handshakeTimeout := C.TCPTimeout
if options.HandshakeTimeout > 0 {
handshakeTimeout = options.HandshakeTimeout.Build()
}
return systemTLSConfig{
serverName: serverName,
nextProtos: append([]string(nil), options.ALPN...),
handshakeTimeout: handshakeTimeout,
minVersion: validated.MinVersion,
maxVersion: validated.MaxVersion,
insecure: options.Insecure || len(options.CertificatePublicKeySHA256) > 0,
anchorOnly: validated.Exclusive,
certificatePublicKeySHA256: append([][]byte(nil), options.CertificatePublicKeySHA256...),
timeFunc: ntp.TimeFuncFromContext(ctx),
store: validated.Store,
}, validated, nil
}
+3 -3
View File
@@ -1110,7 +1110,7 @@ func TestWindowsClientMultipleRoundtrips(t *testing.T) {
clientConn, serverDone := startWindowsEchoServer(t, stdtls.VersionTLS12)
defer clientConn.Close()
for i := 0; i < 100; i++ {
for i := range 100 {
payload := []byte("msg" + string(rune('A'+(i%26))))
_, err := clientConn.Write(payload)
if err != nil {
@@ -1148,7 +1148,7 @@ func TestWindowsClientConcurrentReadWrite(t *testing.T) {
readErr := make(chan error, 1)
readBack := make(chan []byte, messageCount)
go func() {
for i := 0; i < messageCount; i++ {
for range messageCount {
reply := make([]byte, messageSize)
_, err := io.ReadFull(clientConn, reply)
if err != nil {
@@ -1171,7 +1171,7 @@ func TestWindowsClientConcurrentReadWrite(t *testing.T) {
if readResult != nil {
t.Fatal(readResult)
}
for i := 0; i < messageCount; i++ {
for i := range messageCount {
got := <-readBack
if !bytes.Equal(payloads[i], got) {
t.Fatalf("iteration %d: payload mismatch", i)
+2
View File
@@ -1,3 +1,5 @@
//go:build linux || darwin || (windows && (amd64 || 386))
package tlsspoof
import (
+2 -12
View File
@@ -1,3 +1,5 @@
//go:build linux || darwin || (windows && (amd64 || 386))
package tlsspoof
import (
@@ -94,18 +96,6 @@ func buildSpoofFrame(method Method, src, dst netip.AddrPort, sendNext, receiveNe
return buildTCPSegment(src, dst, packetInfo, payload), nil
}
// buildSpoofTCPSegment returns a TCP segment without an IP header, for
// platforms where the kernel synthesises the IP header (darwin IPv6).
func buildSpoofTCPSegment(method Method, src, dst netip.AddrPort, sendNext, receiveNext, timestamp uint32, payload []byte) ([]byte, error) {
packetInfo, err := resolveSpoofPacketInfo(method, sendNext, receiveNext, timestamp, nil, payload)
if err != nil {
return nil, err
}
segment := make([]byte, tcpHeaderLen+len(packetInfo.options)+len(payload))
encodeTCP(segment, 0, src, dst, packetInfo, payload)
return segment, nil
}
func resolveSpoofPacketInfo(method Method, sendNext, receiveNext, timestamp uint32, tcpOptions, payload []byte) (spoofPacketInfo, error) {
packetInfo := spoofPacketInfo{seqNum: sendNext, ackNum: receiveNext}
switch method {
+15
View File
@@ -0,0 +1,15 @@
package tlsspoof
import "net/netip"
// buildSpoofTCPSegment returns a TCP segment without an IP header, for
// platforms where the kernel synthesises the IP header (darwin IPv6).
func buildSpoofTCPSegment(method Method, src, dst netip.AddrPort, sendNext, receiveNext, timestamp uint32, payload []byte) ([]byte, error) {
packetInfo, err := resolveSpoofPacketInfo(method, sendNext, receiveNext, timestamp, nil, payload)
if err != nil {
return nil, err
}
segment := make([]byte, tcpHeaderLen+len(packetInfo.options)+len(payload))
encodeTCP(segment, 0, src, dst, packetInfo, payload)
return segment, nil
}
+2
View File
@@ -1,3 +1,5 @@
//go:build linux || darwin || (windows && (amd64 || 386))
package tlsspoof
// realClientHello is a captured Chrome ClientHello for github.com.
+2 -2
View File
@@ -72,14 +72,14 @@ func TestIntegrationRecvAbortsOnClose(t *testing.T) {
func TestIntegrationConcurrentOpen(t *testing.T) {
errCh := make(chan error, 2)
handles := make(chan *Handle, 2)
for i := 0; i < 2; i++ {
for range 2 {
go func() {
h, err := Open(nil, LayerNetwork, 0, FlagSendOnly)
handles <- h
errCh <- err
}()
}
for i := 0; i < 2; i++ {
for range 2 {
err := <-errCh
h := <-handles
require.NoError(t, err)
+1 -1
View File
@@ -48,7 +48,7 @@ type Address struct {
Timestamp int64
bits uint32
Reserved2 uint32
union [64]byte
_ [64]byte
}
var _ [80]byte = [unsafe.Sizeof(Address{})]byte{}