github.com/laof/lite-speed-test@v0.0.0-20230930011949-1f39b7037845/outbound/util.go (about)

     1  package outbound
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/tls"
     6  	"net"
     7  	"strconv"
     8  	"sync"
     9  	"time"
    10  
    11  	C "github.com/laof/lite-speed-test/constant"
    12  	"github.com/laof/lite-speed-test/transport/resolver"
    13  	"github.com/laof/lite-speed-test/transport/socks5"
    14  )
    15  
    16  const (
    17  	tcpTimeout = 5 * time.Second
    18  )
    19  
    20  var (
    21  	globalClientSessionCache tls.ClientSessionCache
    22  	once                     sync.Once
    23  )
    24  
    25  func getClientSessionCache() tls.ClientSessionCache {
    26  	once.Do(func() {
    27  		globalClientSessionCache = tls.NewLRUClientSessionCache(128)
    28  	})
    29  	return globalClientSessionCache
    30  }
    31  
    32  func tcpKeepAlive(c net.Conn) {
    33  	if tcp, ok := c.(*net.TCPConn); ok {
    34  		tcp.SetKeepAlive(true)
    35  		tcp.SetKeepAlivePeriod(30 * time.Second)
    36  	}
    37  }
    38  
    39  func serializesSocksAddr(metadata *C.Metadata) []byte {
    40  	var buf [][]byte
    41  	addrType := metadata.AddrType()
    42  	aType := uint8(addrType)
    43  	p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
    44  	port := []byte{uint8(p >> 8), uint8(p & 0xff)}
    45  	switch addrType {
    46  	case socks5.AtypDomainName:
    47  		len := uint8(len(metadata.Host))
    48  		host := []byte(metadata.Host)
    49  		buf = [][]byte{{aType, len}, host, port}
    50  	case socks5.AtypIPv4:
    51  		host := metadata.DstIP.To4()
    52  		buf = [][]byte{{aType}, host, port}
    53  	case socks5.AtypIPv6:
    54  		host := metadata.DstIP.To16()
    55  		buf = [][]byte{{aType}, host, port}
    56  	}
    57  	return bytes.Join(buf, nil)
    58  }
    59  
    60  func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
    61  	host, port, err := net.SplitHostPort(address)
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  
    66  	ip, err := resolver.ResolveIP(host)
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  	return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
    71  }