mihomo/adapter/inbound/util.go

81 lines
1.9 KiB
Go
Raw Normal View History

2019-12-08 12:17:24 +08:00
package inbound
import (
2023-01-17 15:41:51 +08:00
"errors"
"net"
2018-08-12 16:18:58 +08:00
"net/http"
2022-04-20 01:52:51 +08:00
"net/netip"
"strconv"
2020-06-11 11:10:08 +08:00
"strings"
2023-01-17 15:41:51 +08:00
"github.com/Dreamacro/clash/common/nnip"
C "github.com/Dreamacro/clash/constant"
2021-05-13 22:18:49 +08:00
"github.com/Dreamacro/clash/transport/socks5"
)
2019-04-25 13:48:47 +08:00
func parseSocksAddr(target socks5.Addr) *C.Metadata {
2022-11-11 09:19:28 +08:00
metadata := &C.Metadata{}
switch target[0] {
2019-04-25 13:48:47 +08:00
case socks5.AtypDomainName:
2020-06-11 12:11:44 +08:00
// trim for FQDN
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
2019-05-09 21:00:29 +08:00
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
2019-04-25 13:48:47 +08:00
case socks5.AtypIPv4:
2022-04-20 01:52:51 +08:00
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
2019-05-09 21:00:29 +08:00
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
2019-04-25 13:48:47 +08:00
case socks5.AtypIPv6:
ip6, _ := netip.AddrFromSlice(target[1 : 1+net.IPv6len])
metadata.DstIP = ip6.Unmap()
2019-05-09 21:00:29 +08:00
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
}
2018-12-05 21:13:29 +08:00
return metadata
}
2018-09-30 12:25:52 +08:00
func parseHTTPAddr(request *http.Request) *C.Metadata {
2018-08-27 00:06:40 +08:00
host := request.URL.Hostname()
port := request.URL.Port()
if port == "" {
port = "80"
}
2020-06-11 11:10:08 +08:00
// trim FQDN (#737)
host = strings.TrimRight(host, ".")
2018-12-05 21:13:29 +08:00
metadata := &C.Metadata{
2022-11-11 09:19:28 +08:00
NetWork: C.TCP,
Host: host,
DstIP: netip.Addr{},
DstPort: port,
}
2018-12-05 21:13:29 +08:00
2022-04-20 01:52:51 +08:00
ip, err := netip.ParseAddr(host)
if err == nil {
metadata.DstIP = ip
2018-12-05 21:13:29 +08:00
}
return metadata
}
2023-01-17 15:41:51 +08:00
func parseAddr(addr net.Addr) (netip.Addr, string, error) {
// Filter when net.Addr interface is nil
if addr == nil {
return netip.Addr{}, "", errors.New("nil addr")
}
if rawAddr, ok := addr.(interface{ RawAddr() net.Addr }); ok {
ip, port, err := parseAddr(rawAddr.RawAddr())
if err == nil {
return ip, port, err
}
}
addrStr := addr.String()
host, port, err := net.SplitHostPort(addrStr)
2019-05-09 21:00:29 +08:00
if err != nil {
2022-04-20 01:52:51 +08:00
return netip.Addr{}, "", err
}
2019-05-09 21:00:29 +08:00
2022-04-20 01:52:51 +08:00
ip, err := netip.ParseAddr(host)
return ip, port, err
}