github.com/yaling888/clash@v1.53.0/adapter/inbound/util.go (about) 1 package inbound 2 3 import ( 4 "fmt" 5 "net" 6 "net/http" 7 "net/netip" 8 "strconv" 9 "strings" 10 11 "github.com/yaling888/clash/common/util" 12 C "github.com/yaling888/clash/constant" 13 "github.com/yaling888/clash/transport/socks5" 14 ) 15 16 func parseSocksAddr(target socks5.Addr) *C.Metadata { 17 metadata := &C.Metadata{} 18 19 switch target[0] { 20 case socks5.AtypDomainName: 21 // trim for FQDN 22 metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".") 23 metadata.DstPort = C.Port((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1])) 24 case socks5.AtypIPv4: 25 metadata.DstIP, _ = netip.AddrFromSlice(target[1 : 1+net.IPv4len]) 26 metadata.DstPort = C.Port((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1])) 27 case socks5.AtypIPv6: 28 ip6, _ := netip.AddrFromSlice(target[1 : 1+net.IPv6len]) 29 metadata.DstIP = ip6.Unmap() 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: netip.Addr{}, 47 DstPort: C.Port(port), 48 } 49 50 if ip, err := netip.ParseAddr(host); err == nil { 51 metadata.DstIP = ip 52 } 53 54 return metadata 55 } 56 57 func parseAddr(addr net.Addr) (netip.Addr, int, error) { 58 switch a := addr.(type) { 59 case *net.TCPAddr: 60 ip, _ := netip.AddrFromSlice(a.IP) 61 return ip.Unmap(), a.Port, nil 62 case *net.UDPAddr: 63 ip, _ := netip.AddrFromSlice(a.IP) 64 return ip.Unmap(), a.Port, nil 65 default: 66 return netip.Addr{}, 0, fmt.Errorf("unknown address type %T", addr) 67 } 68 }