2019-12-08 12:17:24 +08:00
|
|
|
package outbound
|
2018-08-08 11:51:06 +08:00
|
|
|
|
|
|
|
import (
|
2019-04-25 13:48:47 +08:00
|
|
|
"bytes"
|
2018-08-08 11:51:06 +08:00
|
|
|
"net"
|
2019-04-25 13:48:47 +08:00
|
|
|
"strconv"
|
2018-08-08 11:51:06 +08:00
|
|
|
"time"
|
|
|
|
|
2020-02-15 21:42:46 +08:00
|
|
|
"github.com/Dreamacro/clash/component/resolver"
|
2018-08-08 11:51:06 +08:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
2021-05-13 22:18:49 +08:00
|
|
|
"github.com/Dreamacro/clash/transport/socks5"
|
2018-08-08 11:51:06 +08:00
|
|
|
)
|
|
|
|
|
2018-08-29 15:00:12 +08:00
|
|
|
func tcpKeepAlive(c net.Conn) {
|
|
|
|
if tcp, ok := c.(*net.TCPConn); ok {
|
|
|
|
tcp.SetKeepAlive(true)
|
2018-10-01 19:42:15 +08:00
|
|
|
tcp.SetKeepAlivePeriod(30 * time.Second)
|
2018-08-29 15:00:12 +08:00
|
|
|
}
|
|
|
|
}
|
2018-11-01 11:54:45 +08:00
|
|
|
|
2019-04-25 13:48:47 +08:00
|
|
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
|
|
|
var buf [][]byte
|
|
|
|
aType := uint8(metadata.AddrType)
|
2021-11-08 00:31:08 +08:00
|
|
|
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
2019-04-25 13:48:47 +08:00
|
|
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
|
|
|
switch metadata.AddrType {
|
|
|
|
case socks5.AtypDomainName:
|
|
|
|
len := uint8(len(metadata.Host))
|
|
|
|
host := []byte(metadata.Host)
|
|
|
|
buf = [][]byte{{aType, len}, host, port}
|
|
|
|
case socks5.AtypIPv4:
|
2019-05-09 21:00:29 +08:00
|
|
|
host := metadata.DstIP.To4()
|
2019-04-25 13:48:47 +08:00
|
|
|
buf = [][]byte{{aType}, host, port}
|
|
|
|
case socks5.AtypIPv6:
|
2019-05-09 21:00:29 +08:00
|
|
|
host := metadata.DstIP.To16()
|
2019-04-25 13:48:47 +08:00
|
|
|
buf = [][]byte{{aType}, host, port}
|
|
|
|
}
|
|
|
|
return bytes.Join(buf, nil)
|
|
|
|
}
|
|
|
|
|
2019-06-29 00:58:59 +08:00
|
|
|
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
|
|
|
host, port, err := net.SplitHostPort(address)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-02-15 21:42:46 +08:00
|
|
|
ip, err := resolver.ResolveIP(host)
|
2019-06-29 00:58:59 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
|
|
|
}
|
2021-03-22 23:26:20 +08:00
|
|
|
|
|
|
|
func safeConnClose(c net.Conn, err error) {
|
|
|
|
if err != nil {
|
|
|
|
c.Close()
|
|
|
|
}
|
|
|
|
}
|