Files
navi/internal/protocols/naive/binary.go
T
M4andCursor 041cbb1250 Release 2.7.3.1: harden proxy recovery, updates and local API.
Restore orphaned system proxy after crash, require update SHA-256, add macOS /api auth token, fix UDP ping false positives, HTTPS-only subscriptions, and keep the UI responsive during connect.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-29 18:48:54 +03:00

278 lines
7.1 KiB
Go

package naive
import (
"archive/zip"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
)
const githubAPILatest = "https://api.github.com/repos/klzgrad/naiveproxy/releases/latest"
// ResolveBinary finds naive.exe/naive in binDir or PATH.
func ResolveBinary(binDir string) (string, error) {
name := "naive"
if runtime.GOOS == "windows" {
name = "naive.exe"
}
candidates := []string{
filepath.Join(binDir, name),
filepath.Join(binDir, "naiveproxy", name),
}
if exe, err := os.Executable(); err == nil {
candidates = append(candidates, filepath.Join(filepath.Dir(exe), name))
candidates = append(candidates, filepath.Join(filepath.Dir(exe), "bin", name))
}
for _, c := range candidates {
if st, err := os.Stat(c); err == nil && !st.IsDir() {
return c, nil
}
}
return "", fmt.Errorf("naive binary not found (looked in %s); run: vpnclient install-core", binDir)
}
// EnsureBinary downloads the official Windows/Linux/macOS 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
}
pattern, err := assetNameForPlatform()
if err != nil {
return "", err
}
fmt.Fprintf(os.Stderr, "downloading official naiveproxy release (%s)...\n", pattern)
assetName, url, err := findReleaseAsset(pattern)
if err != nil {
return "", err
}
archivePath := filepath.Join(binDir, assetName)
if err := downloadFile(archivePath, url); err != nil {
return "", err
}
defer os.Remove(archivePath)
if err := extractNaiveArchive(archivePath, binDir); err != nil {
return "", err
}
path, err := ResolveBinary(binDir)
if err != nil {
return "", err
}
clearQuarantine(path)
return path, nil
}
func clearQuarantine(path string) {
if runtime.GOOS != "darwin" {
return
}
_ = exec.Command("xattr", "-dr", "com.apple.quarantine", path).Run()
}
func assetNameForPlatform() (string, error) {
switch {
case runtime.GOOS == "windows" && runtime.GOARCH == "amd64":
return "naiveproxy-*-win-x64.zip", nil
case runtime.GOOS == "windows" && runtime.GOARCH == "arm64":
return "naiveproxy-*-win-arm64.zip", nil
case runtime.GOOS == "linux" && runtime.GOARCH == "amd64":
return "naiveproxy-*-linux-x64.zip", nil
case runtime.GOOS == "darwin" && runtime.GOARCH == "amd64":
// Newer releases use mac-x64-x64; older used mac-x64.
return "naiveproxy-*-mac-x64", nil
case runtime.GOOS == "darwin" && runtime.GOARCH == "arm64":
// Newer releases use mac-arm64-arm64; older used mac-arm64.
return "naiveproxy-*-mac-arm64", nil
default:
return "", fmt.Errorf("unsupported platform %s/%s for auto-download; place naive binary in bin/", 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(pattern 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", "vpnclient-go")
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
}
prefix := strings.Split(pattern, "*")[0]
needle := ""
if parts := strings.SplitN(pattern, "*", 2); len(parts) == 2 {
needle = parts[1]
}
var bestName, bestURL string
for _, a := range rel.Assets {
name := a.Name
if strings.Contains(name, "plugin") {
continue
}
if !strings.HasPrefix(name, prefix) {
continue
}
if needle != "" && !strings.Contains(name, needle) {
continue
}
// Prefer desktop archives over openwrt/apk.
if strings.HasSuffix(name, ".zip") || strings.HasSuffix(name, ".tar.xz") || strings.HasSuffix(name, ".txz") {
return name, a.BrowserDownloadURL, nil
}
if bestName == "" {
bestName, bestURL = name, a.BrowserDownloadURL
}
}
if bestName != "" {
return bestName, bestURL, nil
}
return "", "", fmt.Errorf("no asset matching %s in release %s", pattern, 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, io.LimitReader(resp.Body, 120<<20))
return err
}
func extractNaiveArchive(archivePath, destDir string) error {
lower := strings.ToLower(archivePath)
switch {
case strings.HasSuffix(lower, ".zip"):
return unzipNaive(archivePath, destDir)
case strings.HasSuffix(lower, ".tar.xz"), strings.HasSuffix(lower, ".txz"):
return extractTarXz(archivePath, destDir)
default:
return fmt.Errorf("unsupported archive: %s", filepath.Base(archivePath))
}
}
func extractTarXz(archivePath, destDir string) error {
tmp, err := os.MkdirTemp(destDir, "naive-extract-*")
if err != nil {
return err
}
defer os.RemoveAll(tmp)
cmd := exec.Command("tar", "-xJf", archivePath, "-C", tmp)
if out, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("tar extract: %w (%s)", err, strings.TrimSpace(string(out)))
}
want := "naive"
var found string
_ = filepath.Walk(tmp, func(path string, info os.FileInfo, err error) error {
if err != nil || info == nil || info.IsDir() {
return nil
}
if info.Name() == want {
found = path
}
return nil
})
if found == "" {
return fmt.Errorf("archive does not contain %s", want)
}
dest := filepath.Join(destDir, want)
in, err := os.Open(found)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return err
}
defer out.Close()
if _, err := io.Copy(out, in); err != nil {
return err
}
return nil
}
func unzipNaive(zipPath, destDir string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return err
}
defer r.Close()
want := "naive"
if runtime.GOOS == "windows" {
want = "naive.exe"
}
var found bool
for _, f := range r.File {
base := filepath.Base(f.Name)
if base != want {
continue
}
if err := extractFile(f, filepath.Join(destDir, want)); err != nil {
return err
}
found = true
break
}
if !found {
return fmt.Errorf("zip does not contain %s", want)
}
return nil
}
func extractFile(f *zip.File, dest string) error {
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, rc)
return err
}