github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/sysproxy/sysproxy_darwin.go (about) 1 package sysproxy 2 3 import ( 4 "bufio" 5 "bytes" 6 "fmt" 7 "os/exec" 8 "strings" 9 10 "github.com/Asutorufa/yuhaiin/pkg/log" 11 ) 12 13 func SetSysProxy(httpHostname, httpPort, socks5Hostname, socks5Port string) { 14 if httpHostname == "" && socks5Hostname == "" { 15 return 16 } 17 18 if httpHostname != "" { 19 log.Debug("set http system proxy", "hostname", httpHostname, "port", httpPort) 20 } 21 if socks5Hostname != "" { 22 log.Debug("set socks5 system proxy", "hostname", socks5Hostname, "port", socks5Port) 23 } 24 25 networksetup := "/usr/sbin/networksetup" 26 27 services, err := getServices(networksetup) 28 if err != nil { 29 log.Error("set sysproxy failed", "err", err) 30 return 31 } 32 33 for _, service := range services { 34 if httpHostname != "" { 35 _ = exec.Command(networksetup, "-setwebproxystate", service, "on").Run() 36 _ = exec.Command(networksetup, "-setsecurewebproxystate", service, "on").Run() 37 _ = exec.Command(networksetup, "-setwebproxy", service, httpHostname, httpPort).Run() 38 _ = exec.Command(networksetup, "-setsecurewebproxy", service, httpHostname, httpPort).Run() 39 } 40 41 if socks5Hostname != "" { 42 _ = exec.Command(networksetup, "-setsocksfirewallproxystate", service, "on").Run() 43 _ = exec.Command(networksetup, "-setsocksfirewallproxy", service, socks5Hostname, socks5Port).Run() 44 } 45 46 _ = exec.Command(networksetup, append([]string{"-setproxybypassdomains", service}, priAddr...)...).Run() 47 } 48 49 } 50 51 func UnsetSysProxy() { 52 networksetup := "/usr/sbin/networksetup" 53 54 services, err := getServices(networksetup) 55 if err != nil { 56 log.Error("set sysproxy failed", "err", err) 57 return 58 } 59 60 for _, service := range services { 61 // _ = exec.Command(networksetup, "-setproxyautodiscovery", service, "off").Run() 62 _ = exec.Command(networksetup, "-setwebproxystate", service, "off").Run() 63 _ = exec.Command(networksetup, "-setsecurewebproxystate", service, "off").Run() 64 _ = exec.Command(networksetup, "-setsocksfirewallproxystate", service, "off").Run() 65 _ = exec.Command(networksetup, "-setproxybypassdomains", service, "").Run() 66 } 67 } 68 69 func getServices(networksetup string) ([]string, error) { 70 output, err := exec.Command(networksetup, "-listallnetworkservices").Output() 71 if err != nil { 72 return nil, err 73 } 74 75 r := bufio.NewScanner(bytes.NewReader(output)) 76 77 resp := make([]string, 0) 78 79 for r.Scan() { 80 if !strings.Contains(r.Text(), "*") { 81 resp = append(resp, r.Text()) 82 } 83 } 84 85 if len(resp) == 0 { 86 return nil, fmt.Errorf("all services is disabled") 87 } 88 89 return resp, nil 90 }