Release 1.2.0 Windows amd64 with Hysteria 2

This commit is contained in:
Navis
2026-07-28 07:14:52 +03:00
parent 5d968dc0e3
commit 7eaf53f7c2
22 changed files with 801 additions and 75 deletions
+174
View File
@@ -0,0 +1,174 @@
package hysteria2
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
const githubAPILatest = "https://api.github.com/repos/apernet/hysteria/releases/latest"
// ResolveBinary finds hysteria client binary.
func ResolveBinary(binDir string) (string, error) {
names := candidateNames()
candidates := []string{}
for _, name := range names {
candidates = append(candidates,
filepath.Join(binDir, name),
filepath.Join(binDir, "hysteria2", name),
filepath.Join(binDir, "hysteria", name),
)
}
if exe, err := os.Executable(); err == nil {
dir := filepath.Dir(exe)
for _, name := range names {
candidates = append(candidates, filepath.Join(dir, name), filepath.Join(dir, "bin", name))
}
}
for _, c := range candidates {
if st, err := os.Stat(c); err == nil && !st.IsDir() {
return c, nil
}
}
return "", fmt.Errorf("hysteria2 binary not found in %s; run install-core", binDir)
}
func candidateNames() []string {
if runtime.GOOS == "windows" {
return []string{
"hysteria.exe",
"hysteria-windows-amd64.exe",
"hysteria-windows-amd64-avx.exe",
}
}
return []string{"hysteria", "hysteria-linux-amd64"}
}
// EnsureBinary downloads official Hysteria 2 release if missing.
func EnsureBinary(binDir string) (string, error) {
if path, err := ResolveBinary(binDir); err == nil {
return path, nil
}
if err := os.MkdirAll(binDir, 0o755); err != nil {
return "", err
}
want, err := releaseAssetName()
if err != nil {
return "", err
}
fmt.Fprintf(os.Stderr, "downloading official hysteria2 release (%s)...\n", want)
name, url, err := findReleaseAsset(want)
if err != nil {
return "", err
}
destName := "hysteria"
if runtime.GOOS == "windows" {
destName = "hysteria.exe"
}
dest := filepath.Join(binDir, destName)
tmp := filepath.Join(binDir, name+".download")
if err := downloadFile(tmp, url); err != nil {
return "", err
}
_ = os.Remove(dest)
if err := os.Rename(tmp, dest); err != nil {
_ = os.Remove(tmp)
return "", err
}
_ = os.Chmod(dest, 0o755)
return ResolveBinary(binDir)
}
func releaseAssetName() (string, error) {
switch {
case runtime.GOOS == "windows" && runtime.GOARCH == "amd64":
return "hysteria-windows-amd64.exe", nil
case runtime.GOOS == "windows" && runtime.GOARCH == "arm64":
return "hysteria-windows-arm64.exe", nil
case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
return "hysteria-linux-amd64", nil
case runtime.GOOS == "darwin" && runtime.GOARCH == "amd64":
return "hysteria-darwin-amd64", nil
case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":
return "hysteria-darwin-arm64", nil
default:
return "", fmt.Errorf("unsupported platform %s/%s for hysteria2 auto-download", runtime.GOOS, runtime.GOARCH)
}
}
type ghRelease struct {
TagName string `json:"tag_name"`
Assets []struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
} `json:"assets"`
}
func findReleaseAsset(exactName string) (name, downloadURL string, err error) {
client := &http.Client{Timeout: 60 * time.Second}
req, err := http.NewRequest(http.MethodGet, githubAPILatest, nil)
if err != nil {
return "", "", err
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", "navis-vpnclient")
resp, err := client.Do(req)
if err != nil {
return "", "", fmt.Errorf("github api: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return "", "", fmt.Errorf("github api: %s: %s", resp.Status, string(body))
}
var rel ghRelease
if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
return "", "", err
}
// Prefer exact non-avx name; fall back to avx variant on Windows.
var fallback string
var fallbackURL string
for _, a := range rel.Assets {
if a.Name == exactName {
return a.Name, a.BrowserDownloadURL, nil
}
if exactName == "hysteria-windows-amd64.exe" && a.Name == "hysteria-windows-amd64-avx.exe" {
fallback, fallbackURL = a.Name, a.BrowserDownloadURL
}
}
if fallback != "" {
return fallback, fallbackURL, nil
}
// Prefix match for versioned names
for _, a := range rel.Assets {
if strings.HasPrefix(a.Name, strings.TrimSuffix(exactName, filepath.Ext(exactName))) {
return a.Name, a.BrowserDownloadURL, nil
}
}
return "", "", fmt.Errorf("no asset %s in release %s", exactName, rel.TagName)
}
func downloadFile(path, url string) error {
client := &http.Client{Timeout: 10 * time.Minute}
resp, err := client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("download %s: %s", url, resp.Status)
}
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, resp.Body)
return err
}
+212
View File
@@ -0,0 +1,212 @@
package hysteria2
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"vpnclient/internal/config"
)
// Engine runs the official apernet/hysteria client (Hysteria 2).
type Engine struct {
mu sync.Mutex
cmd *exec.Cmd
cancel context.CancelFunc
done chan struct{}
workdir string
profile config.Profile
stderr io.Writer
running bool
}
func New(stderr io.Writer) *Engine {
if stderr == nil {
stderr = os.Stderr
}
return &Engine{stderr: stderr}
}
func (e *Engine) Protocol() config.Protocol { return config.ProtocolHysteria2 }
func (e *Engine) Start(ctx context.Context, profile config.Profile, binDir string) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.running {
return fmt.Errorf("hysteria2: already running")
}
bin, err := ResolveBinary(binDir)
if err != nil {
return err
}
workdir, err := os.MkdirTemp("", "vpnclient-hy2-*")
if err != nil {
return fmt.Errorf("hysteria2: temp dir: %w", err)
}
cfgPath := filepath.Join(workdir, "config.yaml")
if err := writeRuntimeConfig(cfgPath, profile); err != nil {
os.RemoveAll(workdir)
return err
}
runCtx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(runCtx, bin, "-c", cfgPath)
cmd.Dir = workdir
cmd.Stdout = e.stderr
cmd.Stderr = e.stderr
applySysProcAttr(cmd)
env := os.Environ()
for k, v := range profile.Env {
env = append(env, k+"="+v)
}
cmd.Env = env
if err := cmd.Start(); err != nil {
cancel()
os.RemoveAll(workdir)
return fmt.Errorf("hysteria2: start %s: %w", bin, err)
}
done := make(chan struct{})
e.cmd = cmd
e.cancel = cancel
e.done = done
e.workdir = workdir
e.profile = profile
e.running = true
go func() {
err := cmd.Wait()
if err != nil {
fmt.Fprintf(e.stderr, "hysteria2: process ended: %v\n", err)
}
e.mu.Lock()
e.cleanupLocked()
e.mu.Unlock()
close(done)
}()
e.mu.Unlock()
timer := time.NewTimer(900 * time.Millisecond)
defer timer.Stop()
var startErr error
select {
case <-done:
startErr = fmt.Errorf("hysteria2: process exited immediately; check URI/password and binary")
case <-ctx.Done():
_ = e.Stop()
startErr = ctx.Err()
case <-timer.C:
e.mu.Lock()
alive := e.running
e.mu.Unlock()
if !alive {
startErr = fmt.Errorf("hysteria2: process exited during startup")
}
}
e.mu.Lock()
return startErr
}
func (e *Engine) Stop() error {
e.mu.Lock()
defer e.mu.Unlock()
return e.stopLocked()
}
func (e *Engine) stopLocked() error {
if !e.running || e.cmd == nil {
return nil
}
done := e.done
if e.cancel != nil {
e.cancel()
}
proc := e.cmd.Process
e.mu.Unlock()
select {
case <-done:
case <-time.After(2 * time.Second):
if proc != nil {
_ = proc.Kill()
}
<-done
}
e.mu.Lock()
return nil
}
func (e *Engine) cleanupLocked() {
if e.workdir != "" {
_ = os.RemoveAll(e.workdir)
e.workdir = ""
}
e.cmd = nil
e.cancel = nil
e.running = false
}
func (e *Engine) Running() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.running
}
func (e *Engine) LocalHTTPProxy() (string, bool) {
e.mu.Lock()
defer e.mu.Unlock()
if !e.running {
return "", false
}
return e.profile.HTTPListenHostPort()
}
func (e *Engine) LocalSOCKSProxy() (string, bool) {
e.mu.Lock()
defer e.mu.Unlock()
if !e.running {
return "", false
}
return e.profile.SOCKSListenHostPort()
}
func writeRuntimeConfig(path string, profile config.Profile) error {
server, _, err := NormalizeShareLink(profile.Proxy)
if err != nil {
return err
}
socks := "127.0.0.1:1080"
httpListen := "127.0.0.1:1081"
if hp, ok := profile.SOCKSListenHostPort(); ok {
socks = hp
}
if hp, ok := profile.HTTPListenHostPort(); ok {
httpListen = hp
}
var b strings.Builder
b.WriteString("# generated by Navis — do not edit\n")
b.WriteString("server: " + yamlQuote(server) + "\n")
b.WriteString("socks5:\n")
b.WriteString(" listen: " + yamlQuote(socks) + "\n")
b.WriteString("http:\n")
b.WriteString(" listen: " + yamlQuote(httpListen) + "\n")
return os.WriteFile(path, []byte(b.String()), 0o600)
}
func yamlQuote(s string) string {
// Always quote — URIs and host:port can confuse YAML.
escaped := strings.ReplaceAll(s, `\`, `\\`)
escaped = strings.ReplaceAll(escaped, `"`, `\"`)
return `"` + escaped + `"`
}
@@ -0,0 +1,7 @@
//go:build !windows
package hysteria2
import "os/exec"
func applySysProcAttr(cmd *exec.Cmd) {}
@@ -0,0 +1,12 @@
//go:build windows
package hysteria2
import (
"os/exec"
"syscall"
)
func applySysProcAttr(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
}
+113
View File
@@ -0,0 +1,113 @@
package hysteria2
import (
"fmt"
"net/url"
"strings"
)
// NormalizeShareLink accepts hysteria2:// or hy2:// share links (or already-normalized URI).
// Returns a canonical hysteria2:// URI suitable for the official client's `server` field.
func NormalizeShareLink(raw string) (string, string, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", "", fmt.Errorf("empty hysteria2 URI")
}
remark := ""
if i := strings.IndexByte(raw, '#'); i >= 0 {
remark = strings.TrimSpace(raw[i+1:])
if u, err := url.QueryUnescape(remark); err == nil {
remark = u
}
raw = raw[:i]
}
lower := strings.ToLower(raw)
switch {
case strings.HasPrefix(lower, "hy2://"):
raw = "hysteria2://" + raw[len("hy2://"):]
case strings.HasPrefix(lower, "hysteria2://"):
// ok
default:
return "", "", fmt.Errorf("ожидалась ссылка hysteria2:// или hy2://")
}
u, err := url.Parse(raw)
if err != nil {
return "", "", fmt.Errorf("parse hysteria2 URI: %w", err)
}
if u.Host == "" {
return "", "", fmt.Errorf("hysteria2 URI missing host")
}
if u.Scheme != "hysteria2" {
u.Scheme = "hysteria2"
}
return u.String(), remark, nil
}
// Detect returns true if raw looks like a Hysteria 2 share link.
func Detect(raw string) bool {
lower := strings.ToLower(strings.TrimSpace(raw))
return strings.HasPrefix(lower, "hysteria2://") || strings.HasPrefix(lower, "hy2://")
}
// HostPort extracts host and a single port for reachability checks.
func HostPort(shareURI string) (host, port string, err error) {
normalized, _, err := NormalizeShareLink(shareURI)
if err != nil {
return "", "", err
}
u, err := url.Parse(normalized)
if err != nil {
return "", "", err
}
host = u.Hostname()
port = u.Port()
if port == "" {
// Multi-port may be in Hostname() for weird parses; Host may be "ex.com:443,5000-6000"
hostField := u.Host
if h, p, ok := splitMultiPortHost(hostField); ok {
return h, p, nil
}
port = "443"
} else if strings.Contains(port, ",") || strings.Contains(port, "-") {
port = firstPortToken(port)
}
if host == "" {
return "", "", fmt.Errorf("нет хоста")
}
if port == "" {
port = "443"
}
return host, port, nil
}
func splitMultiPortHost(hostField string) (host, port string, ok bool) {
// example.com:443,5000-6000
i := strings.LastIndex(hostField, ":")
if i < 0 {
return "", "", false
}
host = hostField[:i]
port = firstPortToken(hostField[i+1:])
if host == "" || port == "" {
return "", "", false
}
return host, port, true
}
func firstPortToken(ports string) string {
ports = strings.TrimSpace(ports)
if ports == "" {
return ""
}
part := ports
if i := strings.IndexByte(ports, ','); i >= 0 {
part = ports[:i]
}
if i := strings.IndexByte(part, '-'); i >= 0 {
part = part[:i]
}
return strings.TrimSpace(part)
}
+23
View File
@@ -0,0 +1,23 @@
package hysteria2
import "testing"
func TestNormalizeShareLink(t *testing.T) {
got, remark, err := NormalizeShareLink("hy2://secret@example.com:443/?sni=example.com&insecure=1#EU")
if err != nil {
t.Fatal(err)
}
if remark != "EU" {
t.Fatalf("remark=%q", remark)
}
if !Detect(got) {
t.Fatalf("not detected: %s", got)
}
host, port, err := HostPort(got)
if err != nil {
t.Fatal(err)
}
if host != "example.com" || port != "443" {
t.Fatalf("host=%q port=%q", host, port)
}
}