1
0
mirror of https://github.com/nitezs/sub2clash.git synced 2024-12-24 10:54:43 -05:00
sub2clash/parser/hysteria2.go

90 lines
2.3 KiB
Go
Raw Normal View History

2023-10-31 03:14:29 -04:00
package parser
import (
"net/url"
"strings"
2024-04-23 02:39:16 -04:00
"sub2clash/constant"
2023-10-31 03:14:29 -04:00
"sub2clash/model"
)
func ParseHysteria2(proxy string) (model.Proxy, error) {
2024-04-23 02:39:16 -04:00
if !strings.HasPrefix(proxy, constant.Hysteria2Prefix1) &&
!strings.HasPrefix(proxy, constant.Hysteria2Prefix2) {
return model.Proxy{}, &ParseError{Type: ErrInvalidPrefix, Raw: proxy}
}
proxy = strings.TrimPrefix(proxy, constant.Hysteria2Prefix1)
proxy = strings.TrimPrefix(proxy, constant.Hysteria2Prefix2)
urlParts := strings.SplitN(proxy, "@", 2)
if len(urlParts) != 2 {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing character '@' in url",
Raw: proxy,
}
2023-10-31 03:14:29 -04:00
}
2024-04-23 02:39:16 -04:00
password := urlParts[0]
serverInfo := strings.SplitN(urlParts[1], "/?", 2)
if len(serverInfo) != 2 {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing params in url",
Raw: proxy,
}
}
paramStr := serverInfo[1]
2023-10-31 03:14:29 -04:00
serverAndPort := strings.SplitN(serverInfo[0], ":", 2)
2024-04-23 02:39:16 -04:00
var server string
var portStr string
2023-10-31 03:14:29 -04:00
if len(serverAndPort) == 1 {
2024-04-23 02:39:16 -04:00
portStr = "443"
} else if len(serverAndPort) == 2 {
server, portStr = serverAndPort[0], serverAndPort[1]
} else {
return model.Proxy{}, &ParseError{
Type: ErrInvalidStruct,
Message: "missing server host or port",
Raw: proxy,
}
2023-10-31 03:14:29 -04:00
}
2024-04-23 02:39:16 -04:00
port, err := ParsePort(portStr)
2023-10-31 03:14:29 -04:00
if err != nil {
2024-04-23 02:39:16 -04:00
return model.Proxy{}, &ParseError{
Type: ErrInvalidPort,
Message: err.Error(),
Raw: proxy,
}
2023-10-31 03:14:29 -04:00
}
2024-04-23 02:39:16 -04:00
params, err := url.ParseQuery(paramStr)
2023-10-31 03:14:29 -04:00
if err != nil {
2024-04-23 02:39:16 -04:00
return model.Proxy{}, &ParseError{
Type: ErrCannotParseParams,
Raw: proxy,
Message: err.Error(),
}
2024-04-17 09:52:03 -04:00
}
2024-04-23 02:39:16 -04:00
remarks, network, obfs, obfsPassword, pinSHA256, insecure, sni := params.Get("name"), params.Get("network"), params.Get("obfs"), params.Get("obfs-password"), params.Get("pinSHA256"), params.Get("insecure"), params.Get("sni")
enableTLS := pinSHA256 != ""
insecureBool := insecure == "1"
2023-10-31 03:14:29 -04:00
result := model.Proxy{
Type: "hysteria2",
2024-04-23 02:39:16 -04:00
Name: remarks,
Server: server,
Port: port,
2024-04-23 02:39:16 -04:00
Password: password,
Obfs: obfs,
ObfsParam: obfsPassword,
Sni: sni,
SkipCertVerify: insecureBool,
TLS: enableTLS,
Network: network,
2023-10-31 03:14:29 -04:00
}
return result, nil
}