pax_global_header00006660000000000000000000000064143107554610014520gustar00rootroot0000000000000052 comment=7343ac506112d7cc22a71efe6897eea8eb2b3d6a go-ieproxy-0.0.9/000077500000000000000000000000001431075546100136305ustar00rootroot00000000000000go-ieproxy-0.0.9/.github/000077500000000000000000000000001431075546100151705ustar00rootroot00000000000000go-ieproxy-0.0.9/.github/FUNDING.yml000066400000000000000000000013151431075546100170050ustar00rootroot00000000000000# These are supported funding model platforms github: mattn # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] go-ieproxy-0.0.9/.github/workflows/000077500000000000000000000000001431075546100172255ustar00rootroot00000000000000go-ieproxy-0.0.9/.github/workflows/.editorconfig000066400000000000000000000000301431075546100216730ustar00rootroot00000000000000[*.yml] indent_size = 2 go-ieproxy-0.0.9/.github/workflows/CI.yml000066400000000000000000000010361431075546100202430ustar00rootroot00000000000000name: CI on: push: branches: [master] pull_request: jobs: run-tests: name: Run test cases runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] go: [1.17, 1.16] cgo_enabled: [0, 1] steps: - uses: actions/checkout@v2 - name: Set up Go uses: actions/setup-go@v2 with: go-version: ${{ matrix.go }} - name: Run tests run: go test -v ./... env: CGO_ENABLED: ${{ matrix.go }} go-ieproxy-0.0.9/.gitignore000066400000000000000000000000071431075546100156150ustar00rootroot00000000000000.idea/*go-ieproxy-0.0.9/LICENSE000066400000000000000000000021421431075546100146340ustar00rootroot00000000000000MIT License Copyright (c) 2014 mattn Copyright (c) 2017 oliverpool Copyright (c) 2019 Adele Reed Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. go-ieproxy-0.0.9/README.md000066400000000000000000000044171431075546100151150ustar00rootroot00000000000000# ieproxy Go package to detect the proxy settings on Windows platform, and MacOS. On Windows, the settings are initially attempted to be read from the [`WinHttpGetIEProxyConfigForCurrentUser` DLL call](https://docs.microsoft.com/en-us/windows/desktop/api/winhttp/nf-winhttp-winhttpgetieproxyconfigforcurrentuser), but falls back to the registry (`CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings`) in the event the DLL call fails. On MacOS, the settings are read from [`CFNetworkCopySystemProxySettings` method of CFNetwork](https://developer.apple.com/documentation/cfnetwork/1426754-cfnetworkcopysystemproxysettings?language=objc). For more information, take a look at the [documentation](https://godoc.org/github.com/mattn/go-ieproxy) ## Methods You can either obtain a `net/http` compatible proxy function using `ieproxy.GetProxyFunc()`, set environment variables using `ieproxy.OverrideEnvWithStaticProxy()` (though no automatic configuration is available this way), or obtain the proxy settings via `ieproxy.GetConf()`. | Method | Supported configuration options: | |----------------------------------------|-----------------------------------------------| | `ieproxy.GetProxyFunc()` | Static, Specified script, and fully automatic | | `ieproxy.OverrideEnvWithStaticProxy()` | Static | | `ieproxy.GetConf()` | Depends on how you use it | ## Examples ### Using GetProxyFunc(): ```go func init() { http.DefaultTransport.(*http.Transport).Proxy = ieproxy.GetProxyFunc() } ``` GetProxyFunc acts as a middleman between `net/http` and `mattn/go-ieproxy` in order to select the correct proxy configuration based off the details supplied in the config. ### Using OverrideEnvWithStaticProxy(): ```go func init() { ieproxy.OverrideEnvWithStaticProxy() http.DefaultTransport.(*http.Transport).Proxy = http.ProxyFromEnvironment } ``` OverrideEnvWithStaticProxy overrides the relevant environment variables (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`) with the **static, manually configured** proxy details typically found in the registry. ### Using GetConf(): ```go func main() { conf := ieproxy.GetConf() //Handle proxies how you want to. } ``` go-ieproxy-0.0.9/autoload/000077500000000000000000000000001431075546100154405ustar00rootroot00000000000000go-ieproxy-0.0.9/autoload/windows.go000066400000000000000000000006021431075546100174570ustar00rootroot00000000000000// Package autoload automatically calls OverrideEnvWithStaticProxy, // which writes new values to the `http_proxy`, `https_proxy` and `no_proxy` environment variables. // The values are taken from the Windows Regedit // import _ "github.com/mattn/go-ieproxy/autoload" package autoload import ieproxy "github.com/mattn/go-ieproxy" func init() { ieproxy.OverrideEnvWithStaticProxy() } go-ieproxy-0.0.9/darwin_test.go000066400000000000000000000050261431075546100165050ustar00rootroot00000000000000//go:build darwin // +build darwin package ieproxy import ( "net/http" "reflect" "testing" ) func TestPacfile(t *testing.T) { listener, err := listenAndServeWithClose("127.0.0.1:0", http.FileServer(http.Dir("pacfile_examples"))) serverBase := "http://" + listener.Addr().String() + "/" if err != nil { t.Fatal(err) } // test inactive proxy proxy := ProxyScriptConf{ Active: false, PreConfiguredURL: serverBase + "simple.pac", } out := proxy.FindProxyForURL("http://google.com") if out != "" { t.Error("Got: ", out, "Expected: ", "") } proxy.Active = true pacSet := []struct { pacfile string url string expected string }{ { serverBase + "direct.pac", "http://google.com", "", }, { serverBase + "404.pac", "http://google.com", "", }, { serverBase + "simple.pac", "http://google.com", "127.0.0.1:8", }, { serverBase + "multiple.pac", "http://google.com", "127.0.0.1:8081", }, { serverBase + "except.pac", "http://imgur.com", "localhost:9999", }, { serverBase + "except.pac", "http://example.com", "", }, { "", "http://example.com", "", }, { " ", "http://example.com", "", }, { "wrong_format", "http://example.com", "", }, } for _, p := range pacSet { proxy.PreConfiguredURL = p.pacfile out := proxy.FindProxyForURL(p.url) if out != p.expected { t.Error("Got: ", out, "Expected: ", p.expected) } } listener.Close() } var multipleMap map[string]string func init() { multipleMap = make(map[string]string) multipleMap["http"] = "127.0.0.1" multipleMap["ftp"] = "128" } func TestOverrideEnv(t *testing.T) { var callStack []string pseudoSetEnv := func(key, value string) error { if value != "" { callStack = append(callStack, key) callStack = append(callStack, value) } return nil } overrideSet := []struct { in ProxyConf callStack []string }{ { callStack: []string{}, }, { in: ProxyConf{ Static: StaticProxyConf{ Active: true, Protocols: multipleMap, }, }, callStack: []string{"http_proxy", "127.0.0.1"}, }, { in: ProxyConf{ Static: StaticProxyConf{ Active: true, NoProxy: "example.com,microsoft.com", }, }, callStack: []string{"no_proxy", "example.com,microsoft.com"}, }, } for _, o := range overrideSet { callStack = []string{} overrideEnvWithStaticProxy(o.in, pseudoSetEnv) if !reflect.DeepEqual(o.callStack, callStack) { t.Error("Got: ", callStack, "Expected: ", o.callStack) } } } go-ieproxy-0.0.9/example_test.go000066400000000000000000000013521431075546100166520ustar00rootroot00000000000000package ieproxy import ( "fmt" "net/http" "os" ) func init() { OverrideEnvWithStaticProxy() http.DefaultTransport.(*http.Transport).Proxy = http.ProxyFromEnvironment } func Example() { fmt.Println("== Proxy configuration ==") for _, name := range []string{"http_proxy", "https_proxy", "no_proxy"} { fmt.Println(name + ": " + os.Getenv(name)) } fmt.Println("== Proxy test ==") req, err := http.NewRequest("GET", "https://golang.org/", nil) if err != nil { panic(err) } url, err := http.DefaultTransport.(*http.Transport).Proxy(req) if err != nil { panic(err) } if url != nil { fmt.Println("PROXY " + url.String()) } else { fmt.Println("DIRECT") } // Coming output: == Proxy configuration == // http_proxy: ... } go-ieproxy-0.0.9/go.mod000066400000000000000000000002431431075546100147350ustar00rootroot00000000000000module github.com/mattn/go-ieproxy go 1.14 require ( golang.org/x/net v0.0.0-20220630215102-69896b714898 golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e ) go-ieproxy-0.0.9/go.sum000066400000000000000000000017461431075546100147730ustar00rootroot00000000000000golang.org/x/net v0.0.0-20220630215102-69896b714898 h1:K7wO6V1IrczY9QOQ2WkVpw4JQSwCd52UsxVEirZUfiw= golang.org/x/net v0.0.0-20220630215102-69896b714898/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e h1:CsOuNlbOuf0mzxJIefr6Q4uAUetRUwZE4qt7VfzP+xo= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= go-ieproxy-0.0.9/ieproxy.go000066400000000000000000000034351431075546100156630ustar00rootroot00000000000000// Package ieproxy is a utility to retrieve the proxy parameters (especially of Internet Explorer on windows) // // On windows, it gathers the parameters from the registry (regedit), while it uses env variable on other platforms package ieproxy import "os" // ProxyConf gathers the configuration for proxy type ProxyConf struct { Static StaticProxyConf // static configuration Automatic ProxyScriptConf // script configuration } // StaticProxyConf contains the configuration for static proxy type StaticProxyConf struct { // Is the proxy active? Active bool // Proxy address for each scheme (http, https) // "" (empty string) is the fallback proxy Protocols map[string]string // Addresses not to be browsed via the proxy (comma-separated, linux-like) NoProxy string } // ProxyScriptConf contains the configuration for automatic proxy type ProxyScriptConf struct { // Is the proxy active? Active bool // PreConfiguredURL of the .pac file. // If this is empty and Active is true, auto-configuration should be assumed. PreConfiguredURL string } // GetConf retrieves the proxy configuration from the Windows Regedit func GetConf() ProxyConf { return getConf() } // ReloadConf reloads the proxy configuration func ReloadConf() ProxyConf { return reloadConf() } // OverrideEnvWithStaticProxy writes new values to the // `http_proxy`, `https_proxy` and `no_proxy` environment variables. // The values are taken from the Windows Regedit (should be called in `init()` function - see example) func OverrideEnvWithStaticProxy() { overrideEnvWithStaticProxy(GetConf(), os.Setenv) } // FindProxyForURL computes the proxy for a given URL according to the pac file func (psc *ProxyScriptConf) FindProxyForURL(URL string) string { return psc.findProxyForURL(URL) } type envSetter func(string, string) error go-ieproxy-0.0.9/ieproxy_darwin.go000066400000000000000000000103241431075546100172220ustar00rootroot00000000000000package ieproxy /* #cgo LDFLAGS: -framework CoreFoundation #cgo LDFLAGS: -framework CFNetwork #include #include */ import "C" import ( "fmt" "strings" "sync" "unsafe" ) var once sync.Once var darwinProxyConf ProxyConf // GetConf retrieves the proxy configuration from the Windows Regedit func getConf() ProxyConf { once.Do(writeConf) return darwinProxyConf } // reloadConf forces a reload of the proxy configuration. func reloadConf() ProxyConf { writeConf() return getConf() } func cfStringGetGoString(cfStr C.CFStringRef) string { retCString := (*C.char)(C.calloc(C.ulong(uint(128)), 1)) defer C.free(unsafe.Pointer(retCString)) C.CFStringGetCString(cfStr, retCString, C.long(128), C.kCFStringEncodingUTF8) return C.GoString(retCString) } func cfNumberGetGoInt(cfNum C.CFNumberRef) int { ret := 0 C.CFNumberGetValue(cfNum, C.kCFNumberIntType, unsafe.Pointer(&ret)) return ret } func cfArrayGetGoStrings(cfArray C.CFArrayRef) []string { var ret []string for i := 0; i < int(C.CFArrayGetCount(cfArray)); i++ { cfStr := C.CFStringRef(C.CFArrayGetValueAtIndex(cfArray, C.long(i))) if unsafe.Pointer(cfStr) != C.NULL { ret = append(ret, cfStringGetGoString(cfStr)) } } return ret } func writeConf() { cfDictProxy := C.CFDictionaryRef(C.CFNetworkCopySystemProxySettings()) defer C.CFRelease(C.CFTypeRef(cfDictProxy)) darwinProxyConf = ProxyConf{} cfNumHttpEnable := C.CFNumberRef(C.CFDictionaryGetValue(cfDictProxy, unsafe.Pointer(C.kCFNetworkProxiesHTTPEnable))) if unsafe.Pointer(cfNumHttpEnable) != C.NULL && cfNumberGetGoInt(cfNumHttpEnable) > 0 { darwinProxyConf.Static.Active = true if darwinProxyConf.Static.Protocols == nil { darwinProxyConf.Static.Protocols = make(map[string]string) } httpHost := C.CFStringRef(C.CFDictionaryGetValue(cfDictProxy, unsafe.Pointer(C.kCFNetworkProxiesHTTPProxy))) httpPort := C.CFNumberRef(C.CFDictionaryGetValue(cfDictProxy, unsafe.Pointer(C.kCFNetworkProxiesHTTPPort))) httpProxy := fmt.Sprintf("%s:%d", cfStringGetGoString(httpHost), cfNumberGetGoInt(httpPort)) darwinProxyConf.Static.Protocols["http"] = httpProxy } cfNumHttpsEnable := C.CFNumberRef(C.CFDictionaryGetValue(cfDictProxy, unsafe.Pointer(C.kCFNetworkProxiesHTTPSEnable))) if unsafe.Pointer(cfNumHttpsEnable) != C.NULL && cfNumberGetGoInt(cfNumHttpsEnable) > 0 { darwinProxyConf.Static.Active = true if darwinProxyConf.Static.Protocols == nil { darwinProxyConf.Static.Protocols = make(map[string]string) } httpsHost := C.CFStringRef(C.CFDictionaryGetValue(cfDictProxy, unsafe.Pointer(C.kCFNetworkProxiesHTTPSProxy))) httpsPort := C.CFNumberRef(C.CFDictionaryGetValue(cfDictProxy, unsafe.Pointer(C.kCFNetworkProxiesHTTPSPort))) httpProxy := fmt.Sprintf("%s:%d", cfStringGetGoString(httpsHost), cfNumberGetGoInt(httpsPort)) darwinProxyConf.Static.Protocols["https"] = httpProxy } if darwinProxyConf.Static.Active { cfArrayExceptionList := C.CFArrayRef(C.CFDictionaryGetValue(cfDictProxy, unsafe.Pointer(C.kCFNetworkProxiesExceptionsList))) if unsafe.Pointer(cfArrayExceptionList) != C.NULL { exceptionList := cfArrayGetGoStrings(cfArrayExceptionList) darwinProxyConf.Static.NoProxy = strings.Join(exceptionList, ",") } } cfNumPacEnable := C.CFNumberRef(C.CFDictionaryGetValue(cfDictProxy, unsafe.Pointer(C.kCFNetworkProxiesProxyAutoConfigEnable))) if unsafe.Pointer(cfNumPacEnable) != C.NULL && cfNumberGetGoInt(cfNumPacEnable) > 0 { cfStringPac := C.CFStringRef(C.CFDictionaryGetValue(cfDictProxy, unsafe.Pointer(C.kCFNetworkProxiesProxyAutoConfigURLString))) if unsafe.Pointer(cfStringPac) != C.NULL { pac := cfStringGetGoString(cfStringPac) darwinProxyConf.Automatic.PreConfiguredURL = pac darwinProxyConf.Automatic.Active = true } } } // OverrideEnvWithStaticProxy writes new values to the // http_proxy, https_proxy and no_proxy environment variables. // The values are taken from the MacOS System Preferences. func overrideEnvWithStaticProxy(conf ProxyConf, setenv envSetter) { if conf.Static.Active { for _, scheme := range []string{"http", "https"} { url := conf.Static.Protocols[scheme] if url != "" { setenv(scheme+"_proxy", url) } } if conf.Static.NoProxy != "" { setenv("no_proxy", conf.Static.NoProxy) } } } go-ieproxy-0.0.9/ieproxy_unix.go000066400000000000000000000004041431075546100167170ustar00rootroot00000000000000//go:build (!windows && !darwin) || !cgo // +build !windows,!darwin !cgo package ieproxy func getConf() ProxyConf { return ProxyConf{} } func reloadConf() ProxyConf { return getConf() } func overrideEnvWithStaticProxy(pc ProxyConf, setenv envSetter) { } go-ieproxy-0.0.9/ieproxy_windows.go000066400000000000000000000135751431075546100174430ustar00rootroot00000000000000package ieproxy import ( "strings" "sync" "unsafe" "golang.org/x/sys/windows/registry" ) type regeditValues struct { ProxyServer string ProxyOverride string ProxyEnable uint64 AutoConfigURL string } var once sync.Once var windowsProxyConf ProxyConf // GetConf retrieves the proxy configuration from the Windows Regedit func getConf() ProxyConf { once.Do(writeConf) return windowsProxyConf } // reloadConf forces a reload of the proxy configuration from the Windows registry func reloadConf() ProxyConf { writeConf() return getConf() } func writeConf() { proxy := "" proxyByPass := "" autoConfigUrl := "" autoDetect := false // Try from IE first. if ieCfg, err := getUserConfigFromWindowsSyscall(); err == nil { defer globalFreeWrapper(ieCfg.lpszProxy) defer globalFreeWrapper(ieCfg.lpszProxyBypass) defer globalFreeWrapper(ieCfg.lpszAutoConfigUrl) proxy = StringFromUTF16Ptr(ieCfg.lpszProxy) proxyByPass = StringFromUTF16Ptr(ieCfg.lpszProxyBypass) autoConfigUrl = StringFromUTF16Ptr(ieCfg.lpszAutoConfigUrl) autoDetect = ieCfg.fAutoDetect } if proxy == "" && !autoDetect { // Try WinHTTP default proxy. if defaultCfg, err := getDefaultProxyConfiguration(); err == nil { defer globalFreeWrapper(defaultCfg.lpszProxy) defer globalFreeWrapper(defaultCfg.lpszProxyBypass) // Always set both of these (they are a pair, it doesn't make sense to set one here and keep the value of the other from above) proxy = StringFromUTF16Ptr(defaultCfg.lpszProxy) proxyByPass = StringFromUTF16Ptr(defaultCfg.lpszProxyBypass) } } if proxy == "" && !autoDetect { // Fall back to IE registry or manual detection if nothing is found there.. regedit, _ := readRegedit() // If the syscall fails, backup to manual detection. windowsProxyConf = parseRegedit(regedit) return } // Setting the proxy settings. windowsProxyConf = ProxyConf{ Static: StaticProxyConf{ Active: len(proxy) > 0, }, Automatic: ProxyScriptConf{ Active: len(autoConfigUrl) > 0 || autoDetect, }, } if windowsProxyConf.Static.Active { protocol := make(map[string]string) for _, s := range strings.Split(proxy, ";") { s = strings.TrimSpace(s) if s == "" { continue } pair := strings.SplitN(s, "=", 2) if len(pair) > 1 { protocol[pair[0]] = pair[1] } else { protocol[""] = pair[0] } } windowsProxyConf.Static.Protocols = protocol if len(proxyByPass) > 0 { windowsProxyConf.Static.NoProxy = strings.Replace(proxyByPass, ";", ",", -1) } } if windowsProxyConf.Automatic.Active { windowsProxyConf.Automatic.PreConfiguredURL = autoConfigUrl } } func getUserConfigFromWindowsSyscall() (*tWINHTTP_CURRENT_USER_IE_PROXY_CONFIG, error) { if err := winHttpGetIEProxyConfigForCurrentUser.Find(); err != nil { return nil, err } p := new(tWINHTTP_CURRENT_USER_IE_PROXY_CONFIG) r, _, err := winHttpGetIEProxyConfigForCurrentUser.Call(uintptr(unsafe.Pointer(p))) if rTrue(r) { return p, nil } return nil, err } func getDefaultProxyConfiguration() (*tWINHTTP_PROXY_INFO, error) { pInfo := new(tWINHTTP_PROXY_INFO) if err := winHttpGetDefaultProxyConfiguration.Find(); err != nil { return nil, err } r, _, err := winHttpGetDefaultProxyConfiguration.Call(uintptr(unsafe.Pointer(pInfo))) if rTrue(r) { return pInfo, nil } return nil, err } // OverrideEnvWithStaticProxy writes new values to the // http_proxy, https_proxy and no_proxy environment variables. // The values are taken from the Windows Regedit (should be called in init() function) func overrideEnvWithStaticProxy(conf ProxyConf, setenv envSetter) { if conf.Static.Active { for _, scheme := range []string{"http", "https"} { url := mapFallback(scheme, "", conf.Static.Protocols) setenv(scheme+"_proxy", url) } if conf.Static.NoProxy != "" { setenv("no_proxy", conf.Static.NoProxy) } } } func parseRegedit(regedit regeditValues) ProxyConf { protocol := make(map[string]string) for _, s := range strings.Split(regedit.ProxyServer, ";") { if s == "" { continue } pair := strings.SplitN(s, "=", 2) if len(pair) > 1 { protocol[pair[0]] = pair[1] } else { protocol[""] = pair[0] } } return ProxyConf{ Static: StaticProxyConf{ Active: regedit.ProxyEnable > 0, Protocols: protocol, NoProxy: strings.Replace(regedit.ProxyOverride, ";", ",", -1), // to match linux style }, Automatic: ProxyScriptConf{ Active: regedit.AutoConfigURL != "", PreConfiguredURL: regedit.AutoConfigURL, }, } } func readRegedit() (values regeditValues, err error) { var proxySettingsPerUser uint64 = 1 // 1 is the default value to consider current user k, err := registry.OpenKey(registry.LOCAL_MACHINE, `Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.QUERY_VALUE) if err == nil { //We had used the below variable tempPrxUsrSettings, because the Golang method GetIntegerValue //sets the value to zero even it fails. tempPrxUsrSettings, _, err := k.GetIntegerValue("ProxySettingsPerUser") if err == nil { //consider the value of tempPrxUsrSettings if it is a success proxySettingsPerUser = tempPrxUsrSettings } k.Close() } var hkey registry.Key if proxySettingsPerUser == 0 { hkey = registry.LOCAL_MACHINE } else { hkey = registry.CURRENT_USER } k, err = registry.OpenKey(hkey, `Software\Microsoft\Windows\CurrentVersion\Internet Settings`, registry.QUERY_VALUE) if err != nil { return } defer k.Close() values.ProxyServer, _, err = k.GetStringValue("ProxyServer") if err != nil && err != registry.ErrNotExist { return } values.ProxyOverride, _, err = k.GetStringValue("ProxyOverride") if err != nil && err != registry.ErrNotExist { return } values.ProxyEnable, _, err = k.GetIntegerValue("ProxyEnable") if err != nil && err != registry.ErrNotExist { return } values.AutoConfigURL, _, err = k.GetStringValue("AutoConfigURL") if err != nil && err != registry.ErrNotExist { return } err = nil return } go-ieproxy-0.0.9/kernel32_data_windows.go000066400000000000000000000005211431075546100203450ustar00rootroot00000000000000package ieproxy import ( "golang.org/x/sys/windows" "unsafe" ) var kernel32 = windows.NewLazySystemDLL("kernel32.dll") var globalFree = kernel32.NewProc("GlobalFree") func globalFreeWrapper(ptr *uint16) { if ptr != nil { _, _, _ = globalFree.Call(uintptr(unsafe.Pointer(ptr))) } } func rTrue(r uintptr) bool { return r == 1 } go-ieproxy-0.0.9/pac_darwin.go000066400000000000000000000074721431075546100163000ustar00rootroot00000000000000package ieproxy /* #cgo LDFLAGS: -framework CoreFoundation #cgo LDFLAGS: -framework CFNetwork #include #include #define STR_LEN 128 void proxyAutoConfCallback(void* client, CFArrayRef proxies, CFErrorRef error) { CFTypeRef* result_ptr = (CFTypeRef*)client; if (error != NULL) { *result_ptr = CFRetain(error); } else { *result_ptr = CFRetain(proxies); } CFRunLoopStop(CFRunLoopGetCurrent()); } int intCFNumber(CFNumberRef num) { int ret; CFNumberGetValue(num, kCFNumberIntType, &ret); return ret; } char* _getProxyUrlFromPac(char* pac, char* reqCs) { char* retCString = (char*)calloc(STR_LEN, sizeof(char)); CFStringRef reqStr = CFStringCreateWithCString(NULL, reqCs, kCFStringEncodingUTF8); CFStringRef pacStr = CFStringCreateWithCString(NULL, pac, kCFStringEncodingUTF8); CFURLRef pacUrl = CFURLCreateWithString(NULL, pacStr, NULL); CFURLRef reqUrl = CFURLCreateWithString(NULL, reqStr, NULL); CFTypeRef result = NULL; CFStreamClientContext context = { 0, &result, NULL, NULL, NULL }; CFRunLoopSourceRef runloop_src = CFNetworkExecuteProxyAutoConfigurationURL(pacUrl, reqUrl, proxyAutoConfCallback, &context); if (runloop_src) { const CFStringRef private_runloop_mode = CFSTR("go-ieproxy"); CFRunLoopAddSource(CFRunLoopGetCurrent(), runloop_src, private_runloop_mode); CFRunLoopRunInMode(private_runloop_mode, DBL_MAX, false); CFRunLoopRemoveSource(CFRunLoopGetCurrent(), runloop_src, kCFRunLoopCommonModes); if (CFGetTypeID(result) == CFArrayGetTypeID()) { CFArrayRef resultArray = (CFTypeRef)result; if (CFArrayGetCount(resultArray) > 0) { CFDictionaryRef pxy = (CFDictionaryRef)CFArrayGetValueAtIndex(resultArray, 0); CFStringRef pxyType = CFDictionaryGetValue(pxy, kCFProxyTypeKey); if (CFEqual(pxyType, kCFProxyTypeNone)) { // noop } if (CFEqual(pxyType, kCFProxyTypeHTTP)) { CFStringRef host = (CFStringRef)CFDictionaryGetValue(pxy, kCFProxyHostNameKey); CFNumberRef port = (CFNumberRef)CFDictionaryGetValue(pxy, kCFProxyPortNumberKey); char host_str[STR_LEN - 16]; CFStringGetCString(host, host_str, STR_LEN - 16, kCFStringEncodingUTF8); int port_int = 80; if (port) { CFNumberGetValue(port, kCFNumberIntType, &port_int); } sprintf(retCString, "%s:%d", host_str, port_int); } } } else { // error } } CFRelease(result); CFRelease(reqStr); CFRelease(reqUrl); CFRelease(pacStr); CFRelease(pacUrl); return retCString; } char* _getPacUrl() { char* retCString = (char*)calloc(STR_LEN, sizeof(char)); CFDictionaryRef proxyDict = CFNetworkCopySystemProxySettings(); CFNumberRef pacEnable = (CFNumberRef)CFDictionaryGetValue(proxyDict, kCFNetworkProxiesProxyAutoConfigEnable); if (pacEnable && intCFNumber(pacEnable)) { CFStringRef pacUrlStr = (CFStringRef)CFDictionaryGetValue(proxyDict, kCFNetworkProxiesProxyAutoConfigURLString); if (pacUrlStr) { CFStringGetCString(pacUrlStr, retCString, STR_LEN, kCFStringEncodingUTF8); } } CFRelease(proxyDict); return retCString; } */ import "C" import ( "net/url" "unsafe" ) func (psc *ProxyScriptConf) findProxyForURL(URL string) string { if !psc.Active { return "" } proxy := getProxyForURL(psc.PreConfiguredURL, URL) return proxy } func getProxyForURL(pacFileURL, targetURL string) string { if pacFileURL == "" { pacFileURL = getPacUrl() } if pacFileURL == "" { return "" } if u, err := url.Parse(pacFileURL); err != nil || u.Scheme == "" { return "" } csUrl := C.CString(targetURL) csPac := C.CString(pacFileURL) csRet := C._getProxyUrlFromPac(csPac, csUrl) defer C.free(unsafe.Pointer(csUrl)) defer C.free(unsafe.Pointer(csPac)) defer C.free(unsafe.Pointer(csRet)) return C.GoString(csRet) } func getPacUrl() string { csRet := C._getPacUrl() defer C.free(unsafe.Pointer(csRet)) return C.GoString(csRet) } go-ieproxy-0.0.9/pac_unix.go000066400000000000000000000002511431075546100157630ustar00rootroot00000000000000//go:build (!windows && !darwin) || !cgo // +build !windows,!darwin !cgo package ieproxy func (psc *ProxyScriptConf) findProxyForURL(URL string) string { return "" } go-ieproxy-0.0.9/pac_windows.go000066400000000000000000000037431431075546100165030ustar00rootroot00000000000000package ieproxy import ( "strings" "syscall" "unsafe" ) func (psc *ProxyScriptConf) findProxyForURL(URL string) string { if !psc.Active { return "" } proxy, _ := getProxyForURL(psc.PreConfiguredURL, URL) i := strings.Index(proxy, ";") if i >= 0 { return proxy[:i] } return proxy } func getProxyForURL(pacfileURL, URL string) (string, error) { pacfileURLPtr, err := syscall.UTF16PtrFromString(pacfileURL) if err != nil { return "", err } URLPtr, err := syscall.UTF16PtrFromString(URL) if err != nil { return "", err } handle, _, err := winHttpOpen.Call(0, 0, 0, 0, 0) if handle == 0 { return "", err } defer winHttpCloseHandle.Call(handle) dwFlags := fWINHTTP_AUTOPROXY_CONFIG_URL dwAutoDetectFlags := autoDetectFlag(0) pfURLptr := pacfileURLPtr if pacfileURL == "" { dwFlags = fWINHTTP_AUTOPROXY_AUTO_DETECT dwAutoDetectFlags = fWINHTTP_AUTO_DETECT_TYPE_DNS_A | fWINHTTP_AUTO_DETECT_TYPE_DHCP pfURLptr = nil } options := tWINHTTP_AUTOPROXY_OPTIONS{ dwFlags: dwFlags, // adding cache might cause issues: https://github.com/mattn/go-ieproxy/issues/6 dwAutoDetectFlags: dwAutoDetectFlags, lpszAutoConfigUrl: pfURLptr, lpvReserved: nil, dwReserved: 0, fAutoLogonIfChallenged: true, // may not be optimal https://msdn.microsoft.com/en-us/library/windows/desktop/aa383153(v=vs.85).aspx } // lpszProxyBypass isn't used as this only executes in cases where there (may) be a pac file (autodetect can fail), where lpszProxyBypass couldn't be returned. // in the case that autodetect fails and no pre-specified pacfile is present, no proxy is returned. info := new(tWINHTTP_PROXY_INFO) ret, _, err := winHttpGetProxyForURL.Call( handle, uintptr(unsafe.Pointer(URLPtr)), uintptr(unsafe.Pointer(&options)), uintptr(unsafe.Pointer(info)), ) if ret > 0 { err = nil } defer globalFreeWrapper(info.lpszProxyBypass) defer globalFreeWrapper(info.lpszProxy) return StringFromUTF16Ptr(info.lpszProxy), err } go-ieproxy-0.0.9/pacfile_examples/000077500000000000000000000000001431075546100171315ustar00rootroot00000000000000go-ieproxy-0.0.9/pacfile_examples/direct.pac000066400000000000000000000000721431075546100210670ustar00rootroot00000000000000function FindProxyForURL(url, host){ return 'DIRECT'; } go-ieproxy-0.0.9/pacfile_examples/except.pac000066400000000000000000000003701431075546100211060ustar00rootroot00000000000000function FindProxyForURL(url, host) { var useSocks = ["imgur.com"]; for (var i= 0; i < useSocks.length; i++) { if (shExpMatch(host, useSocks[i])) { return "PROXY localhost:9999"; } } return "DIRECT"; } go-ieproxy-0.0.9/pacfile_examples/multiple.pac000066400000000000000000000001311431075546100214440ustar00rootroot00000000000000function FindProxyForURL(url, host){ return 'PROXY 127.0.0.1:8081; PROXY 129.0.0.1'; } go-ieproxy-0.0.9/pacfile_examples/simple.pac000066400000000000000000000001051431075546100211030ustar00rootroot00000000000000function FindProxyForURL(url, host){ return 'PROXY 127.0.0.1:8'; } go-ieproxy-0.0.9/proxy_middleman.go000066400000000000000000000003321431075546100173500ustar00rootroot00000000000000package ieproxy import ( "net/http" "net/url" ) // GetProxyFunc is a forwarder for the OS-Exclusive proxyMiddleman_os.go files func GetProxyFunc() func(*http.Request) (*url.URL, error) { return proxyMiddleman() } go-ieproxy-0.0.9/proxy_middleman_darwin.go000066400000000000000000000021311431075546100207130ustar00rootroot00000000000000package ieproxy import ( "net/http" "net/url" "golang.org/x/net/http/httpproxy" ) func proxyMiddleman() func(req *http.Request) (i *url.URL, e error) { // Get the proxy configuration conf := GetConf() envCfg := httpproxy.FromEnvironment() if envCfg.HTTPProxy != "" || envCfg.HTTPSProxy != "" { // If the user manually specifies environment variables, prefer those over the MacOS config. return http.ProxyFromEnvironment } return func(req *http.Request) (i *url.URL, e error) { if conf.Automatic.Active { host := conf.Automatic.FindProxyForURL(req.URL.String()) if host != "" { return &url.URL{Host: host}, nil } } if conf.Static.Active { return staticProxy(conf, req) } // Should return no proxy; fallthrough. return http.ProxyFromEnvironment(req) } } func staticProxy(conf ProxyConf, req *http.Request) (i *url.URL, e error) { // If static proxy obtaining is specified proxy := httpproxy.Config{ HTTPSProxy: conf.Static.Protocols["https"], HTTPProxy: conf.Static.Protocols["http"], NoProxy: conf.Static.NoProxy, } return proxy.ProxyFunc()(req.URL) } go-ieproxy-0.0.9/proxy_middleman_unix.go000066400000000000000000000004241431075546100204150ustar00rootroot00000000000000//go:build !windows && !darwin // +build !windows,!darwin package ieproxy import ( "net/http" "net/url" ) func proxyMiddleman() func(req *http.Request) (i *url.URL, e error) { // Fallthrough to ProxyFromEnvironment on all other OSes. return http.ProxyFromEnvironment } go-ieproxy-0.0.9/proxy_middleman_windows.go000066400000000000000000000025001431075546100211210ustar00rootroot00000000000000package ieproxy import ( "net/http" "net/url" "golang.org/x/net/http/httpproxy" ) func proxyMiddleman() func(req *http.Request) (i *url.URL, e error) { // Get the proxy configuration conf := GetConf() envcfg := httpproxy.FromEnvironment() if envcfg.HTTPProxy != "" || envcfg.HTTPSProxy != "" { // If the user manually specifies environment variables, prefer those over the Windows config. return http.ProxyFromEnvironment } return func(req *http.Request) (i *url.URL, e error) { if conf.Automatic.Active { host := conf.Automatic.FindProxyForURL(req.URL.String()) if host != "" { return &url.URL{Host: host}, nil } } if conf.Static.Active { return staticProxy(conf, req) } // Should return no proxy; fallthrough. return http.ProxyFromEnvironment(req) } } func staticProxy(conf ProxyConf, req *http.Request) (i *url.URL, e error) { // If static proxy obtaining is specified prox := httpproxy.Config{ HTTPSProxy: mapFallback("https", "", conf.Static.Protocols), HTTPProxy: mapFallback("http", "", conf.Static.Protocols), NoProxy: conf.Static.NoProxy, } return prox.ProxyFunc()(req.URL) } // Return oKey or fbKey if oKey doesn't exist in the map. func mapFallback(oKey, fbKey string, m map[string]string) string { if v, ok := m[oKey]; ok { return v } else { return m[fbKey] } } go-ieproxy-0.0.9/utils.go000066400000000000000000000005361431075546100153230ustar00rootroot00000000000000package ieproxy import ( "unicode/utf16" "unsafe" ) // StringFromUTF16Ptr converts a *uint16 C string to a Go String func StringFromUTF16Ptr(s *uint16) string { if s == nil { return "" } p := (*[1<<30 - 1]uint16)(unsafe.Pointer(s)) // find the string length sz := 0 for p[sz] != 0 { sz++ } return string(utf16.Decode(p[:sz:sz])) } go-ieproxy-0.0.9/utils_test.go000066400000000000000000000010441431075546100163550ustar00rootroot00000000000000package ieproxy import ( "log" "net" "net/http" ) // For testing purposes func listenAndServeWithClose(addr string, handler http.Handler) (net.Listener, error) { var ( listener net.Listener err error ) srv := &http.Server{Addr: addr, Handler: handler} if addr == "" { addr = ":http" } listener, err = net.Listen("tcp", addr) if err != nil { return nil, err } go func() { err := srv.Serve(listener.(*net.TCPListener)) if err != nil { log.Println("HTTP Server Error - ", err) } }() return listener, nil } go-ieproxy-0.0.9/windows_test.go000066400000000000000000000117511431075546100167150ustar00rootroot00000000000000//go:build windows // +build windows package ieproxy import ( "net/http" "reflect" "testing" ) var emptyMap, catchAllMap, multipleMap, multipleMapWithCatchAll map[string]string func init() { emptyMap = make(map[string]string) catchAllMap = make(map[string]string) catchAllMap[""] = "127.0.0.1" multipleMap = make(map[string]string) multipleMap["http"] = "127.0.0.1" multipleMap["ftp"] = "128" multipleMapWithCatchAll = make(map[string]string) multipleMapWithCatchAll["http"] = "127.0.0.1" multipleMapWithCatchAll["ftp"] = "128" multipleMapWithCatchAll[""] = "129" } func TestParseRegedit(t *testing.T) { parsingSet := []struct { in regeditValues out ProxyConf }{ { in: regeditValues{}, out: ProxyConf{ Static: StaticProxyConf{ Protocols: emptyMap, // to prevent it being }, }, }, { in: regeditValues{ ProxyServer: "127.0.0.1", }, out: ProxyConf{ Static: StaticProxyConf{ Protocols: catchAllMap, }, }, }, { in: regeditValues{ ProxyServer: "http=127.0.0.1;ftp=128", }, out: ProxyConf{ Static: StaticProxyConf{ Protocols: multipleMap, }, }, }, { in: regeditValues{ ProxyServer: "http=127.0.0.1;ftp=128;129", }, out: ProxyConf{ Static: StaticProxyConf{ Protocols: multipleMapWithCatchAll, }, }, }, { in: regeditValues{ ProxyOverride: "example.com;microsoft.com", }, out: ProxyConf{ Static: StaticProxyConf{ Protocols: emptyMap, NoProxy: "example.com,microsoft.com", }, }, }, { in: regeditValues{ ProxyEnable: 1, }, out: ProxyConf{ Static: StaticProxyConf{ Active: true, Protocols: emptyMap, }, }, }, { in: regeditValues{ AutoConfigURL: "localhost/proxy.pac", }, out: ProxyConf{ Static: StaticProxyConf{ Protocols: emptyMap, }, Automatic: ProxyScriptConf{ Active: true, PreConfiguredURL: "localhost/proxy.pac", }, }, }, } for _, p := range parsingSet { out := parseRegedit(p.in) if !reflect.DeepEqual(p.out, out) { t.Error("Got: ", out, "Expected: ", p.out) } } } func TestOverrideEnv(t *testing.T) { var callStack []string pseudoSetEnv := func(key, value string) error { if value != "" { callStack = append(callStack, key) callStack = append(callStack, value) } return nil } overrideSet := []struct { in ProxyConf callStack []string }{ { callStack: []string{}, }, { in: ProxyConf{ Static: StaticProxyConf{ Active: true, Protocols: catchAllMap, }, }, callStack: []string{"http_proxy", "127.0.0.1", "https_proxy", "127.0.0.1"}, }, { in: ProxyConf{ Static: StaticProxyConf{ Active: false, NoProxy: "example.com,microsoft.com", Protocols: catchAllMap, }, }, callStack: []string{}, }, { in: ProxyConf{ Static: StaticProxyConf{ Active: true, Protocols: multipleMap, }, }, callStack: []string{"http_proxy", "127.0.0.1"}, }, { in: ProxyConf{ Static: StaticProxyConf{ Active: true, Protocols: multipleMapWithCatchAll, }, }, callStack: []string{"http_proxy", "127.0.0.1", "https_proxy", "129"}, }, { in: ProxyConf{ Static: StaticProxyConf{ Active: true, NoProxy: "example.com,microsoft.com", }, }, callStack: []string{"no_proxy", "example.com,microsoft.com"}, }, } for _, o := range overrideSet { callStack = []string{} overrideEnvWithStaticProxy(o.in, pseudoSetEnv) if !reflect.DeepEqual(o.callStack, callStack) { t.Error("Got: ", callStack, "Expected: ", o.callStack) } } } func TestPacfile(t *testing.T) { listener, err := listenAndServeWithClose("127.0.0.1:0", http.FileServer(http.Dir("pacfile_examples"))) serverBase := "http://" + listener.Addr().String() + "/" if err != nil { t.Fatal(err) } // test inactive proxy proxy := ProxyScriptConf{ Active: false, PreConfiguredURL: serverBase + "simple.pac", } out := proxy.FindProxyForURL("http://google.com") if out != "" { t.Error("Got: ", out, "Expected: ", "") } proxy.Active = true pacSet := []struct { pacfile string url string expected string }{ { serverBase + "direct.pac", "http://google.com", "", }, { serverBase + "404.pac", "http://google.com", "", }, { serverBase + "simple.pac", "http://google.com", "127.0.0.1:8", }, { serverBase + "multiple.pac", "http://google.com", "127.0.0.1:8081", }, { serverBase + "except.pac", "http://imgur.com", "localhost:9999", }, { serverBase + "except.pac", "http://example.com", "", }, { "", "http://example.com", "", }, { " ", "http://example.com", "", }, { "wrong_format", "http://example.com", "", }, } for _, p := range pacSet { proxy.PreConfiguredURL = p.pacfile out := proxy.FindProxyForURL(p.url) if out != p.expected { t.Error("Got: ", out, "Expected: ", p.expected) } } listener.Close() } go-ieproxy-0.0.9/winhttp_data_windows.go000066400000000000000000000033211431075546100204160ustar00rootroot00000000000000package ieproxy import "golang.org/x/sys/windows" var winHttp = windows.NewLazySystemDLL("winhttp.dll") var winHttpGetProxyForURL = winHttp.NewProc("WinHttpGetProxyForUrl") var winHttpOpen = winHttp.NewProc("WinHttpOpen") var winHttpCloseHandle = winHttp.NewProc("WinHttpCloseHandle") var winHttpGetIEProxyConfigForCurrentUser = winHttp.NewProc("WinHttpGetIEProxyConfigForCurrentUser") var winHttpGetDefaultProxyConfiguration = winHttp.NewProc("WinHttpGetDefaultProxyConfiguration") type tWINHTTP_AUTOPROXY_OPTIONS struct { dwFlags autoProxyFlag dwAutoDetectFlags autoDetectFlag lpszAutoConfigUrl *uint16 lpvReserved *uint16 dwReserved uint32 fAutoLogonIfChallenged bool } type autoProxyFlag uint32 const ( fWINHTTP_AUTOPROXY_AUTO_DETECT = autoProxyFlag(0x00000001) fWINHTTP_AUTOPROXY_CONFIG_URL = autoProxyFlag(0x00000002) fWINHTTP_AUTOPROXY_NO_CACHE_CLIENT = autoProxyFlag(0x00080000) fWINHTTP_AUTOPROXY_NO_CACHE_SVC = autoProxyFlag(0x00100000) fWINHTTP_AUTOPROXY_NO_DIRECTACCESS = autoProxyFlag(0x00040000) fWINHTTP_AUTOPROXY_RUN_INPROCESS = autoProxyFlag(0x00010000) fWINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY = autoProxyFlag(0x00020000) fWINHTTP_AUTOPROXY_SORT_RESULTS = autoProxyFlag(0x00400000) ) type autoDetectFlag uint32 const ( fWINHTTP_AUTO_DETECT_TYPE_DHCP = autoDetectFlag(0x00000001) fWINHTTP_AUTO_DETECT_TYPE_DNS_A = autoDetectFlag(0x00000002) ) type tWINHTTP_PROXY_INFO struct { dwAccessType uint32 lpszProxy *uint16 lpszProxyBypass *uint16 } type tWINHTTP_CURRENT_USER_IE_PROXY_CONFIG struct { fAutoDetect bool lpszAutoConfigUrl *uint16 lpszProxy *uint16 lpszProxyBypass *uint16 }