github.com/igoogolx/clash@v1.19.8/adapter/inbound/util.go (about) 1 package inbound 2 3 import ( 4 "fmt" 5 "net" 6 "net/http" 7 "strconv" 8 "strings" 9 10 "github.com/igoogolx/clash/common/util" 11 C "github.com/igoogolx/clash/constant" 12 "github.com/igoogolx/clash/transport/socks5" 13 ) 14 15 func parseSocksAddr(target socks5.Addr) *C.Metadata { 16 metadata := &C.Metadata{} 17 18 switch target[0] { 19 case socks5.AtypDomainName: 20 // trim for FQDN 21 metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".") 22 metadata.DstPort = C.Port((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1])) 23 case socks5.AtypIPv4: 24 ip := net.IP(target[1 : 1+net.IPv4len]) 25 metadata.DstIP = ip 26 metadata.DstPort = C.Port((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1])) 27 case socks5.AtypIPv6: 28 ip := net.IP(target[1 : 1+net.IPv6len]) 29 metadata.DstIP = ip 30 metadata.DstPort = C.Port((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1])) 31 } 32 33 return metadata 34 } 35 36 func parseHTTPAddr(request *http.Request) *C.Metadata { 37 host := request.URL.Hostname() 38 port, _ := strconv.ParseUint(util.EmptyOr(request.URL.Port(), "80"), 10, 16) 39 40 // trim FQDN (#737) 41 host = strings.TrimRight(host, ".") 42 43 metadata := &C.Metadata{ 44 NetWork: C.TCP, 45 Host: host, 46 DstIP: nil, 47 DstPort: C.Port(port), 48 } 49 50 if ip := net.ParseIP(host); ip != nil { 51 metadata.DstIP = ip 52 } 53 54 return metadata 55 } 56 57 func parseAddr(addr net.Addr) (net.IP, int, error) { 58 switch a := addr.(type) { 59 case *net.TCPAddr: 60 return a.IP, a.Port, nil 61 case *net.UDPAddr: 62 return a.IP, a.Port, nil 63 default: 64 return nil, 0, fmt.Errorf("unknown address type %s", addr.String()) 65 } 66 }