github.com/chwjbn/xclash@v0.2.0/adapter/inbound/util.go (about) 1 package inbound 2 3 import ( 4 "net" 5 "net/http" 6 "strconv" 7 "strings" 8 9 C "github.com/chwjbn/xclash/constant" 10 "github.com/chwjbn/xclash/transport/socks5" 11 ) 12 13 func parseSocksAddr(target socks5.Addr) *C.Metadata { 14 metadata := &C.Metadata{ 15 AddrType: int(target[0]), 16 } 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 = strconv.Itoa((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 = strconv.Itoa((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 = strconv.Itoa((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 := request.URL.Port() 39 if port == "" { 40 port = "80" 41 } 42 43 // trim FQDN (#737) 44 host = strings.TrimRight(host, ".") 45 46 metadata := &C.Metadata{ 47 NetWork: C.TCP, 48 AddrType: C.AtypDomainName, 49 Host: host, 50 DstIP: nil, 51 DstPort: port, 52 } 53 54 ip := net.ParseIP(host) 55 if ip != nil { 56 switch { 57 case ip.To4() == nil: 58 metadata.AddrType = C.AtypIPv6 59 default: 60 metadata.AddrType = C.AtypIPv4 61 } 62 metadata.DstIP = ip 63 } 64 65 return metadata 66 } 67 68 func parseAddr(addr string) (net.IP, string, error) { 69 host, port, err := net.SplitHostPort(addr) 70 if err != nil { 71 return nil, "", err 72 } 73 74 ip := net.ParseIP(host) 75 return ip, port, nil 76 }