feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+144
@@ -0,0 +1,144 @@
|
||||
// Package netproxy sends Go's HTTP requests through the proxy the user set
|
||||
// in the system's settings, as browsers and the app's web pages do, with
|
||||
// its bypass list and automatic configuration (PAC files, WPAD):
|
||||
//
|
||||
// client := &http.Client{Transport: netproxy.Transport()}
|
||||
//
|
||||
// MyGo's own requests go this way: the updater's, and those of the fetch
|
||||
// and websocket plugins unless their options name a client.
|
||||
//
|
||||
// Proxy decides, for each request:
|
||||
//
|
||||
// 1. Loopback hosts (localhost, *.localhost, 127.0.0.0/8, ::1) are
|
||||
// reached directly.
|
||||
// 2. When any of HTTP_PROXY, HTTPS_PROXY, ALL_PROXY or NO_PROXY (or its
|
||||
// lowercase name) is set, the environment decides, as
|
||||
// http.ProxyFromEnvironment does: an explicit setting wins over the
|
||||
// system's.
|
||||
// 3. Otherwise the system's settings for the URL do: WinHTTP's reading
|
||||
// of the user's settings on Windows, with automatic detection and PAC
|
||||
// files; CFNetwork's on macOS, with PAC files; GIO's default proxy
|
||||
// resolver on Linux, which reads GNOME's settings, or KDE's and PAC
|
||||
// files through libproxy. Where none answers, requests go direct.
|
||||
//
|
||||
// The system's answer for a scheme and host is kept for 5 seconds, so a
|
||||
// change of the settings applies to the requests that follow without
|
||||
// restarting the app. Requests under way keep their connections, and Go's
|
||||
// transport keys idle connections by their proxy, so none opened through
|
||||
// the previous proxy is reused for the new one.
|
||||
//
|
||||
// Go's transport speaks to HTTP and HTTPS proxies and to SOCKS5: a SOCKS
|
||||
// proxy of unknown version is taken for SOCKS5, and SOCKS4 proxies are
|
||||
// skipped. A proxy's password is sent only when the system's answer
|
||||
// holds it, as GNOME's settings can. In browsers (js/wasm) the browser
|
||||
// makes the requests, with its own proxy.
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ttl is how long the system's answer for a scheme and host is kept.
|
||||
const ttl = 5 * time.Second
|
||||
|
||||
// envNames are the variables that hand the decision to the environment.
|
||||
var envNames = [...]string{
|
||||
"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy",
|
||||
"ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy",
|
||||
}
|
||||
|
||||
// Replaced by tests.
|
||||
var (
|
||||
envProxy = http.ProxyFromEnvironment
|
||||
systemProxy = system
|
||||
now = time.Now
|
||||
)
|
||||
|
||||
// Proxy returns the proxy for req, or nil to connect directly. It is an
|
||||
// http.Transport's Proxy, safe from any goroutine; it may block while the
|
||||
// system runs a PAC file.
|
||||
func Proxy(req *http.Request) (*url.URL, error) {
|
||||
if isLoopback(req.URL.Hostname()) {
|
||||
return nil, nil
|
||||
}
|
||||
for _, name := range envNames {
|
||||
if os.Getenv(name) != "" {
|
||||
return envProxy(req)
|
||||
}
|
||||
}
|
||||
return cached(req.URL.Scheme, req.URL.Host), nil
|
||||
}
|
||||
|
||||
var transport lazy[*http.Transport]
|
||||
|
||||
// Transport returns a transport like http.DefaultTransport whose Proxy is
|
||||
// Proxy. It is shared: clone it to change its settings.
|
||||
func Transport() *http.Transport {
|
||||
return transport.get(func() *http.Transport {
|
||||
t := http.DefaultTransport.(*http.Transport).Clone()
|
||||
t.Proxy = Proxy
|
||||
return t
|
||||
})
|
||||
}
|
||||
|
||||
// lazy is a value made on first use. Unlike sync.OnceValue's, a package
|
||||
// variable of it runs nothing at init, so that apps that never make a
|
||||
// request through Proxy link none of it.
|
||||
type lazy[T any] struct {
|
||||
once sync.Once
|
||||
v T
|
||||
}
|
||||
|
||||
func (l *lazy[T]) get(f func() T) T {
|
||||
l.once.Do(func() { l.v = f() })
|
||||
return l.v
|
||||
}
|
||||
|
||||
var cache struct {
|
||||
sync.Mutex
|
||||
m map[string]cacheEntry
|
||||
}
|
||||
|
||||
type cacheEntry struct {
|
||||
proxy *url.URL
|
||||
until time.Time
|
||||
}
|
||||
|
||||
// cached returns the system's proxy for scheme and host (with its port),
|
||||
// asking the system when the last answer is older than ttl.
|
||||
func cached(scheme, host string) *url.URL {
|
||||
key := scheme + "://" + host
|
||||
t := now()
|
||||
cache.Lock()
|
||||
e, ok := cache.m[key]
|
||||
cache.Unlock()
|
||||
if !ok || !t.Before(e.until) {
|
||||
e = cacheEntry{systemProxy(&url.URL{Scheme: scheme, Host: host, Path: "/"}), t.Add(ttl)}
|
||||
cache.Lock()
|
||||
if cache.m == nil || len(cache.m) >= 256 {
|
||||
cache.m = map[string]cacheEntry{}
|
||||
}
|
||||
cache.m[key] = e
|
||||
cache.Unlock()
|
||||
}
|
||||
if e.proxy == nil {
|
||||
return nil
|
||||
}
|
||||
p := *e.proxy
|
||||
return &p
|
||||
}
|
||||
|
||||
func isLoopback(host string) bool {
|
||||
host = strings.ToLower(host)
|
||||
if host == "localhost" || strings.HasSuffix(host, ".localhost") {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFirstSupported(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
list []string
|
||||
want string
|
||||
}{
|
||||
{nil, ""},
|
||||
{[]string{"direct://"}, ""},
|
||||
{[]string{"http://proxy:3128"}, "http://proxy:3128"},
|
||||
{[]string{"HTTP://proxy:3128/"}, "http://proxy:3128"},
|
||||
{[]string{"https://proxy:443"}, "https://proxy:443"},
|
||||
{[]string{"http://user:pw@proxy:3128"}, "http://user:pw@proxy:3128"},
|
||||
// GNOME's SOCKS setting: socks5, then socks4a and socks4.
|
||||
{[]string{"socks5://s:1080", "socks4a://s:1080", "socks4://s:1080"}, "socks5://s:1080"},
|
||||
{[]string{"socks5h://s:1080"}, "socks5h://s:1080"},
|
||||
{[]string{"socks://s:1080"}, "socks5://s:1080"},
|
||||
{[]string{"socks4://s:1080", "http://p:80"}, "http://p:80"},
|
||||
{[]string{"socks4://s:1080", "direct://", "http://p:80"}, ""},
|
||||
{[]string{"ftp://f:21", "", "http://"}, ""},
|
||||
{[]string{"http://[::1]:8080"}, "http://[::1]:8080"},
|
||||
} {
|
||||
if got := urlString(firstSupported(tc.list)); got != tc.want {
|
||||
t.Errorf("firstSupported(%q) = %q, want %q", tc.list, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWinProxy(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
list, scheme, want string
|
||||
}{
|
||||
{"", "https", ""},
|
||||
{"127.0.0.1:7890", "https", "http://127.0.0.1:7890"},
|
||||
{"127.0.0.1:7890", "http", "http://127.0.0.1:7890"},
|
||||
{"http://proxy:8080", "https", "http://proxy:8080"},
|
||||
{"proxy", "http", "http://proxy"},
|
||||
{"http=h:80;https=s:443;socks=k:1080", "http", "http://h:80"},
|
||||
{"http=h:80;https=s:443;socks=k:1080", "https", "http://s:443"},
|
||||
{"http=h:80;socks=k:1080", "https", "socks5://k:1080"},
|
||||
{"ftp=f:21", "https", ""},
|
||||
{"HTTPS=s:443 http=h:80", "https", "http://s:443"},
|
||||
{"https=https://s:443", "https", "https://s:443"},
|
||||
// WinHTTP's answer from a setup script: proxies to try in turn.
|
||||
{"a:8080; b:8080", "https", "http://a:8080"},
|
||||
{"socks4://k:1080;b:80", "http", "http://b:80"},
|
||||
} {
|
||||
if got := urlString(winProxy(tc.list, tc.scheme)); got != tc.want {
|
||||
t.Errorf("winProxy(%q, %q) = %q, want %q", tc.list, tc.scheme, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWinBypassed(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
list, host string
|
||||
want bool
|
||||
}{
|
||||
{"", "example.com", false},
|
||||
{"<local>", "intranet", true},
|
||||
{"<local>", "example.com", false},
|
||||
{"<local>", "::1", false},
|
||||
{"*.corp.com", "a.b.corp.com", true},
|
||||
{"*.corp.com", "corp.com", false},
|
||||
{"*.CORP.com", "Wiki.Corp.Com", true},
|
||||
{".corp.com", "wiki.corp.com", true},
|
||||
{"corp.com", "corp.com", true},
|
||||
{"corp.com", "wiki.corp.com", false},
|
||||
{"10.*;192.168.*", "10.1.2.3", true},
|
||||
{"10.*;192.168.*", "192.168.0.7", true},
|
||||
{"10.*;192.168.*", "11.0.0.1", false},
|
||||
{"10.0.0.0/8", "10.9.9.9", true},
|
||||
{"10.0.0.0/8", "example.com", false},
|
||||
{"fe80::/10", "fe80::1", true},
|
||||
{"foo.com:8080", "foo.com", true},
|
||||
{"*.a.com <local>\t*.b.com", "x.b.com", true},
|
||||
{"<-loopback>;*.a.com", "b.com", false},
|
||||
{"http://*.a.com", "x.a.com", true},
|
||||
{"*", "anything.example", true},
|
||||
} {
|
||||
if got := winBypassed(tc.list, tc.host); got != tc.want {
|
||||
t.Errorf("winBypassed(%q, %q) = %v, want %v", tc.list, tc.host, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWinStatic(t *testing.T) {
|
||||
u := func(s string) *url.URL { p, _ := url.Parse(s); return p }
|
||||
if got := urlString(winStatic("p:80", "<local>;*.corp.com", u("https://wiki.corp.com/"))); got != "" {
|
||||
t.Errorf("bypassed host got proxy %q", got)
|
||||
}
|
||||
if got := urlString(winStatic("p:80", "<local>;*.corp.com", u("https://example.com/"))); got != "http://p:80" {
|
||||
t.Errorf("got %q, want http://p:80", got)
|
||||
}
|
||||
}
|
||||
|
||||
// clearEnv unsets the variables that hand the decision to the
|
||||
// environment.
|
||||
func clearEnv(t *testing.T) {
|
||||
for _, name := range envNames {
|
||||
t.Setenv(name, "")
|
||||
}
|
||||
}
|
||||
|
||||
// fakeSystem replaces the system's settings with proxy, counting the
|
||||
// questions, and the clock with a fake one.
|
||||
func fakeSystem(t *testing.T, proxy string) (asked *int, clock *time.Time) {
|
||||
asked, clock = new(int), new(time.Time)
|
||||
*clock = time.Unix(1000, 0)
|
||||
saved, savedNow := systemProxy, now
|
||||
systemProxy = func(target *url.URL) *url.URL {
|
||||
*asked++
|
||||
if target.Path != "/" || target.RawQuery != "" {
|
||||
t.Errorf("system asked about %s, want scheme and host only", target)
|
||||
}
|
||||
p, _ := url.Parse(proxy)
|
||||
return p
|
||||
}
|
||||
now = func() time.Time { return *clock }
|
||||
cache.Lock()
|
||||
cache.m = nil
|
||||
cache.Unlock()
|
||||
t.Cleanup(func() { systemProxy, now = saved, savedNow })
|
||||
return asked, clock
|
||||
}
|
||||
|
||||
func proxyFor(t *testing.T, rawURL string) string {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest("GET", rawURL, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := Proxy(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return urlString(p)
|
||||
}
|
||||
|
||||
func TestProxyLoopbackIsDirect(t *testing.T) {
|
||||
clearEnv(t)
|
||||
asked, _ := fakeSystem(t, "http://proxy:3128")
|
||||
for _, u := range []string{
|
||||
"http://localhost:5173/", "http://LocalHost/", "http://app.localhost/",
|
||||
"http://127.0.0.1:8080/", "http://127.4.5.6/", "http://[::1]:3000/",
|
||||
} {
|
||||
if got := proxyFor(t, u); got != "" {
|
||||
t.Errorf("Proxy(%s) = %q, want direct", u, got)
|
||||
}
|
||||
}
|
||||
if *asked != 0 {
|
||||
t.Errorf("system asked %d times about loopback hosts", *asked)
|
||||
}
|
||||
t.Setenv("HTTPS_PROXY", "http://env:1")
|
||||
if got := proxyFor(t, "https://localhost/"); got != "" {
|
||||
t.Errorf("Proxy(localhost) with HTTPS_PROXY = %q, want direct", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyEnvironmentWins(t *testing.T) {
|
||||
saved := envProxy
|
||||
t.Cleanup(func() { envProxy = saved })
|
||||
env, _ := url.Parse("http://env:8080")
|
||||
envProxy = func(*http.Request) (*url.URL, error) { return env, nil }
|
||||
for _, name := range envNames {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
clearEnv(t)
|
||||
asked, _ := fakeSystem(t, "http://system:3128")
|
||||
t.Setenv(name, "x")
|
||||
if got := proxyFor(t, "https://example.com/"); got != "http://env:8080" {
|
||||
t.Errorf("Proxy = %q, want the environment's", got)
|
||||
}
|
||||
if *asked != 0 {
|
||||
t.Errorf("system asked %d times", *asked)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxySystemCached(t *testing.T) {
|
||||
clearEnv(t)
|
||||
asked, clock := fakeSystem(t, "http://system:3128")
|
||||
for range 3 {
|
||||
if got := proxyFor(t, "https://example.com/a?b=c"); got != "http://system:3128" {
|
||||
t.Fatalf("Proxy = %q, want the system's", got)
|
||||
}
|
||||
}
|
||||
if *asked != 1 {
|
||||
t.Errorf("system asked %d times, want 1", *asked)
|
||||
}
|
||||
proxyFor(t, "http://example.com/")
|
||||
proxyFor(t, "https://example.com:8443/")
|
||||
if *asked != 3 {
|
||||
t.Errorf("system asked %d times for 3 schemes and hosts, want 3", *asked)
|
||||
}
|
||||
*clock = clock.Add(ttl)
|
||||
proxyFor(t, "https://example.com/")
|
||||
if *asked != 4 {
|
||||
t.Errorf("system asked %d times once the answer expired, want 4", *asked)
|
||||
}
|
||||
|
||||
// The answer is a copy: changing it changes no other.
|
||||
req, _ := http.NewRequest("GET", "https://example.com/", nil)
|
||||
p, _ := Proxy(req)
|
||||
p.Host = "changed"
|
||||
if got := proxyFor(t, "https://example.com/"); got != "http://system:3128" {
|
||||
t.Errorf("Proxy after changing its answer = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransport(t *testing.T) {
|
||||
tr := Transport()
|
||||
if tr != Transport() {
|
||||
t.Error("Transport is not shared")
|
||||
}
|
||||
if tr.Proxy == nil || tr == http.DefaultTransport {
|
||||
t.Error("Transport is not a clone of http.DefaultTransport with Proxy")
|
||||
}
|
||||
}
|
||||
|
||||
func urlString(u *url.URL) string {
|
||||
if u == nil {
|
||||
return ""
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
Vendored
+163
@@ -0,0 +1,163 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// firstSupported returns the first proxy of list, as "http://host:port",
|
||||
// "socks5://host:port" or "direct://", that Go's transport can use, or
|
||||
// nil for a direct connection: "direct://" comes first, or no proxy
|
||||
// can be used.
|
||||
func firstSupported(list []string) *url.URL {
|
||||
for _, s := range list {
|
||||
if p, direct := proxyURL(s); direct {
|
||||
return nil
|
||||
} else if p != nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// proxyURL parses one proxy of a list. It returns nil for a proxy Go's
|
||||
// transport cannot use, and direct for "direct://".
|
||||
func proxyURL(s string) (p *url.URL, direct bool) {
|
||||
s = strings.TrimSpace(s)
|
||||
if strings.EqualFold(s, "direct://") || strings.EqualFold(s, "direct") {
|
||||
return nil, true
|
||||
}
|
||||
u, err := url.Parse(s)
|
||||
if err != nil || u.Host == "" || u.Hostname() == "" {
|
||||
return nil, false
|
||||
}
|
||||
switch u.Scheme = strings.ToLower(u.Scheme); u.Scheme {
|
||||
case "http", "https", "socks5", "socks5h":
|
||||
case "socks":
|
||||
// A SOCKS proxy of no stated version.
|
||||
u.Scheme = "socks5"
|
||||
default: // socks4, socks4a, ftp...
|
||||
return nil, false
|
||||
}
|
||||
return &url.URL{Scheme: u.Scheme, User: u.User, Host: u.Host}, false
|
||||
}
|
||||
|
||||
// winProxy returns the proxy of a Windows proxy list for URLs of scheme:
|
||||
// "host:port" for every scheme, or per scheme as
|
||||
// "http=host:port;https=host:port;socks=host:port", where a scheme
|
||||
// without its own proxy uses the SOCKS one. Entries are separated by
|
||||
// semicolons or spaces; the first one that applies wins.
|
||||
func winProxy(list, scheme string) *url.URL {
|
||||
var all, socks *url.URL
|
||||
for _, e := range splitList(list) {
|
||||
k, v, ok := strings.Cut(e, "=")
|
||||
if !ok {
|
||||
if all == nil {
|
||||
all = winEntry(e, "http")
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch k = strings.ToLower(strings.TrimSpace(k)); {
|
||||
case k == scheme:
|
||||
if p := winEntry(v, "http"); p != nil {
|
||||
return p
|
||||
}
|
||||
case k == "socks" && socks == nil:
|
||||
socks = winEntry(v, "socks5")
|
||||
}
|
||||
}
|
||||
if all != nil {
|
||||
return all
|
||||
}
|
||||
return socks
|
||||
}
|
||||
|
||||
// winStatic returns the proxy of a proxy list and bypass list for target.
|
||||
func winStatic(proxy, bypass string, target *url.URL) *url.URL {
|
||||
if proxy == "" || winBypassed(bypass, target.Hostname()) {
|
||||
return nil
|
||||
}
|
||||
return winProxy(proxy, target.Scheme)
|
||||
}
|
||||
|
||||
// winEntry parses the server of a Windows proxy list, "host:port" or
|
||||
// "scheme://host:port", with scheme when it names none.
|
||||
func winEntry(s, scheme string) *url.URL {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
if !strings.Contains(s, "://") {
|
||||
s = scheme + "://" + s
|
||||
}
|
||||
p, _ := proxyURL(s)
|
||||
return p
|
||||
}
|
||||
|
||||
// winBypassed reports whether a Windows bypass list sends host direct:
|
||||
// entries separated by semicolons or spaces, each a host name or an IP
|
||||
// address with * wildcards ("*.example.com", "10.*"), a domain with a
|
||||
// leading dot (".example.com"), an address prefix ("10.0.0.0/8"), or
|
||||
// <local>, the host names without a dot.
|
||||
func winBypassed(list, host string) bool {
|
||||
host = strings.ToLower(strings.TrimSuffix(host, "."))
|
||||
if host == "" {
|
||||
return false
|
||||
}
|
||||
ip, ipErr := netip.ParseAddr(host)
|
||||
for _, e := range splitList(strings.ToLower(list)) {
|
||||
if _, rest, ok := strings.Cut(e, "://"); ok {
|
||||
e = rest
|
||||
}
|
||||
switch {
|
||||
case e == "<local>":
|
||||
if ipErr != nil && !strings.Contains(host, ".") {
|
||||
return true
|
||||
}
|
||||
case strings.HasPrefix(e, "<"): // <-loopback>; loopback hosts never reach here
|
||||
case strings.Contains(e, "/"):
|
||||
if p, err := netip.ParsePrefix(e); err == nil && ipErr == nil && p.Contains(ip.Unmap()) {
|
||||
return true
|
||||
}
|
||||
default:
|
||||
if h, _, err := net.SplitHostPort(e); err == nil {
|
||||
e = h // the port is not checked
|
||||
}
|
||||
e = strings.Trim(e, "[]")
|
||||
if strings.HasPrefix(e, ".") {
|
||||
e = "*" + e
|
||||
}
|
||||
if matchGlob(e, host) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// matchGlob reports whether s matches pattern, where * stands for any
|
||||
// characters, dots included.
|
||||
func matchGlob(pattern, s string) bool {
|
||||
before, after, ok := strings.Cut(pattern, "*")
|
||||
if !ok {
|
||||
return pattern == s
|
||||
}
|
||||
if !strings.HasPrefix(s, before) {
|
||||
return false
|
||||
}
|
||||
s = s[len(before):]
|
||||
for i := 0; i <= len(s); i++ {
|
||||
if matchGlob(after, s[i:]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func splitList(s string) []string {
|
||||
return strings.FieldsFunc(s, func(r rune) bool {
|
||||
return r == ';' || r == ' ' || r == '\t' || r == '\r' || r == '\n'
|
||||
})
|
||||
}
|
||||
+351
@@ -0,0 +1,351 @@
|
||||
//go:build darwin && !ios && (amd64 || arm64) && !ios
|
||||
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// macOS asks CFNetwork, as Safari does: CFNetworkCopyProxiesForURL applies
|
||||
// the settings of System Settings > Network > Proxies to the URL, with
|
||||
// their exceptions, and names the setup script (PAC file) to run when
|
||||
// there is one, which CFNetworkExecuteProxyAutoConfigurationURL runs on
|
||||
// this thread's run loop.
|
||||
|
||||
// pacTimeout bounds fetching and running a setup script.
|
||||
const pacTimeout = 5 * time.Second
|
||||
|
||||
const (
|
||||
cfStringEncodingUTF8 = 0x08000100
|
||||
cfNumberSInt32Type = 3
|
||||
cfRunLoopRunFinished = 1
|
||||
)
|
||||
|
||||
// CFStreamClientContext.
|
||||
type streamClientContext struct {
|
||||
version int
|
||||
info uintptr
|
||||
retain, release, copyDescription uintptr
|
||||
}
|
||||
|
||||
type cfAPI struct {
|
||||
release func(cf uintptr)
|
||||
typeID func(cf uintptr) uint
|
||||
equal func(a, b uintptr) bool
|
||||
stringTypeID func() uint
|
||||
numberTypeID func() uint
|
||||
dictTypeID func() uint
|
||||
stringCreate func(alloc uintptr, s string, encoding uint32) uintptr
|
||||
stringLength func(s uintptr) int
|
||||
stringMaxSize func(length int, encoding uint32) int
|
||||
stringGet func(s uintptr, buf *byte, size int, encoding uint32) bool
|
||||
numberGet func(n uintptr, typ int, value *int32) bool
|
||||
urlCreate func(alloc, s, base uintptr) uintptr
|
||||
arrayCount func(a uintptr) int
|
||||
arrayAt func(a uintptr, i int) uintptr
|
||||
dictGet func(d, key uintptr) uintptr
|
||||
runLoopCurrent func() uintptr
|
||||
addSource func(rl, source, mode uintptr)
|
||||
removeSource func(rl, source, mode uintptr)
|
||||
invalidate func(source uintptr)
|
||||
runInMode func(mode uintptr, seconds float64, returnAfterSourceHandled bool) int32
|
||||
stop func(rl uintptr)
|
||||
|
||||
copySettings func() uintptr
|
||||
copyProxies func(url, settings uintptr) uintptr
|
||||
runPACURL func(script, url, callback uintptr, ctx *streamClientContext) uintptr
|
||||
runPACScript func(script, url, callback uintptr, ctx *streamClientContext) uintptr
|
||||
|
||||
poolPush, poolPop uintptr
|
||||
|
||||
keyType, keyHost, keyPort, keyPACURL, keyPACScript uintptr
|
||||
typeNone, typeHTTP, typeHTTPS, typeSOCKS, typePACURL, typePACScript uintptr
|
||||
|
||||
// mode is the private run loop mode setup scripts run in, and
|
||||
// callback their completion callback, made once.
|
||||
mode, callback uintptr
|
||||
}
|
||||
|
||||
var cfLazy lazy[*cfAPI]
|
||||
|
||||
// cf returns CoreFoundation's and CFNetwork's functions, or nil.
|
||||
func cf() *cfAPI { return cfLazy.get(loadCF) }
|
||||
|
||||
func loadCF() *cfAPI {
|
||||
open := func(path string) uintptr {
|
||||
h, _ := purego.Dlopen(path, purego.RTLD_LAZY|purego.RTLD_GLOBAL)
|
||||
return h
|
||||
}
|
||||
core := open("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
|
||||
network := open("/System/Library/Frameworks/CFNetwork.framework/CFNetwork")
|
||||
objc := open("/usr/lib/libobjc.A.dylib")
|
||||
if core == 0 || network == 0 || objc == 0 {
|
||||
return nil
|
||||
}
|
||||
a := &cfAPI{}
|
||||
for _, f := range []struct {
|
||||
lib uintptr
|
||||
fn any
|
||||
name string
|
||||
}{
|
||||
{core, &a.release, "CFRelease"},
|
||||
{core, &a.typeID, "CFGetTypeID"},
|
||||
{core, &a.equal, "CFEqual"},
|
||||
{core, &a.stringTypeID, "CFStringGetTypeID"},
|
||||
{core, &a.numberTypeID, "CFNumberGetTypeID"},
|
||||
{core, &a.dictTypeID, "CFDictionaryGetTypeID"},
|
||||
{core, &a.stringCreate, "CFStringCreateWithCString"},
|
||||
{core, &a.stringLength, "CFStringGetLength"},
|
||||
{core, &a.stringMaxSize, "CFStringGetMaximumSizeForEncoding"},
|
||||
{core, &a.stringGet, "CFStringGetCString"},
|
||||
{core, &a.numberGet, "CFNumberGetValue"},
|
||||
{core, &a.urlCreate, "CFURLCreateWithString"},
|
||||
{core, &a.arrayCount, "CFArrayGetCount"},
|
||||
{core, &a.arrayAt, "CFArrayGetValueAtIndex"},
|
||||
{core, &a.dictGet, "CFDictionaryGetValue"},
|
||||
{core, &a.runLoopCurrent, "CFRunLoopGetCurrent"},
|
||||
{core, &a.addSource, "CFRunLoopAddSource"},
|
||||
{core, &a.removeSource, "CFRunLoopRemoveSource"},
|
||||
{core, &a.invalidate, "CFRunLoopSourceInvalidate"},
|
||||
{core, &a.runInMode, "CFRunLoopRunInMode"},
|
||||
{core, &a.stop, "CFRunLoopStop"},
|
||||
{network, &a.copySettings, "CFNetworkCopySystemProxySettings"},
|
||||
{network, &a.copyProxies, "CFNetworkCopyProxiesForURL"},
|
||||
{network, &a.runPACURL, "CFNetworkExecuteProxyAutoConfigurationURL"},
|
||||
{network, &a.runPACScript, "CFNetworkExecuteProxyAutoConfigurationScript"},
|
||||
} {
|
||||
p, err := purego.Dlsym(f.lib, f.name)
|
||||
if err != nil || p == 0 {
|
||||
return nil
|
||||
}
|
||||
purego.RegisterFunc(f.fn, p)
|
||||
}
|
||||
var err error
|
||||
if a.poolPush, err = purego.Dlsym(objc, "objc_autoreleasePoolPush"); err != nil {
|
||||
return nil
|
||||
}
|
||||
if a.poolPop, err = purego.Dlsym(objc, "objc_autoreleasePoolPop"); err != nil {
|
||||
return nil
|
||||
}
|
||||
for _, c := range []struct {
|
||||
v *uintptr
|
||||
name string
|
||||
}{
|
||||
{&a.keyType, "kCFProxyTypeKey"},
|
||||
{&a.keyHost, "kCFProxyHostNameKey"},
|
||||
{&a.keyPort, "kCFProxyPortNumberKey"},
|
||||
{&a.keyPACURL, "kCFProxyAutoConfigurationURLKey"},
|
||||
{&a.keyPACScript, "kCFProxyAutoConfigurationJavaScriptKey"},
|
||||
{&a.typeNone, "kCFProxyTypeNone"},
|
||||
{&a.typeHTTP, "kCFProxyTypeHTTP"},
|
||||
{&a.typeHTTPS, "kCFProxyTypeHTTPS"},
|
||||
{&a.typeSOCKS, "kCFProxyTypeSOCKS"},
|
||||
{&a.typePACURL, "kCFProxyTypeAutoConfigurationURL"},
|
||||
{&a.typePACScript, "kCFProxyTypeAutoConfigurationJavaScript"},
|
||||
} {
|
||||
p, err := purego.Dlsym(network, c.name)
|
||||
if err != nil || p == 0 {
|
||||
return nil
|
||||
}
|
||||
*c.v = **(**uintptr)(unsafe.Pointer(&p)) // a CFStringRef constant
|
||||
}
|
||||
if a.mode = a.stringCreate(0, "github.com/egoist/mygo/netproxy", cfStringEncodingUTF8); a.mode == 0 {
|
||||
return nil
|
||||
}
|
||||
a.callback = purego.NewCallback(pacDone)
|
||||
return a
|
||||
}
|
||||
|
||||
func system(target *url.URL) *url.URL {
|
||||
a := cf()
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
// The autorelease pool and the run loop belong to this thread.
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
pool, _, _ := purego.SyscallN(a.poolPush)
|
||||
defer purego.SyscallN(a.poolPop, pool)
|
||||
|
||||
s := a.stringCreate(0, target.String(), cfStringEncodingUTF8)
|
||||
if s == 0 {
|
||||
return nil
|
||||
}
|
||||
u := a.urlCreate(0, s, 0)
|
||||
a.release(s)
|
||||
if u == 0 {
|
||||
return nil
|
||||
}
|
||||
defer a.release(u)
|
||||
settings := a.copySettings()
|
||||
if settings == 0 {
|
||||
return nil
|
||||
}
|
||||
defer a.release(settings)
|
||||
list := a.copyProxies(u, settings)
|
||||
if list == 0 {
|
||||
return nil
|
||||
}
|
||||
defer a.release(list)
|
||||
return firstSupported(a.proxies(list, u))
|
||||
}
|
||||
|
||||
// proxies converts CFNetwork's list of proxies, an array of dictionaries,
|
||||
// to URLs, running the setup scripts it names for target; with target 0,
|
||||
// as for the list a script returns, it skips them.
|
||||
func (a *cfAPI) proxies(list, target uintptr) []string {
|
||||
var out []string
|
||||
for i := range a.arrayCount(list) {
|
||||
d := a.arrayAt(list, i)
|
||||
if d == 0 || a.typeID(d) != a.dictTypeID() {
|
||||
continue
|
||||
}
|
||||
typ := a.dictGet(d, a.keyType)
|
||||
switch {
|
||||
case typ == 0:
|
||||
case a.equal(typ, a.typeNone):
|
||||
out = append(out, "direct://")
|
||||
case a.equal(typ, a.typeHTTP), a.equal(typ, a.typeHTTPS):
|
||||
// An HTTPS proxy is the proxy of https URLs, spoken to in HTTP.
|
||||
out = append(out, a.server("http", d))
|
||||
case a.equal(typ, a.typeSOCKS):
|
||||
out = append(out, a.server("socks5", d))
|
||||
case target != 0 && a.equal(typ, a.typePACURL):
|
||||
out = append(out, a.runPAC(a.dictGet(d, a.keyPACURL), target, false)...)
|
||||
case target != 0 && a.equal(typ, a.typePACScript):
|
||||
out = append(out, a.runPAC(a.dictGet(d, a.keyPACScript), target, true)...)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// server returns the proxy of dictionary d as scheme://host:port, or ""
|
||||
// without a host.
|
||||
func (a *cfAPI) server(scheme string, d uintptr) string {
|
||||
host := a.goString(a.dictGet(d, a.keyHost))
|
||||
if host == "" {
|
||||
return ""
|
||||
}
|
||||
var port int32
|
||||
if n := a.dictGet(d, a.keyPort); n != 0 && a.typeID(n) == a.numberTypeID() {
|
||||
a.numberGet(n, cfNumberSInt32Type, &port)
|
||||
}
|
||||
if port > 0 {
|
||||
return scheme + "://" + net.JoinHostPort(host, strconv.Itoa(int(port)))
|
||||
}
|
||||
if strings.Contains(host, ":") {
|
||||
host = "[" + host + "]"
|
||||
}
|
||||
return scheme + "://" + host
|
||||
}
|
||||
|
||||
func (a *cfAPI) goString(s uintptr) string {
|
||||
if s == 0 || a.typeID(s) != a.stringTypeID() {
|
||||
return ""
|
||||
}
|
||||
n := a.stringMaxSize(a.stringLength(s), cfStringEncodingUTF8) + 1
|
||||
buf := make([]byte, n)
|
||||
if !a.stringGet(s, &buf[0], n, cfStringEncodingUTF8) {
|
||||
return ""
|
||||
}
|
||||
for i, c := range buf {
|
||||
if c == 0 {
|
||||
return string(buf[:i])
|
||||
}
|
||||
}
|
||||
return string(buf)
|
||||
}
|
||||
|
||||
// Setup scripts' results, by the info of their callback's context.
|
||||
var pacs struct {
|
||||
sync.Mutex
|
||||
next uintptr
|
||||
results map[uintptr]*pacResult
|
||||
}
|
||||
|
||||
type pacResult struct {
|
||||
done bool
|
||||
proxies []string
|
||||
}
|
||||
|
||||
// runPAC runs the setup script at the URL script, or the script itself,
|
||||
// for target and returns the proxies it chose. A script that fails or
|
||||
// takes longer than pacTimeout chooses none.
|
||||
func (a *cfAPI) runPAC(script, target uintptr, isScript bool) []string {
|
||||
if script == 0 {
|
||||
return nil
|
||||
}
|
||||
res := &pacResult{}
|
||||
pacs.Lock()
|
||||
if pacs.results == nil {
|
||||
pacs.results = map[uintptr]*pacResult{}
|
||||
}
|
||||
pacs.next++
|
||||
id := pacs.next
|
||||
pacs.results[id] = res
|
||||
pacs.Unlock()
|
||||
defer func() {
|
||||
pacs.Lock()
|
||||
delete(pacs.results, id)
|
||||
pacs.Unlock()
|
||||
}()
|
||||
|
||||
ctx := &streamClientContext{info: id}
|
||||
var source uintptr // owned, though its name says neither Create nor Copy
|
||||
if isScript {
|
||||
source = a.runPACScript(script, target, a.callback, ctx)
|
||||
} else {
|
||||
source = a.runPACURL(script, target, a.callback, ctx)
|
||||
}
|
||||
if source == 0 {
|
||||
return nil
|
||||
}
|
||||
rl := a.runLoopCurrent()
|
||||
a.addSource(rl, source, a.mode)
|
||||
deadline := time.Now().Add(pacTimeout)
|
||||
for {
|
||||
pacs.Lock()
|
||||
done := res.done
|
||||
pacs.Unlock()
|
||||
left := time.Until(deadline)
|
||||
if done || left <= 0 {
|
||||
break
|
||||
}
|
||||
if a.runInMode(a.mode, left.Seconds(), false) == cfRunLoopRunFinished {
|
||||
break
|
||||
}
|
||||
}
|
||||
// Cancels a script that is still running.
|
||||
a.invalidate(source)
|
||||
a.removeSource(rl, source, a.mode)
|
||||
a.release(source)
|
||||
runtime.KeepAlive(ctx)
|
||||
pacs.Lock()
|
||||
defer pacs.Unlock()
|
||||
return res.proxies
|
||||
}
|
||||
|
||||
// pacDone is the callback of setup scripts, on the run loop of the thread
|
||||
// that runs them. It owns neither the list nor the error.
|
||||
func pacDone(info, list, cfErr uintptr) {
|
||||
a := cf()
|
||||
var proxies []string
|
||||
if cfErr == 0 && list != 0 {
|
||||
proxies = a.proxies(list, 0)
|
||||
}
|
||||
pacs.Lock()
|
||||
if res := pacs.results[info]; res != nil {
|
||||
res.done, res.proxies = true, proxies
|
||||
}
|
||||
pacs.Unlock()
|
||||
a.stop(a.runLoopCurrent())
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
//go:build darwin && !ios && (amd64 || arm64) && !ios
|
||||
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"runtime"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestSystemDarwin asks CFNetwork for the proxy of a URL: whatever the
|
||||
// machine's settings, the answer is a proxy Go can use or none.
|
||||
func TestSystemDarwin(t *testing.T) {
|
||||
if cf() == nil {
|
||||
t.Fatal("CFNetwork did not load")
|
||||
}
|
||||
p := system(&url.URL{Scheme: "https", Host: "example.com", Path: "/"})
|
||||
if p != nil && p.Host == "" {
|
||||
t.Errorf("system = %v, a proxy without a host", p)
|
||||
}
|
||||
t.Logf("system proxy: %v", p)
|
||||
}
|
||||
|
||||
// TestPACScript runs a setup script on this thread's run loop and reads
|
||||
// the proxies it chose.
|
||||
func TestPACScript(t *testing.T) {
|
||||
a := cf()
|
||||
if a == nil {
|
||||
t.Fatal("CFNetwork did not load")
|
||||
}
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
script := a.stringCreate(0, `function FindProxyForURL(url, host) { return "PROXY p.example:8080; SOCKS s.example:1080; DIRECT"; }`, cfStringEncodingUTF8)
|
||||
defer a.release(script)
|
||||
s := a.stringCreate(0, "https://example.com/", cfStringEncodingUTF8)
|
||||
defer a.release(s)
|
||||
target := a.urlCreate(0, s, 0)
|
||||
defer a.release(target)
|
||||
got := a.runPAC(script, target, true)
|
||||
want := []string{"http://p.example:8080", "socks5://s.example:1080", "direct://"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("runPAC = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// Linux asks GIO's default proxy resolver, as WebKitGTK does: GNOME's
|
||||
// settings, KDE's and PAC files through libproxy, the desktop portal in a
|
||||
// sandbox. Without GIO, requests go direct.
|
||||
|
||||
type gioAPI struct {
|
||||
resolver func() uintptr
|
||||
lookup func(resolver uintptr, uri string, cancellable uintptr, err *uintptr) uintptr
|
||||
strfreev func(v uintptr)
|
||||
errorFree func(err uintptr)
|
||||
}
|
||||
|
||||
var gio lazy[*gioAPI]
|
||||
|
||||
func loadGIO() *gioAPI {
|
||||
lib, err := purego.Dlopen("libgio-2.0.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
g := &gioAPI{}
|
||||
// GLib's functions are found through GIO, which links it.
|
||||
if !bind(lib, &g.resolver, "g_proxy_resolver_get_default") ||
|
||||
!bind(lib, &g.lookup, "g_proxy_resolver_lookup") ||
|
||||
!bind(lib, &g.strfreev, "g_strfreev") ||
|
||||
!bind(lib, &g.errorFree, "g_error_free") {
|
||||
return nil
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
func bind(lib uintptr, fn any, name string) bool {
|
||||
p, err := purego.Dlsym(lib, name)
|
||||
if err != nil || p == 0 {
|
||||
return false
|
||||
}
|
||||
purego.RegisterFunc(fn, p)
|
||||
return true
|
||||
}
|
||||
|
||||
func system(target *url.URL) *url.URL {
|
||||
g := gio.get(loadGIO)
|
||||
if g == nil {
|
||||
return nil
|
||||
}
|
||||
r := g.resolver() // not owned
|
||||
if r == 0 {
|
||||
return nil
|
||||
}
|
||||
var gerr uintptr
|
||||
list := g.lookup(r, target.String(), 0, &gerr)
|
||||
if list == 0 {
|
||||
if gerr != 0 {
|
||||
g.errorFree(gerr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
defer g.strfreev(list)
|
||||
var proxies []string
|
||||
for p := *(*unsafe.Pointer)(unsafe.Pointer(&list)); *(*uintptr)(p) != 0; p = unsafe.Add(p, unsafe.Sizeof(uintptr(0))) {
|
||||
proxies = append(proxies, cString(*(*unsafe.Pointer)(p)))
|
||||
}
|
||||
return firstSupported(proxies)
|
||||
}
|
||||
|
||||
func cString(p unsafe.Pointer) string {
|
||||
n := 0
|
||||
for *(*byte)(unsafe.Add(p, n)) != 0 {
|
||||
n++
|
||||
}
|
||||
return string(unsafe.Slice((*byte)(p), n))
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestSystemLinux asks GIO, when it is installed, for the proxy of a URL:
|
||||
// whatever the machine's settings, the answer is a proxy Go can use or
|
||||
// none.
|
||||
func TestSystemLinux(t *testing.T) {
|
||||
if gio.get(loadGIO) == nil {
|
||||
t.Log("no GIO: requests go direct")
|
||||
}
|
||||
p := system(&url.URL{Scheme: "https", Host: "example.com", Path: "/"})
|
||||
if p != nil && p.Host == "" {
|
||||
t.Errorf("system = %v, a proxy without a host", p)
|
||||
}
|
||||
t.Logf("system proxy: %v", p)
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
//go:build !windows && !(darwin && !ios && (amd64 || arm64)) && !(linux && !android && (amd64 || arm64))
|
||||
|
||||
package netproxy
|
||||
|
||||
import "net/url"
|
||||
|
||||
// In browsers the browser makes the requests, through its own proxy; other
|
||||
// systems go direct.
|
||||
func system(*url.URL) *url.URL { return nil }
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Windows reads the user's settings (Settings > Network & internet >
|
||||
// Proxy, the Internet Options of old) with WinHTTP, as Chromium does:
|
||||
// automatic detection (WPAD) and setup scripts (PAC files) first, then the
|
||||
// manual proxy and its bypass list.
|
||||
|
||||
type winHTTP struct {
|
||||
ieConfig, open, setTimeouts, proxyForURL, globalFree *syscall.LazyProc
|
||||
session uintptr
|
||||
}
|
||||
|
||||
var winhttp lazy[*winHTTP]
|
||||
|
||||
// loadWinHTTP loads WinHTTP from the system directory, never from the
|
||||
// app's directory or the search path, and opens a synchronous session for
|
||||
// setup scripts, kept for the process.
|
||||
func loadWinHTTP() *winHTTP {
|
||||
kernel32 := syscall.NewLazyDLL("kernel32.dll") // a KnownDLL
|
||||
buf := make([]uint16, syscall.MAX_PATH)
|
||||
n, _, _ := kernel32.NewProc("GetSystemDirectoryW").Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
|
||||
if n == 0 || int(n) > len(buf) {
|
||||
return nil
|
||||
}
|
||||
dll := syscall.NewLazyDLL(syscall.UTF16ToString(buf[:n]) + `\winhttp.dll`)
|
||||
w := &winHTTP{
|
||||
ieConfig: dll.NewProc("WinHttpGetIEProxyConfigForCurrentUser"),
|
||||
open: dll.NewProc("WinHttpOpen"),
|
||||
setTimeouts: dll.NewProc("WinHttpSetTimeouts"),
|
||||
proxyForURL: dll.NewProc("WinHttpGetProxyForUrl"),
|
||||
globalFree: kernel32.NewProc("GlobalFree"),
|
||||
}
|
||||
for _, p := range []*syscall.LazyProc{w.ieConfig, w.open, w.setTimeouts, w.proxyForURL, w.globalFree} {
|
||||
if p.Find() != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
agent, _ := syscall.UTF16PtrFromString("mygo")
|
||||
w.session, _, _ = w.open.Call(uintptr(unsafe.Pointer(agent)), winhttpAccessTypeNoProxy, 0, 0, 0)
|
||||
if w.session != 0 {
|
||||
// Bounds fetching a setup script, which may not answer.
|
||||
w.setTimeouts.Call(w.session, 5000, 5000, 5000, 5000)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
const (
|
||||
winhttpAccessTypeNoProxy = 1
|
||||
winhttpAccessTypeNamedProxy = 3
|
||||
|
||||
winhttpAutoproxyAutoDetect = 0x1
|
||||
winhttpAutoproxyConfigURL = 0x2
|
||||
winhttpAutoDetectTypeDHCP = 0x1
|
||||
winhttpAutoDetectTypeDNSA = 0x2
|
||||
)
|
||||
|
||||
// WINHTTP_CURRENT_USER_IE_PROXY_CONFIG. Its strings are the caller's, freed
|
||||
// with GlobalFree.
|
||||
type ieProxyConfig struct {
|
||||
autoDetect int32 // BOOL
|
||||
autoConfigURL *uint16
|
||||
proxy *uint16
|
||||
proxyBypass *uint16
|
||||
}
|
||||
|
||||
// WINHTTP_AUTOPROXY_OPTIONS.
|
||||
type autoProxyOptions struct {
|
||||
flags uint32
|
||||
autoDetectFlags uint32
|
||||
autoConfigURL *uint16
|
||||
reserved1 uintptr
|
||||
reserved2 uint32
|
||||
autoLogonIfChallenged int32 // BOOL
|
||||
}
|
||||
|
||||
// WINHTTP_PROXY_INFO. Its strings are the caller's, freed with GlobalFree.
|
||||
type proxyInfo struct {
|
||||
accessType uint32
|
||||
proxy *uint16
|
||||
proxyBypass *uint16
|
||||
}
|
||||
|
||||
func system(target *url.URL) *url.URL {
|
||||
w := winhttp.get(loadWinHTTP)
|
||||
if w == nil {
|
||||
return nil
|
||||
}
|
||||
var cfg ieProxyConfig
|
||||
if ok, _, _ := w.ieConfig.Call(uintptr(unsafe.Pointer(&cfg))); ok == 0 {
|
||||
return nil
|
||||
}
|
||||
pac, proxy, bypass := w.take(cfg.autoConfigURL), w.take(cfg.proxy), w.take(cfg.proxyBypass)
|
||||
if cfg.autoDetect != 0 || pac != "" {
|
||||
if p, ok := w.auto(target, cfg.autoDetect != 0, pac); ok {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return winStatic(proxy, bypass, target)
|
||||
}
|
||||
|
||||
// auto runs the setup script, the one detection finds or the one at pac.
|
||||
// It reports false when there is none or it fails.
|
||||
func (w *winHTTP) auto(target *url.URL, detect bool, pac string) (*url.URL, bool) {
|
||||
if w.session == 0 {
|
||||
return nil, false
|
||||
}
|
||||
opts := autoProxyOptions{autoLogonIfChallenged: 1}
|
||||
if detect {
|
||||
opts.flags |= winhttpAutoproxyAutoDetect
|
||||
opts.autoDetectFlags = winhttpAutoDetectTypeDHCP | winhttpAutoDetectTypeDNSA
|
||||
}
|
||||
if pac != "" {
|
||||
u, err := syscall.UTF16PtrFromString(pac)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
opts.flags |= winhttpAutoproxyConfigURL
|
||||
opts.autoConfigURL = u
|
||||
}
|
||||
u, err := syscall.UTF16PtrFromString(target.String())
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
var info proxyInfo
|
||||
if ok, _, _ := w.proxyForURL.Call(w.session, uintptr(unsafe.Pointer(u)), uintptr(unsafe.Pointer(&opts)), uintptr(unsafe.Pointer(&info))); ok == 0 {
|
||||
return nil, false
|
||||
}
|
||||
proxy, bypass := w.take(info.proxy), w.take(info.proxyBypass)
|
||||
if info.accessType != winhttpAccessTypeNamedProxy {
|
||||
return nil, true
|
||||
}
|
||||
return winStatic(proxy, bypass, target), true
|
||||
}
|
||||
|
||||
// take returns the string WinHTTP allocated and frees it.
|
||||
func (w *winHTTP) take(p *uint16) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
n := 0
|
||||
for *(*uint16)(unsafe.Add(unsafe.Pointer(p), 2*n)) != 0 {
|
||||
n++
|
||||
}
|
||||
s := syscall.UTF16ToString(unsafe.Slice(p, n))
|
||||
w.globalFree.Call(uintptr(unsafe.Pointer(p)))
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package netproxy
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// TestStructLayout checks the structures WinHTTP fills against their C
|
||||
// layout on 64-bit Windows.
|
||||
func TestStructLayout(t *testing.T) {
|
||||
if unsafe.Sizeof(uintptr(0)) != 8 {
|
||||
t.Skip("64-bit layouts")
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
got, want uintptr
|
||||
}{
|
||||
{"WINHTTP_CURRENT_USER_IE_PROXY_CONFIG", unsafe.Sizeof(ieProxyConfig{}), 32},
|
||||
{"WINHTTP_AUTOPROXY_OPTIONS", unsafe.Sizeof(autoProxyOptions{}), 32},
|
||||
{"WINHTTP_AUTOPROXY_OPTIONS.fAutoLogonIfChallenged", unsafe.Offsetof(autoProxyOptions{}.autoLogonIfChallenged), 28},
|
||||
{"WINHTTP_PROXY_INFO", unsafe.Sizeof(proxyInfo{}), 24},
|
||||
} {
|
||||
if tc.got != tc.want {
|
||||
t.Errorf("%s: %d, want %d", tc.name, tc.got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSystemWindows asks WinHTTP for the proxy of a URL: whatever the
|
||||
// machine's settings, the answer is a proxy Go can use or none.
|
||||
func TestSystemWindows(t *testing.T) {
|
||||
if winhttp.get(loadWinHTTP) == nil {
|
||||
t.Fatal("WinHTTP did not load")
|
||||
}
|
||||
p := system(&url.URL{Scheme: "https", Host: "example.com", Path: "/"})
|
||||
if p != nil && p.Host == "" {
|
||||
t.Errorf("system = %v, a proxy without a host", p)
|
||||
}
|
||||
t.Logf("system proxy: %v", p)
|
||||
}
|
||||
Reference in new issue
Block a user