3 Commits

Author SHA1 Message Date
Kain344 321c462f92 fix cicd
Build and Release / release (push) Failing after 41s
2026-05-24 10:22:47 +07:00
Kain344 d3ac27aa5d UPDATE: Enhance macOS support with new build steps, add admin relaunch functionality, and improve proxy management
Build and Release / release (push) Failing after 41s
2026-05-24 10:18:56 +07:00
Kain344 1abf0caee4 UPDATE: Add admin relaunch functionality for macOS and Linux, enhance README with new features and usage examples
Build and Release / release (push) Successful in 18s
2026-05-23 19:53:13 +07:00
14 changed files with 644 additions and 24 deletions
+34 -2
View File
@@ -20,13 +20,45 @@ jobs:
- name: Build for Windows - name: Build for Windows
run: GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" . run: GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" .
- name: Build for macOS Intel
run: |
GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 \
go build -trimpath -ldflags="-s -w" \
-o firefly-go-proxy-macos-amd64 .
- name: Build for macOS Apple Silicon
run: |
GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 \
go build -trimpath -ldflags="-s -w" \
-o firefly-go-proxy-macos-arm64 .
- name: Grant execute permissions - name: Grant execute permissions
run: | run: |
chmod +x ./script/release-uploader chmod +x ./script/release-uploader
- name: Upload release - name: Upload Windows release
env: env:
REPO_TOKEN: ${{ secrets.REPO_TOKEN }} REPO_TOKEN: ${{ secrets.REPO_TOKEN }}
run: script/release-uploader -token=$REPO_TOKEN -release-url="https://git.kain.io.vn/api/v1/repos/Firefly-Shelter/FireflyGo_Proxy/releases" -files="firefly-go-proxy.exe" run: |
script/release-uploader \
-token="$REPO_TOKEN" \
-release-url="https://git.kain.io.vn/api/v1/repos/Firefly-Shelter/FireflyGo_Proxy/releases" \
-files="firefly-go-proxy.exe"
- name: Upload macOS Intel release
env:
REPO_TOKEN: ${{ secrets.REPO_TOKEN }}
run: |
script/release-uploader \
-token="$REPO_TOKEN" \
-release-url="https://git.kain.io.vn/api/v1/repos/Firefly-Shelter/FireflyGo_Proxy/releases" \
-files="firefly-go-proxy-macos-amd64"
- name: Upload macOS ARM release
env:
REPO_TOKEN: ${{ secrets.REPO_TOKEN }}
run: |
script/release-uploader \
-token="$REPO_TOKEN" \
-release-url="https://git.kain.io.vn/api/v1/repos/Firefly-Shelter/FireflyGo_Proxy/releases" \
-files="firefly-go-proxy-macos-arm64"
+10
View File
@@ -10,6 +10,7 @@ A lightweight HTTP/HTTPS proxy server with domain redirection and request blocki
- Automatic certificate management - Automatic certificate management
- Cross-platform support (Windows, macOS, Linux) - Cross-platform support (Windows, macOS, Linux)
- System proxy configuration - System proxy configuration
- Automatic admin prompt on macOS/Linux for certificate/proxy setup
## Installation ## Installation
@@ -38,6 +39,7 @@ go build
- `-r`: Redirect target host (default: "127.0.0.1:21000") - `-r`: Redirect target host (default: "127.0.0.1:21000")
- `-b`: Comma-separated list of blocked ports - `-b`: Comma-separated list of blocked ports
- `-p`: Proxy listen port (default: auto)
- `-e`: Path to an executable to run with admin privileges - `-e`: Path to an executable to run with admin privileges
### Examples ### Examples
@@ -66,6 +68,14 @@ go build
./firefly-proxy.exe -e "/path/to/your/executable" //windows ./firefly-proxy.exe -e "/path/to/your/executable" //windows
``` ```
5. Start proxy on a specific port:
```bash
./firefly-proxy -p 8888 //linux|macos
./firefly-proxy.exe -p 8888 //windows
```
On macOS/Linux, if the proxy is not already running as root, it relaunches with an administrator prompt. On Linux, logs from the elevated process are written to `/tmp/firefly-go-proxy.log`; on macOS, elevated process output is discarded.
## How it works ## How it works
The proxy intercepts HTTP/HTTPS traffic and can: The proxy intercepts HTTP/HTTPS traffic and can:
+77
View File
@@ -0,0 +1,77 @@
//go:build darwin
// +build darwin
package main
import (
"fmt"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"syscall"
)
func relaunchWithAdminIfNeeded() (bool, error) {
if os.Geteuid() == 0 {
return false, nil
}
exePath, err := os.Executable()
if err != nil {
return false, fmt.Errorf("get executable path: %w", err)
}
workDir, err := os.Getwd()
if err != nil {
return false, fmt.Errorf("get working directory: %w", err)
}
wrapperPID := os.Getpid()
launcherPID := os.Getppid()
args := make([]string, 0, len(os.Args))
args = append(args, shellQuote(exePath))
for _, arg := range os.Args[1:] {
args = append(args, shellQuote(arg))
}
if !hasFlagArg("parent-pid") {
args = append(args, shellQuote("-parent-pid"), shellQuote(strconv.Itoa(wrapperPID)))
}
command := fmt.Sprintf(
"cd %s && %s > /dev/null 2>&1 &",
shellQuote(workDir),
strings.Join(args, " "),
)
script := fmt.Sprintf("do shell script %s with administrator privileges", appleScriptString(command))
if out, err := exec.Command("osascript", "-e", script).CombinedOutput(); err != nil {
return false, formatCommandError("relaunch proxy as admin", err, out)
}
waitForRelaunchedProxyShutdown(launcherPID)
return true, nil
}
func waitForRelaunchedProxyShutdown(launcherPID int) {
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
defer signal.Stop(stop)
select {
case <-stop:
case <-parentProcessDone(launcherPID):
}
}
func hasFlagArg(name string) bool {
for _, arg := range os.Args[1:] {
trimmed := strings.TrimLeft(arg, "-")
if trimmed == name || strings.HasPrefix(trimmed, name+"=") {
return true
}
}
return false
}
+73
View File
@@ -0,0 +1,73 @@
//go:build linux
// +build linux
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
func relaunchWithAdminIfNeeded() (bool, error) {
if os.Geteuid() == 0 {
return false, nil
}
exePath, err := os.Executable()
if err != nil {
return false, fmt.Errorf("get executable path: %w", err)
}
workDir, err := os.Getwd()
if err != nil {
return false, fmt.Errorf("get working directory: %w", err)
}
args := make([]string, 0, len(os.Args))
args = append(args, shellQuote(exePath))
for _, arg := range os.Args[1:] {
args = append(args, shellQuote(arg))
}
logPath := filepath.Join(os.TempDir(), "firefly-go-proxy.log")
command := fmt.Sprintf(
"cd %s && nohup %s >> %s 2>&1 &",
shellQuote(workDir),
strings.Join(args, " "),
shellQuote(logPath),
)
if pkexecPath, err := exec.LookPath("pkexec"); err == nil {
if out, err := exec.Command(pkexecPath, "sh", "-c", command).CombinedOutput(); err == nil {
return true, nil
} else if _, sudoErr := exec.LookPath("sudo"); sudoErr != nil {
return false, formatCommandError("relaunch proxy as admin with pkexec", err, out)
}
}
sudoPath, err := exec.LookPath("sudo")
if err != nil {
return false, errors.New("pkexec or sudo is required to relaunch with admin privileges")
}
if out, err := exec.Command(sudoPath, "sh", "-c", command).CombinedOutput(); err != nil {
return false, formatCommandError("relaunch proxy as admin with sudo", err, out)
}
return true, nil
}
func shellQuote(value string) string {
return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
}
func formatCommandError(action string, err error, out []byte) error {
msg := strings.TrimSpace(string(out))
if msg == "" {
return fmt.Errorf("%s: %w", action, err)
}
return fmt.Errorf("%s: %w: %s", action, err, msg)
}
+8
View File
@@ -0,0 +1,8 @@
//go:build !darwin && !linux
// +build !darwin,!linux
package main
func relaunchWithAdminIfNeeded() (bool, error) {
return false, nil
}
+65 -5
View File
@@ -19,14 +19,48 @@ import (
var ENV_CONFIG = make([]string, 0) var ENV_CONFIG = make([]string, 0)
func rawQueryFromRequestURI(requestURI string) string {
queryStart := strings.IndexByte(requestURI, '?')
if queryStart == -1 {
return ""
}
rawQuery := requestURI[queryStart+1:]
if fragmentStart := strings.IndexByte(rawQuery, '#'); fragmentStart != -1 {
rawQuery = rawQuery[:fragmentStart]
}
return rawQuery
}
func main() { func main() {
redirectHost := flag.String("r", "127.0.0.1:21000", "redirect target host") redirectHost := flag.String("r", "127.0.0.1:21000", "redirect target host")
blockedStr := flag.String("b", "", "comma separated list of blocked ports") blockedStr := flag.String("b", "", "comma separated list of blocked ports")
proxyPort := flag.Int("p", 0, "proxy listen port (default: auto)")
exePath := flag.String("e", "", "path to the executable") exePath := flag.String("e", "", "path to the executable")
parentPID := flag.Int("parent-pid", 0, "parent process id to watch")
flag.Parse() flag.Parse()
relaunched, err := relaunchWithAdminIfNeeded()
if err != nil {
zlog.Error().Err(err).Msg("Failed to relaunch with admin privileges")
return
}
if relaunched {
zlog.Info().Msg("Relaunched with admin privileges")
return
}
blockedPorts := parseBlockedPorts(*blockedStr) blockedPorts := parseBlockedPorts(*blockedStr)
port := findFreePort(blockedPorts) port := ""
if *proxyPort != 0 {
if *proxyPort < 1 || *proxyPort > 65535 {
zlog.Error().Int("port", *proxyPort).Msg("Invalid proxy port")
return
}
port = fmt.Sprint(*proxyPort)
} else {
port = findFreePort(blockedPorts)
}
if port == "-1" { if port == "-1" {
zlog.Error().Str("port", port).Msg("No free port available") zlog.Error().Str("port", port).Msg("No free port available")
return return
@@ -39,9 +73,12 @@ func main() {
} }
addr := ":" + port addr := ":" + port
proxyAddr := "127.0.0.1" proxyAddr := "127.0.0.1"
proxyEndpoint := proxyAddr + ":" + port
proxyEnabled := false proxyEnabled := false
stopProxyRefresh := func() {}
defer func() { defer func() {
stopProxyRefresh()
if r := recover(); r != nil { if r := recover(); r != nil {
zlog.Error(). zlog.Error().
Interface("panic", r). Interface("panic", r).
@@ -59,6 +96,7 @@ func main() {
return return
} }
proxyEnabled = true proxyEnabled = true
stopProxyRefresh = startProxyRefreshLoop(proxyAddr, port)
customCaMitm := &goproxy.ConnectAction{Action: goproxy.ConnectMitm, TLSConfig: goproxy.TLSConfigFromCA(cert)} customCaMitm := &goproxy.ConnectAction{Action: goproxy.ConnectMitm, TLSConfig: goproxy.TLSConfigFromCA(cert)}
var customAlwaysMitm goproxy.FuncHttpsHandler = func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) { var customAlwaysMitm goproxy.FuncHttpsHandler = func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
@@ -84,8 +122,13 @@ func main() {
proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
host := req.URL.Hostname() host := req.URL.Hostname()
path := req.URL.Path path := req.URL.Path
rawQuery := req.URL.RawQuery
if rawQuery == "" {
rawQuery = rawQueryFromRequestURI(req.RequestURI)
}
if matchDomain(host, AlwaysIgnoreDomains) { if matchDomain(host, AlwaysIgnoreDomains) {
zlog.Warn().Str("url", req.URL.String()).Msg("PASS URL")
return req, nil return req, nil
} }
@@ -101,21 +144,35 @@ func main() {
) )
} }
full := req.URL.String() full := req.URL.String()
if matchURL(full, ForceRedirectOnUrlContains) { if containsURL(full, ForceRedirectOnUrlContains) {
zlog.Info().Str("Url", full).Msg("Force redirect") zlog.Info().
Str("from_url", full).
Str("raw_query", rawQuery).
Msg("Force redirect")
req.URL.Scheme = "http" req.URL.Scheme = "http"
req.URL.Host = *redirectHost req.URL.Host = *redirectHost
req.URL.RawQuery = rawQuery
req.RequestURI = ""
zlog.Info().Str("to_url", req.URL.String()).Msg("Force redirected")
return req, nil return req, nil
} }
zlog.Info().Str("Host", host).Msg("Redirect domain") zlog.Info().
Str("host", host).
Str("from_url", full).
Str("raw_query", rawQuery).
Msg("Redirect domain")
req.URL.Scheme = "http" req.URL.Scheme = "http"
req.URL.Host = *redirectHost req.URL.Host = *redirectHost
req.URL.RawQuery = rawQuery
req.RequestURI = ""
zlog.Info().Str("to_url", req.URL.String()).Msg("Redirected domain")
return req, nil return req, nil
} }
zlog.Warn().Str("url", req.URL.String()).Msg("PASS URL")
return req, nil return req, nil
}) })
@@ -131,6 +188,7 @@ func main() {
stop := make(chan os.Signal, 1) stop := make(chan os.Signal, 1)
serverErr := make(chan error, 1) serverErr := make(chan error, 1)
parentDone := parentProcessDone(*parentPID)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
if *exePath != "" && exists(*exePath) { if *exePath != "" && exists(*exePath) {
go func() { go func() {
@@ -145,7 +203,7 @@ func main() {
} }
go func() { go func() {
zlog.Info(). zlog.Info().
Str("ProxyAddress", proxyAddr). Str("ProxyAddress", proxyEndpoint).
Str("RedirectTo", *redirectHost). Str("RedirectTo", *redirectHost).
Str("BlockedPorts", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(blockedPorts)), ","), "[]")). Str("BlockedPorts", strings.Trim(strings.Join(strings.Fields(fmt.Sprint(blockedPorts)), ","), "[]")).
Str("ExePath", *exePath). Str("ExePath", *exePath).
@@ -159,6 +217,8 @@ func main() {
case <-stop: case <-stop:
case err := <-serverErr: case err := <-serverErr:
zlog.Error().Err(err).Msg("ListenAndServe failed") zlog.Error().Err(err).Msg("ListenAndServe failed")
case <-parentDone:
zlog.Info().Int("ParentPID", *parentPID).Msg("Parent process exited")
} }
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+36
View File
@@ -0,0 +1,36 @@
//go:build darwin
// +build darwin
package main
import (
"syscall"
"time"
)
func parentProcessDone(pid int) <-chan struct{} {
if pid <= 1 {
return nil
}
done := make(chan struct{})
go func() {
defer close(done)
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for range ticker.C {
if !processExists(pid) {
return
}
}
}()
return done
}
func processExists(pid int) bool {
err := syscall.Kill(pid, 0)
return err == nil || err == syscall.EPERM
}
+8
View File
@@ -0,0 +1,8 @@
//go:build !darwin
// +build !darwin
package main
func parentProcessDone(pid int) <-chan struct{} {
return nil
}
+42
View File
@@ -0,0 +1,42 @@
//go:build darwin
// +build darwin
package main
import (
"sync"
"time"
zlog "github.com/rs/zerolog/log"
)
func startProxyRefreshLoop(host string, port string) func() {
done := make(chan struct{})
stopped := make(chan struct{})
var once sync.Once
go func() {
defer close(stopped)
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-ticker.C:
if err := setProxy(true, host, port); err != nil {
zlog.Error().Err(err).Msg("Failed to refresh macOS proxy services")
}
}
}
}()
return func() {
once.Do(func() {
close(done)
<-stopped
})
}
}
+8
View File
@@ -0,0 +1,8 @@
//go:build !darwin
// +build !darwin
package main
func startProxyRefreshLoop(host string, port string) func() {
return func() {}
}
+1 -1
View File
@@ -1,4 +1,4 @@
# Changelog # Changelog
### UPDATE ### UPDATE
- Go 1.26.1, latest lib - Fix bug in macos
+2 -2
View File
@@ -1,5 +1,5 @@
{ {
"tag": "1.1-02", "tag": "1.2-01",
"title": "PreBuild Version 1.1 - 02" "title": "PreBuild Version 1.2 - 01"
} }
+268 -11
View File
@@ -7,6 +7,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"os/exec" "os/exec"
"strconv"
"strings" "strings"
"sync" "sync"
) )
@@ -26,6 +27,7 @@ var darwinProxyState = struct {
sync.Mutex sync.Mutex
captured bool captured bool
previous map[string]darwinProxySettings previous map[string]darwinProxySettings
applied map[string]struct{}
}{} }{}
func enabledNetworkServices() ([]string, error) { func enabledNetworkServices() ([]string, error) {
@@ -50,6 +52,171 @@ func enabledNetworkServices() ([]string, error) {
return services, nil return services, nil
} }
func proxyNetworkServices() ([]string, error) {
service, defaultErr := defaultNetworkService()
if defaultErr == nil && service != "" {
return []string{service}, nil
}
services, activeErr := activeNetworkServices()
if activeErr == nil && len(services) > 0 {
return services, nil
}
if defaultErr != nil || activeErr != nil {
return nil, errors.Join(defaultErr, activeErr)
}
return nil, fmt.Errorf("no active network services found")
}
func defaultNetworkService() (string, error) {
device, err := defaultNetworkDevice()
if err != nil {
return "", err
}
servicesByDevice, err := networkServicesByDevice()
if err != nil {
return "", err
}
service := servicesByDevice[device]
if service == "" {
return "", fmt.Errorf("network service for default device %s not found", device)
}
return service, nil
}
func defaultNetworkDevice() (string, error) {
out, err := exec.Command("route", "-n", "get", "default").CombinedOutput()
if err != nil {
return "", formatCommandError("get default network route", err, out)
}
for _, line := range strings.Split(string(out), "\n") {
key, value, ok := strings.Cut(line, ":")
if ok && strings.TrimSpace(key) == "interface" {
device := strings.TrimSpace(value)
if device != "" {
return device, nil
}
}
}
return "", fmt.Errorf("default network interface not found")
}
func networkServicesByDevice() (map[string]string, error) {
out, err := exec.Command("networksetup", "-listnetworkserviceorder").CombinedOutput()
if err != nil {
return nil, formatCommandError("list network service order", err, out)
}
services := make(map[string]string)
currentService := ""
for _, line := range strings.Split(string(out), "\n") {
line = strings.TrimSpace(line)
if service, ok := parseNetworkServiceOrderName(line); ok {
currentService = service
continue
}
if currentService == "" {
continue
}
if device, ok := parseNetworkServiceOrderDevice(line); ok {
services[device] = currentService
currentService = ""
}
}
if len(services) == 0 {
return nil, fmt.Errorf("no network service devices found")
}
return services, nil
}
func parseNetworkServiceOrderName(line string) (string, bool) {
if !strings.HasPrefix(line, "(") {
return "", false
}
end := strings.Index(line, ")")
if end <= 1 {
return "", false
}
if _, err := strconv.Atoi(line[1:end]); err != nil {
return "", false
}
service := strings.TrimSpace(line[end+1:])
return service, service != ""
}
func parseNetworkServiceOrderDevice(line string) (string, bool) {
_, value, ok := strings.Cut(line, "Device:")
if !ok {
return "", false
}
value = strings.TrimSpace(value)
if idx := strings.IndexAny(value, ",)"); idx != -1 {
value = value[:idx]
}
device := strings.TrimSpace(value)
return device, device != ""
}
func activeNetworkServices() ([]string, error) {
services, err := enabledNetworkServices()
if err != nil {
return nil, err
}
active := make([]string, 0, len(services))
for _, service := range services {
ok, err := isNetworkServiceActive(service)
if err != nil {
continue
}
if ok {
active = append(active, service)
}
}
if len(active) == 0 {
return nil, fmt.Errorf("no active network services found")
}
return active, nil
}
func isNetworkServiceActive(service string) (bool, error) {
out, err := exec.Command("networksetup", "-getinfo", service).CombinedOutput()
if err != nil {
return false, formatCommandError("get network service info "+service, err, out)
}
for _, line := range strings.Split(string(out), "\n") {
key, value, ok := strings.Cut(line, ":")
if !ok {
continue
}
key = strings.TrimSpace(key)
if key != "IP address" && key != "IPv6 IP address" {
continue
}
value = strings.TrimSpace(value)
if value != "" && !strings.EqualFold(value, "none") {
return true, nil
}
}
return false, nil
}
func getProxySettings(service string) (darwinProxySettings, error) { func getProxySettings(service string) (darwinProxySettings, error) {
web, webErr := getProxyEndpoint("-getwebproxy", service) web, webErr := getProxyEndpoint("-getwebproxy", service)
secure, secureErr := getProxyEndpoint("-getsecurewebproxy", service) secure, secureErr := getProxyEndpoint("-getsecurewebproxy", service)
@@ -166,12 +333,86 @@ func captureProxySettings(services []string) (map[string]darwinProxySettings, er
return settings, nil return settings, nil
} }
func setProxy(enable bool, host string, port string) error { func captureMissingProxySettings(services []string) error {
services, err := enabledNetworkServices() missing := make([]string, 0, len(services))
for _, service := range services {
if _, ok := darwinProxyState.previous[service]; !ok {
missing = append(missing, service)
}
}
if len(missing) == 0 {
return nil
}
settings, err := captureProxySettings(missing)
if err != nil { if err != nil {
return err return err
} }
for service, setting := range settings {
darwinProxyState.previous[service] = setting
}
return nil
}
func serviceSet(services []string) map[string]struct{} {
set := make(map[string]struct{}, len(services))
for _, service := range services {
set[service] = struct{}{}
}
return set
}
func appliedServicesNotIn(selected map[string]struct{}) []string {
services := make([]string, 0, len(darwinProxyState.applied))
for service := range darwinProxyState.applied {
if _, ok := selected[service]; !ok {
services = append(services, service)
}
}
return services
}
func appliedServices() []string {
services := make([]string, 0, len(darwinProxyState.applied))
for service := range darwinProxyState.applied {
services = append(services, service)
}
return services
}
func proxySettingsForServices(settings map[string]darwinProxySettings, services []string) map[string]darwinProxySettings {
filtered := make(map[string]darwinProxySettings, len(services))
for _, service := range services {
if setting, ok := settings[service]; ok {
filtered[service] = setting
}
}
return filtered
}
func resetDarwinProxyState() {
darwinProxyState.previous = nil
darwinProxyState.applied = nil
darwinProxyState.captured = false
}
func restoreAppliedProxySettings() error {
if len(darwinProxyState.applied) == 0 {
return nil
}
err := restoreProxySettings(proxySettingsForServices(
darwinProxyState.previous,
appliedServices(),
))
if err == nil {
darwinProxyState.applied = nil
}
return err
}
func setProxy(enable bool, host string, port string) error {
darwinProxyState.Lock() darwinProxyState.Lock()
defer darwinProxyState.Unlock() defer darwinProxyState.Unlock()
@@ -180,32 +421,48 @@ func setProxy(enable bool, host string, port string) error {
return fmt.Errorf("host and port are required to enable proxy") return fmt.Errorf("host and port are required to enable proxy")
} }
if !darwinProxyState.captured { services, err := proxyNetworkServices()
settings, err := captureProxySettings(services)
if err != nil { if err != nil {
return errors.Join(err, restoreAppliedProxySettings())
}
if darwinProxyState.previous == nil {
darwinProxyState.previous = make(map[string]darwinProxySettings)
}
if err := captureMissingProxySettings(services); err != nil {
return err return err
} }
darwinProxyState.previous = settings
darwinProxyState.captured = true darwinProxyState.captured = true
}
if err := setProxyForServices(services, host, port); err != nil { if err := setProxyForServices(services, host, port); err != nil {
restoreErr := restoreProxySettings(darwinProxyState.previous) restoreErr := restoreProxySettings(darwinProxyState.previous)
darwinProxyState.previous = nil resetDarwinProxyState()
darwinProxyState.captured = false
return errors.Join(err, restoreErr) return errors.Join(err, restoreErr)
} }
return nil
selected := serviceSet(services)
removed := appliedServicesNotIn(selected)
restoreErr := restoreProxySettings(proxySettingsForServices(darwinProxyState.previous, removed))
if restoreErr != nil {
for _, service := range removed {
selected[service] = struct{}{}
}
}
darwinProxyState.applied = selected
return restoreErr
} }
if darwinProxyState.captured { if darwinProxyState.captured {
err := restoreProxySettings(darwinProxyState.previous) err := restoreProxySettings(darwinProxyState.previous)
if err == nil { if err == nil {
darwinProxyState.previous = nil resetDarwinProxyState()
darwinProxyState.captured = false
} }
return err return err
} }
services, err := enabledNetworkServices()
if err != nil {
return err
}
return disableProxyForServices(services) return disableProxyForServices(services)
} }
+9
View File
@@ -26,6 +26,15 @@ func matchURL(url string, list []string) bool {
return false return false
} }
func containsURL(url string, list []string) bool {
for _, u := range list {
if strings.Contains(url, u) {
return true
}
}
return false
}
func cleanHost(h string) string { func cleanHost(h string) string {
if idx := strings.LastIndex(h, ":"); idx != -1 { if idx := strings.LastIndex(h, ":"); idx != -1 {
return h[:idx] return h[:idx]