mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-11-25 18:11:50 +08:00
fix: 代理池恢复需探测确认并受耗尽门控、转发器认证与缓冲、掩码回写与删除收尾、补测
This commit is contained in:
1 parent
45514b3586
commit
2b30c47414
7 files changed
+621
-67
No files matched your search
@@ -341,6 +341,7 @@ func (s *Server) testEgressProxy(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
GlobalProxy string `json:"global_proxy"`
|
||||
ProbeURL string `json:"probe_url"` // 可选:覆盖默认探测地址
|
||||
Resume bool `json:"resume"` // manual settings probe may release paused_by_proxy tasks
|
||||
}
|
||||
// 请求体只有一个地址,给个上限,免得被塞大 payload。
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
|
||||
@@ -369,7 +370,10 @@ func (s *Server) testEgressProxy(w http.ResponseWriter, r *http.Request) {
|
||||
// 整体上限 40s:单次 Timeout 只兜一次,不兜总量;前端 fetch 没有超时。
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second)
|
||||
defer cancel()
|
||||
proxyGuards := s.snapshotProxyReconnectGuards(false)
|
||||
var proxyGuards map[string]proxyReconnectGuard
|
||||
if req.Resume {
|
||||
proxyGuards = s.snapshotProxyReconnectGuardsWithExhausted(false, true)
|
||||
}
|
||||
|
||||
configuredProxy := strings.TrimSpace(req.GlobalProxy)
|
||||
if strings.Contains(configuredProxy, "***") || strings.Contains(configuredProxy, "******") {
|
||||
@@ -420,10 +424,10 @@ func (s *Server) testEgressProxy(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
rep.OK = judgeEgress(rep)
|
||||
rep.Warnings = egressWarnings(rep, pending, savedProxy)
|
||||
if rep.OK && !pending {
|
||||
// The settings page uses this endpoint for its manual "测试代理" action.
|
||||
// A successful probe is the same signal as an automatic reconnect success,
|
||||
// but it must never consume an automatic attempt.
|
||||
if req.Resume && rep.OK && !pending {
|
||||
// The navbar uses the same probe endpoint for display-only polling but
|
||||
// omits resume. Only an explicit settings-page test can release the
|
||||
// guarded paused_by_proxy tasks.
|
||||
s.proxyReconnectSuccessWithGuards(proxyGuards, nil)
|
||||
}
|
||||
writeJSON(w, 200, rep)
|
||||
|
||||
+103
-14
@@ -11,6 +11,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
@@ -24,6 +25,10 @@ type dynamicForwardProxy struct {
|
||||
direct func() bool
|
||||
server *http.Server
|
||||
once sync.Once
|
||||
mu sync.Mutex
|
||||
conns map[net.Conn]struct{}
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func newDynamicForwardProxy(current func() string) (*dynamicForwardProxy, error) {
|
||||
@@ -31,8 +36,9 @@ func newDynamicForwardProxy(current func() string) (*dynamicForwardProxy, error)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := &dynamicForwardProxy{ln: ln, addr: "http://" + ln.Addr().String(), current: current, direct: func() bool { return true }}
|
||||
p.server = &http.Server{Handler: http.HandlerFunc(p.serveHTTP)}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
p := &dynamicForwardProxy{ln: ln, addr: "http://" + ln.Addr().String(), current: current, direct: func() bool { return true }, conns: map[net.Conn]struct{}{}, ctx: ctx, cancel: cancel}
|
||||
p.server = &http.Server{Handler: http.HandlerFunc(p.serveHTTP), BaseContext: func(net.Listener) context.Context { return ctx }}
|
||||
go p.server.Serve(ln)
|
||||
return p, nil
|
||||
}
|
||||
@@ -47,10 +53,31 @@ func (p *dynamicForwardProxy) Close() error {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
p.once.Do(func() { _ = p.server.Close() })
|
||||
p.once.Do(func() {
|
||||
p.cancel()
|
||||
p.mu.Lock()
|
||||
for c := range p.conns {
|
||||
_ = c.Close()
|
||||
}
|
||||
p.conns = nil
|
||||
p.mu.Unlock()
|
||||
_ = p.server.Close()
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *dynamicForwardProxy) track(c net.Conn) func() {
|
||||
if c == nil {
|
||||
return func() {}
|
||||
}
|
||||
p.mu.Lock()
|
||||
if p.conns != nil {
|
||||
p.conns[c] = struct{}{}
|
||||
}
|
||||
p.mu.Unlock()
|
||||
return func() { p.mu.Lock(); delete(p.conns, c); p.mu.Unlock() }
|
||||
}
|
||||
|
||||
func (p *dynamicForwardProxy) serveHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodConnect {
|
||||
p.serveConnect(w, r)
|
||||
@@ -74,7 +101,9 @@ func (p *dynamicForwardProxy) serveHTTP(w http.ResponseWriter, r *http.Request)
|
||||
http.Error(w, "proxy unavailable", 502)
|
||||
return
|
||||
}
|
||||
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { return d.Dial(network, addr) }
|
||||
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return dialProxyContext(ctx, d, network, addr)
|
||||
}
|
||||
} else {
|
||||
tr.Proxy = http.ProxyURL(u)
|
||||
}
|
||||
@@ -117,7 +146,7 @@ func (p *dynamicForwardProxy) serveConnect(w http.ResponseWriter, r *http.Reques
|
||||
var conn net.Conn
|
||||
var err error
|
||||
if up == "" {
|
||||
conn, err = (&net.Dialer{}).DialContext(r.Context(), "tcp", target)
|
||||
conn, err = (&net.Dialer{Timeout: 10 * time.Second}).DialContext(r.Context(), "tcp", target)
|
||||
} else {
|
||||
u, e := url.Parse(up)
|
||||
if e != nil {
|
||||
@@ -127,7 +156,7 @@ func (p *dynamicForwardProxy) serveConnect(w http.ResponseWriter, r *http.Reques
|
||||
if e != nil {
|
||||
err = e
|
||||
} else {
|
||||
conn, err = d.Dial("tcp", target)
|
||||
conn, err = dialProxyContext(r.Context(), d, "tcp", target)
|
||||
}
|
||||
} else {
|
||||
conn, err = dialHTTPConnect(r.Context(), u, target)
|
||||
@@ -137,7 +166,6 @@ func (p *dynamicForwardProxy) serveConnect(w http.ResponseWriter, r *http.Reques
|
||||
http.Error(w, "proxy unavailable", 502)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
h, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "proxy unavailable", 500)
|
||||
@@ -147,11 +175,22 @@ func (p *dynamicForwardProxy) serveConnect(w http.ResponseWriter, r *http.Reques
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
removeClient := p.track(client)
|
||||
defer removeClient()
|
||||
removeUpstream := p.track(conn)
|
||||
defer removeUpstream()
|
||||
defer client.Close()
|
||||
defer conn.Close()
|
||||
_, _ = rw.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
_ = rw.Flush()
|
||||
go io.Copy(conn, client)
|
||||
_, _ = io.Copy(client, conn)
|
||||
clientReader := io.Reader(client)
|
||||
if rw.Reader != nil && rw.Reader.Buffered() > 0 {
|
||||
clientReader = io.MultiReader(rw.Reader, client)
|
||||
}
|
||||
done := make(chan struct{}, 2)
|
||||
go func() { _, _ = io.Copy(conn, clientReader); _ = conn.Close(); done <- struct{}{} }()
|
||||
go func() { _, _ = io.Copy(client, conn); _ = client.Close(); done <- struct{}{} }()
|
||||
<-done
|
||||
}
|
||||
|
||||
func socksDialer(u *url.URL) (proxy.Dialer, error) {
|
||||
@@ -160,11 +199,42 @@ func socksDialer(u *url.URL) (proxy.Dialer, error) {
|
||||
pw, _ := u.User.Password()
|
||||
auth = &proxy.Auth{User: u.User.Username(), Password: pw}
|
||||
}
|
||||
return proxy.SOCKS5("tcp", u.Host, auth, &net.Dialer{})
|
||||
return proxy.SOCKS5("tcp", u.Host, auth, &net.Dialer{Timeout: 10 * time.Second})
|
||||
}
|
||||
|
||||
func dialProxyContext(ctx context.Context, d proxy.Dialer, network, addr string) (net.Conn, error) {
|
||||
if cd, ok := d.(proxy.ContextDialer); ok {
|
||||
return cd.DialContext(ctx, network, addr)
|
||||
}
|
||||
type result struct {
|
||||
c net.Conn
|
||||
err error
|
||||
}
|
||||
ch := make(chan result, 1)
|
||||
go func() { c, err := d.Dial(network, addr); ch <- result{c, err} }()
|
||||
select {
|
||||
case r := <-ch:
|
||||
return r.c, r.err
|
||||
case <-ctx.Done():
|
||||
go func() {
|
||||
r := <-ch
|
||||
if r.c != nil {
|
||||
_ = r.c.Close()
|
||||
}
|
||||
}()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
type bufferedConn struct {
|
||||
net.Conn
|
||||
reader *bufio.Reader
|
||||
}
|
||||
|
||||
func (c *bufferedConn) Read(p []byte) (int, error) { return c.reader.Read(p) }
|
||||
|
||||
func dialHTTPConnect(ctx context.Context, u *url.URL, target string) (net.Conn, error) {
|
||||
d := &net.Dialer{}
|
||||
d := &net.Dialer{Timeout: 10 * time.Second}
|
||||
addr := u.Host
|
||||
if !strings.Contains(addr, ":") {
|
||||
addr += ":80"
|
||||
@@ -185,14 +255,33 @@ func dialHTTPConnect(ctx context.Context, u *url.URL, target string) (net.Conn,
|
||||
if u.User != nil {
|
||||
req := &http.Request{Header: http.Header{}}
|
||||
req.SetBasicAuth(u.User.Username(), func() string { p, _ := u.User.Password(); return p }())
|
||||
fmt.Fprintf(br, "Proxy-Authorization: %s\r\n", req.Header.Get("Proxy-Authorization"))
|
||||
fmt.Fprintf(br, "Proxy-Authorization: %s\r\n", req.Header.Get("Authorization"))
|
||||
}
|
||||
fmt.Fprint(br, "\r\n")
|
||||
if err := br.Flush(); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.ReadResponse(br.Reader, &http.Request{Method: http.MethodConnect})
|
||||
readCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
type responseResult struct {
|
||||
resp *http.Response
|
||||
err error
|
||||
}
|
||||
readDone := make(chan responseResult, 1)
|
||||
go func() {
|
||||
resp, err := http.ReadResponse(br.Reader, &http.Request{Method: http.MethodConnect})
|
||||
readDone <- responseResult{resp: resp, err: err}
|
||||
}()
|
||||
var rr responseResult
|
||||
select {
|
||||
case rr = <-readDone:
|
||||
case <-readCtx.Done():
|
||||
_ = conn.Close()
|
||||
<-readDone
|
||||
return nil, readCtx.Err()
|
||||
}
|
||||
resp, err := rr.resp, rr.err
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
@@ -201,5 +290,5 @@ func dialHTTPConnect(ctx context.Context, u *url.URL, target string) (net.Conn,
|
||||
_ = conn.Close()
|
||||
return nil, fmt.Errorf("upstream CONNECT: %s", resp.Status)
|
||||
}
|
||||
return conn, nil
|
||||
return &bufferedConn{Conn: conn, reader: br.Reader}, nil
|
||||
}
|
||||
+17
-17
@@ -65,6 +65,10 @@ type proxyReconnectGuard struct {
|
||||
}
|
||||
|
||||
func (s *Server) snapshotProxyReconnectGuards(checkAttempt bool) map[string]proxyReconnectGuard {
|
||||
return s.snapshotProxyReconnectGuardsWithExhausted(checkAttempt, false)
|
||||
}
|
||||
|
||||
func (s *Server) snapshotProxyReconnectGuardsWithExhausted(checkAttempt, includeExhausted bool) map[string]proxyReconnectGuard {
|
||||
guards := make(map[string]proxyReconnectGuard)
|
||||
if s == nil || s.m == nil {
|
||||
return guards
|
||||
@@ -74,6 +78,9 @@ func (s *Server) snapshotProxyReconnectGuards(checkAttempt bool) map[string]prox
|
||||
if st.PauseReason != "paused_by_proxy" {
|
||||
continue
|
||||
}
|
||||
if st.ReconnectExhausted && !includeExhausted {
|
||||
continue
|
||||
}
|
||||
guards[t.ID] = proxyReconnectGuard{
|
||||
generation: st.ReconnectGeneration,
|
||||
attempt: st.ReconnectAttempt,
|
||||
@@ -252,22 +259,15 @@ func (s *Server) proxyReconnectTick() {
|
||||
}
|
||||
if s.m.proxyPool != nil && len(s.m.proxyPoolEntries()) > 0 {
|
||||
active := s.m.proxyPoolActiveID()
|
||||
found := false
|
||||
for _, e := range s.m.proxyPoolEntries() {
|
||||
if e.ID == active && e.Enabled && e.Health == "healthy" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if e.ID == active {
|
||||
found = true
|
||||
s.proxyPoolTick()
|
||||
return
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
s.proxyPoolTick()
|
||||
return
|
||||
}
|
||||
// Pool-managed reconnects are driven by a confirmed pool probe. Do not
|
||||
// run the per-task reconnect loop against an entry that merely still says
|
||||
// healthy: that would resume exhausted tasks without a fresh probe and
|
||||
// reset their attempt budget on the next failure. The pool tick also
|
||||
// handles a missing/cooling active member and can switch to another
|
||||
// confirmed healthy member before calling the guarded resume path.
|
||||
_ = active
|
||||
s.proxyPoolTick()
|
||||
return
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
max, interval := s.proxyReconnectConfig()
|
||||
@@ -424,7 +424,7 @@ func (s *Server) testTaskProxy(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
proxy := strings.TrimSpace(s.m.GlobalProxy())
|
||||
guards := s.snapshotProxyReconnectGuards(false)
|
||||
guards := s.snapshotProxyReconnectGuardsWithExhausted(false, true)
|
||||
if proxy == "" {
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "direct": true})
|
||||
s.proxyReconnectSuccessWithGuards(guards, nil)
|
||||
|
||||
+131
-27
@@ -137,9 +137,10 @@ type proxyPoolState struct {
|
||||
|
||||
func (m *Manager) initProxyPool() {
|
||||
m.proxyPool = &proxyPoolState{}
|
||||
if raw, ok, _ := m.pg.GetSetting(settingProxyPool); ok && strings.TrimSpace(raw) != "" {
|
||||
persistedPool, poolSettingPresent, _ := m.pg.GetSetting(settingProxyPool)
|
||||
if poolSettingPresent && strings.TrimSpace(persistedPool) != "" {
|
||||
var p proxyPoolPersist
|
||||
if json.Unmarshal([]byte(raw), &p) == nil {
|
||||
if json.Unmarshal([]byte(persistedPool), &p) == nil {
|
||||
m.proxyPool.entries, m.proxyPool.active = p.Entries, p.Active
|
||||
}
|
||||
}
|
||||
@@ -148,18 +149,55 @@ func (m *Manager) initProxyPool() {
|
||||
m.proxyPool.active = strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
if len(m.proxyPool.entries) == 0 && strings.TrimSpace(m.globalProxy) != "" {
|
||||
if len(m.proxyPool.entries) == 0 && !poolSettingPresent && strings.TrimSpace(m.globalProxy) != "" {
|
||||
m.proxyPool.entries = []proxyPoolEntry{{ProxyPoolEntry: ProxyPoolEntry{ID: "proxy-legacy", URL: maskSecrets(m.globalProxy), Enabled: true, Health: "healthy"}, RawURL: m.globalProxy}}
|
||||
m.proxyPool.active = "proxy-legacy"
|
||||
_ = m.persistProxyPoolLocked()
|
||||
}
|
||||
if m.proxyPool.active != "" {
|
||||
if len(m.proxyPool.entries) == 0 && poolSettingPresent {
|
||||
m.globalProxy = ""
|
||||
m.proxyPool.active = ""
|
||||
_ = m.pg.SetSetting(settingGlobalProxy, "")
|
||||
_ = m.pg.SetSetting(settingProxyPoolActive, "")
|
||||
} else if len(m.proxyPool.entries) > 0 {
|
||||
chosen := ""
|
||||
for _, e := range m.proxyPool.entries {
|
||||
if e.ID == m.proxyPool.active {
|
||||
m.globalProxy = e.RawURL
|
||||
if e.ID == m.proxyPool.active && e.Enabled {
|
||||
chosen = e.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
if chosen == "" {
|
||||
for _, e := range m.proxyPool.entries {
|
||||
if e.Enabled && e.Health == "healthy" {
|
||||
chosen = e.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if chosen == "" {
|
||||
for _, e := range m.proxyPool.entries {
|
||||
if e.Enabled && e.RawURL != "" {
|
||||
chosen = e.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if chosen == "" {
|
||||
m.globalProxy, m.proxyPool.active = "", ""
|
||||
_ = m.pg.SetSetting(settingGlobalProxy, "")
|
||||
_ = m.pg.SetSetting(settingProxyPoolActive, "")
|
||||
} else {
|
||||
m.proxyPool.active = chosen
|
||||
for _, e := range m.proxyPool.entries {
|
||||
if e.ID == chosen {
|
||||
m.globalProxy = e.RawURL
|
||||
break
|
||||
}
|
||||
}
|
||||
_ = m.pg.SetSetting(settingProxyPoolActive, chosen)
|
||||
_ = m.pg.SetSetting(settingGlobalProxy, m.globalProxy)
|
||||
}
|
||||
}
|
||||
m.proxyPoolConfigured.Store(len(m.proxyPool.entries) > 0)
|
||||
}
|
||||
@@ -226,6 +264,14 @@ func (m *Manager) setProxyPoolEntries(entries []proxyPoolEntry, active string) e
|
||||
return m.applyActiveProxyLocked(e.ID, "reconnect")
|
||||
}
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Enabled && e.RawURL != "" {
|
||||
return m.applyActiveProxyLockedWithHealth(e.ID, "reconnect", true)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(m.GlobalProxy()) != "" {
|
||||
return m.applyActiveProxyLocked("", "reconnect")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, e := range entries {
|
||||
@@ -237,9 +283,13 @@ func (m *Manager) setProxyPoolEntries(entries []proxyPoolEntry, active string) e
|
||||
}
|
||||
|
||||
func (m *Manager) applyActiveProxyLocked(id, reason string) error {
|
||||
return m.applyActiveProxyLockedWithHealth(id, reason, false)
|
||||
}
|
||||
|
||||
func (m *Manager) applyActiveProxyLockedWithHealth(id, reason string, allowUnhealthy bool) error {
|
||||
var next string
|
||||
for _, e := range m.proxyPool.entries {
|
||||
if e.ID == id && e.Enabled && e.Health == "healthy" {
|
||||
if e.ID == id && e.Enabled && (allowUnhealthy || e.Health == "healthy") {
|
||||
next = e.RawURL
|
||||
break
|
||||
}
|
||||
@@ -355,7 +405,10 @@ func (m *Manager) markProxyProbeLocked(id string, res egressProbeResult) {
|
||||
} else {
|
||||
e.ConsecutiveFailures++
|
||||
e.LastError = maskSecrets(res.Error)
|
||||
threshold := proxyIntSetting(m.pg, settingProxyHealthThreshold, defaultProxyHealthThreshold)
|
||||
threshold := defaultProxyHealthThreshold
|
||||
if m.pg != nil {
|
||||
threshold = proxyIntSetting(m.pg, settingProxyHealthThreshold, defaultProxyHealthThreshold)
|
||||
}
|
||||
if e.ConsecutiveFailures >= threshold {
|
||||
e.Health = "unhealthy-cooling"
|
||||
}
|
||||
@@ -488,7 +541,7 @@ func (s *Server) proxyPoolTickLocked(forceHealth bool) {
|
||||
}
|
||||
s.m.proxyPool.mu.Unlock()
|
||||
if !healthDue && !forceHealth {
|
||||
s.reconcileProxyPoolAfterProbe()
|
||||
s.reconcileProxyPoolAfterProbe(false)
|
||||
return
|
||||
}
|
||||
entries := s.m.proxyPoolEntries()
|
||||
@@ -496,6 +549,9 @@ func (s *Server) proxyPoolTickLocked(forceHealth bool) {
|
||||
if sem == nil {
|
||||
sem = make(chan struct{}, proxyPoolMaxProbeConcurrency)
|
||||
}
|
||||
activeAtProbe := s.m.proxyPoolActiveID()
|
||||
probeResults := make(map[string]bool, len(entries))
|
||||
var probeMu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for _, e := range entries {
|
||||
if !e.Enabled {
|
||||
@@ -516,13 +572,19 @@ func (s *Server) proxyPoolTickLocked(forceHealth bool) {
|
||||
defer func() { <-sem }()
|
||||
res := s.runProxyProbe(s.ctx, e.RawURL, "", defaultEgressProbes, proxyPoolProbeTimeout)
|
||||
s.m.markProxyProbe(e.ID, res)
|
||||
probeMu.Lock()
|
||||
probeResults[e.ID] = res.OK
|
||||
probeMu.Unlock()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
s.reconcileProxyPoolAfterProbe()
|
||||
probeMu.Lock()
|
||||
confirmed := probeResults[activeAtProbe]
|
||||
probeMu.Unlock()
|
||||
s.reconcileProxyPoolAfterProbe(confirmed)
|
||||
}
|
||||
|
||||
func (s *Server) reconcileProxyPoolAfterProbe() {
|
||||
func (s *Server) reconcileProxyPoolAfterProbe(activeConfirmed bool) {
|
||||
entries := s.m.proxyPoolEntries()
|
||||
activeID := s.m.proxyPoolActiveID()
|
||||
activeHealthy := false
|
||||
@@ -532,10 +594,13 @@ func (s *Server) reconcileProxyPoolAfterProbe() {
|
||||
break
|
||||
}
|
||||
}
|
||||
if activeHealthy {
|
||||
if activeHealthy && activeConfirmed {
|
||||
s.proxyReconnectSuccess()
|
||||
return
|
||||
}
|
||||
if activeHealthy {
|
||||
return
|
||||
}
|
||||
s.m.proxyPool.mu.Lock()
|
||||
id := s.m.selectHealthyLocked(activeID)
|
||||
var err error
|
||||
@@ -585,16 +650,17 @@ func (s *Server) handleProxyPoolFailure(cause error) bool {
|
||||
defer s.proxyPoolTickMu.Unlock()
|
||||
s.m.proxyPool.mu.Lock()
|
||||
defer s.m.proxyPool.mu.Unlock()
|
||||
if s.m.GlobalProxy() != cur {
|
||||
return false
|
||||
}
|
||||
active := s.m.proxyPool.active
|
||||
currentChanged := s.m.GlobalProxy() != cur
|
||||
for _, e := range s.m.proxyPool.entries {
|
||||
if e.ID == active && e.RawURL == cur {
|
||||
if e.RawURL == cur {
|
||||
s.m.markProxyProbeLocked(e.ID, res)
|
||||
break
|
||||
}
|
||||
}
|
||||
if currentChanged {
|
||||
return true
|
||||
}
|
||||
if onFailure {
|
||||
if id := s.m.selectHealthyLocked(active); id != "" && id != active {
|
||||
if err := s.m.applyActiveProxyLocked(id, "failure"); err == nil {
|
||||
@@ -733,13 +799,23 @@ func mergeMaskedProxyURL(raw, old string) (string, error) {
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s", maskSecrets(err.Error()))
|
||||
}
|
||||
if ou, _ := traffic.ValidateProxyURL(old); ou != nil && nu.User != nil {
|
||||
pw, _ := nu.User.Password()
|
||||
if strings.Contains(pw, "***") || strings.Contains(pw, "******") {
|
||||
if oldpw, ok := ou.User.Password(); ok {
|
||||
nu.User = url.UserPassword(nu.User.Username(), oldpw)
|
||||
if ou, _ := traffic.ValidateProxyURL(old); ou != nil && nu.User != nil && ou.User != nil {
|
||||
newUser := nu.User.Username()
|
||||
newPW, hasNewPW := nu.User.Password()
|
||||
maskedUser := newUser == "***" || newUser == "******"
|
||||
maskedPW := hasNewPW && (strings.Contains(newPW, "***") || strings.Contains(newPW, "******"))
|
||||
if maskedUser {
|
||||
oldPW, hasOldPW := ou.User.Password()
|
||||
if hasOldPW {
|
||||
nu.User = url.UserPassword(ou.User.Username(), oldPW)
|
||||
} else {
|
||||
nu.User = url.User(nu.User.Username())
|
||||
nu.User = url.User(ou.User.Username())
|
||||
}
|
||||
} else if maskedPW {
|
||||
if oldPW, hasOldPW := ou.User.Password(); hasOldPW {
|
||||
nu.User = url.UserPassword(newUser, oldPW)
|
||||
} else {
|
||||
nu.User = url.User(newUser)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -769,6 +845,7 @@ func (s *Server) updateProxyPool(w http.ResponseWriter, r *http.Request) {
|
||||
if e.ID != id {
|
||||
continue
|
||||
}
|
||||
oldEntry := *e
|
||||
oldRaw := e.RawURL
|
||||
if req.URL != nil {
|
||||
raw, err := mergeMaskedProxyURL(*req.URL, oldRaw)
|
||||
@@ -778,6 +855,11 @@ func (s *Server) updateProxyPool(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
e.RawURL, e.URL = raw, maskSecrets(raw)
|
||||
if e.ID == s.m.proxyPool.active && e.Enabled && raw != "" {
|
||||
// A validated edit replaces the endpoint and starts a fresh health round,
|
||||
// including when the old endpoint was cooling down.
|
||||
e.Health, e.ConsecutiveFailures, e.LastError = "healthy", 0, ""
|
||||
}
|
||||
}
|
||||
if req.Name != nil {
|
||||
e.Name = strings.TrimSpace(*req.Name)
|
||||
@@ -796,8 +878,8 @@ func (s *Server) updateProxyPool(w http.ResponseWriter, r *http.Request) {
|
||||
if s.m.proxyPool.active == id {
|
||||
if req.URL != nil || req.Enabled != nil {
|
||||
if e.Enabled && e.RawURL != "" {
|
||||
if err := s.m.applyActiveProxyLocked(id, "manual"); err != nil {
|
||||
e.RawURL, e.URL = oldRaw, maskSecrets(oldRaw)
|
||||
if err := s.m.applyActiveProxyLockedWithHealth(id, "manual", req.URL != nil); err != nil {
|
||||
*e = oldEntry
|
||||
s.m.proxyPool.mu.Unlock()
|
||||
writeErr(w, 400, maskSecrets(err.Error()))
|
||||
return
|
||||
@@ -866,8 +948,30 @@ func (s *Server) deleteProxyPool(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
s.m.proxyPool.active = ""
|
||||
needPause = true
|
||||
// Keep runtime traffic attached to a surviving pool member even when
|
||||
// every remaining member is cooling down; never retain the deleted URL.
|
||||
next := ""
|
||||
for _, e := range s.m.proxyPool.entries {
|
||||
if e.Enabled && e.RawURL != "" {
|
||||
next = e.ID
|
||||
break
|
||||
}
|
||||
}
|
||||
if next != "" {
|
||||
if err := s.m.applyActiveProxyLockedWithHealth(next, "manual", true); err != nil {
|
||||
s.m.proxyPool.mu.Unlock()
|
||||
writeErr(w, 500, maskSecrets(err.Error()))
|
||||
return
|
||||
}
|
||||
needPause = true
|
||||
} else {
|
||||
if err := s.m.applyActiveProxyLocked("", "manual"); err != nil {
|
||||
s.m.proxyPool.mu.Unlock()
|
||||
writeErr(w, 500, maskSecrets(err.Error()))
|
||||
return
|
||||
}
|
||||
needPause = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := s.m.persistProxyPoolLocked(); err != nil {
|
||||
@@ -900,7 +1004,7 @@ func (s *Server) testProxyPoolEntry(w http.ResponseWriter, r *http.Request) {
|
||||
res := s.runProxyProbe(r.Context(), e.RawURL, "", defaultEgressProbes, proxyPoolProbeTimeout)
|
||||
s.m.markProxyProbe(id, res)
|
||||
if res.OK {
|
||||
s.reconcileProxyPoolAfterProbe()
|
||||
s.reconcileProxyPoolAfterProbe(id == s.m.proxyPoolActiveID())
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": res.OK, "result": res})
|
||||
return
|
||||
|
||||
+355
-3
@@ -1,12 +1,19 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
@@ -68,12 +75,205 @@ func TestProxyPoolURLKeyNormalizesHostCase(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeMaskedProxyURLPreservesOnlyPassword(t *testing.T) {
|
||||
got, err := mergeMaskedProxyURL("http://newuser:***@NEW.example:9090", "http://old:[email protected]:8080")
|
||||
func TestProxyPoolHealthThresholdCooldownAndRecovery(t *testing.T) {
|
||||
m := &Manager{proxyPool: &proxyPoolState{entries: []proxyPoolEntry{{ProxyPoolEntry: ProxyPoolEntry{ID: "a", Enabled: true, Health: "healthy"}, RawURL: "http://a"}}}}
|
||||
fail := egressProbeResult{Error: "http://user:pass@proxy: connection refused"}
|
||||
for i := 0; i < defaultProxyHealthThreshold-1; i++ {
|
||||
m.markProxyProbe("a", fail)
|
||||
if got := m.proxyPool.entries[0].Health; got != "healthy" {
|
||||
t.Fatalf("failure %d moved to %s before threshold", i+1, got)
|
||||
}
|
||||
}
|
||||
m.markProxyProbe("a", fail)
|
||||
if got := m.proxyPool.entries[0]; got.Health != "unhealthy-cooling" || got.ConsecutiveFailures != defaultProxyHealthThreshold {
|
||||
t.Fatalf("threshold state=%+v", got)
|
||||
}
|
||||
if got := m.proxyPool.entries[0].LastError; strings.Contains(got, "pass") || !strings.Contains(got, "***@") {
|
||||
t.Fatalf("failure was not masked: %q", got)
|
||||
}
|
||||
m.markProxyProbe("a", egressProbeResult{OK: true, ExitIP: "203.0.113.9"})
|
||||
if got := m.proxyPool.entries[0]; got.Health != "healthy" || got.ConsecutiveFailures != 0 || got.EgressIP != "203.0.113.9" {
|
||||
t.Fatalf("recovery state=%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyReconnectGuardsGateExhaustedAutomaticResume(t *testing.T) {
|
||||
task := &Task{ID: "exhausted", PauseReason: "paused_by_proxy", ReconnectGeneration: 4, ReconnectAttempt: 3, ReconnectExhausted: true}
|
||||
m := &Manager{tasks: map[string]*Task{task.ID: task}}
|
||||
s := &Server{m: m}
|
||||
if got := s.snapshotProxyReconnectGuards(false); len(got) != 0 {
|
||||
t.Fatalf("automatic guards included exhausted task: %+v", got)
|
||||
}
|
||||
if got := s.snapshotProxyReconnectGuardsWithExhausted(false, true); len(got) != 1 {
|
||||
t.Fatalf("manual guards did not include exhausted task: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyPoolSettingsRejectTooShortInterval(t *testing.T) {
|
||||
m := &Manager{}
|
||||
if err := m.SetProxyPoolSettings(true, minProxyRotateInterval-1, true, "sequential", 3, 60, 30); err == nil {
|
||||
t.Fatal("interval below lower bound was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyPoolRandomSelectionStillExcludesDisabledAndCooling(t *testing.T) {
|
||||
m := proxyTestManager(t)
|
||||
if err := m.pg.SetSetting(settingProxyRotateStrategy, "random"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.proxyPool = &proxyPoolState{entries: []proxyPoolEntry{
|
||||
{ProxyPoolEntry: ProxyPoolEntry{ID: "disabled", Enabled: false, Health: "healthy"}},
|
||||
{ProxyPoolEntry: ProxyPoolEntry{ID: "cooling", Enabled: true, Health: "unhealthy-cooling"}},
|
||||
{ProxyPoolEntry: ProxyPoolEntry{ID: "good", Enabled: true, Health: "healthy"}},
|
||||
}}
|
||||
for i := 0; i < 20; i++ {
|
||||
if got := m.selectHealthyLocked(""); got != "good" {
|
||||
t.Fatalf("random selected %q", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyPoolFailureMarksOriginalMemberAfterConcurrentSwitch(t *testing.T) {
|
||||
m := &Manager{globalProxy: "http://a", proxyPool: &proxyPoolState{active: "a", entries: []proxyPoolEntry{
|
||||
{ProxyPoolEntry: ProxyPoolEntry{ID: "a", Enabled: true, Health: "healthy"}, RawURL: "http://a"},
|
||||
{ProxyPoolEntry: ProxyPoolEntry{ID: "b", Enabled: true, Health: "healthy"}, RawURL: "http://b"},
|
||||
}}}
|
||||
s := &Server{m: m, ctx: context.Background(), proxyPoolWake: make(chan struct{}, 1)}
|
||||
s.proxyProbe = func(context.Context, string, string, []string, time.Duration) egressProbeResult {
|
||||
m.mu.Lock()
|
||||
m.globalProxy = "http://b"
|
||||
m.mu.Unlock()
|
||||
return egressProbeResult{Error: "proxy connection refused"}
|
||||
}
|
||||
if !s.handleProxyPoolFailure(fmt.Errorf("proxyconnect tcp: connection refused")) {
|
||||
t.Fatal("failure after concurrent switch was not consumed")
|
||||
}
|
||||
if got := m.proxyPool.entries[0].ConsecutiveFailures; got != 1 {
|
||||
t.Fatalf("original member failure count=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyPoolAllMembersUnhealthyKeepsProxyConfigured(t *testing.T) {
|
||||
m := &Manager{globalProxy: "http://a", proxyPool: &proxyPoolState{active: "a", entries: []proxyPoolEntry{
|
||||
{ProxyPoolEntry: ProxyPoolEntry{ID: "a", Enabled: true, Health: "unhealthy-cooling", ConsecutiveFailures: defaultProxyHealthThreshold, LastCheckedAt: time.Now().Add(-2 * time.Minute)}, RawURL: "http://a"},
|
||||
{ProxyPoolEntry: ProxyPoolEntry{ID: "b", Enabled: true, Health: "unhealthy-cooling", ConsecutiveFailures: defaultProxyHealthThreshold, LastCheckedAt: time.Now().Add(-2 * time.Minute)}, RawURL: "http://b"},
|
||||
}}}
|
||||
s := &Server{m: m, ctx: context.Background(), proxyPoolProbeSem: make(chan struct{}, proxyPoolMaxProbeConcurrency)}
|
||||
s.proxyProbe = func(context.Context, string, string, []string, time.Duration) egressProbeResult {
|
||||
return egressProbeResult{Error: "proxy down"}
|
||||
}
|
||||
s.proxyPoolTickLocked(true)
|
||||
if got := m.GlobalProxy(); got != "http://a" {
|
||||
t.Fatalf("all unhealthy members fell back to direct: %q", got)
|
||||
}
|
||||
if got := m.proxyPoolActiveID(); got != "a" {
|
||||
t.Fatalf("active member changed without a healthy replacement: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyPoolMaskedEditHotCutsCoolingActiveMember(t *testing.T) {
|
||||
m := &Manager{globalProxy: "http://old:[email protected]:8080", proxyPool: &proxyPoolState{active: "a", entries: []proxyPoolEntry{{
|
||||
ProxyPoolEntry: ProxyPoolEntry{ID: "a", Enabled: true, Health: "unhealthy-cooling", ConsecutiveFailures: 3},
|
||||
RawURL: "http://old:[email protected]:8080",
|
||||
}}}}
|
||||
s := &Server{m: m}
|
||||
r := httptest.NewRequest(http.MethodPatch, "/api/settings/proxy-pool/a", strings.NewReader(`{"url":"http://***@new.example:9090"}`))
|
||||
r.SetPathValue("id", "a")
|
||||
w := httptest.NewRecorder()
|
||||
s.updateProxyPool(w, r)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if got := m.GlobalProxy(); got != "http://old:[email protected]:9090" {
|
||||
t.Fatalf("active proxy=%q", got)
|
||||
}
|
||||
if got := m.proxyPool.entries[0].Health; got != "healthy" {
|
||||
t.Fatalf("edited active member health=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyPoolDeleteNeverRetainsDeletedRuntimeURL(t *testing.T) {
|
||||
m := &Manager{globalProxy: "http://a", proxyPool: &proxyPoolState{active: "a", entries: []proxyPoolEntry{
|
||||
{ProxyPoolEntry: ProxyPoolEntry{ID: "a", Enabled: true, Health: "healthy"}, RawURL: "http://a"},
|
||||
{ProxyPoolEntry: ProxyPoolEntry{ID: "b", Enabled: true, Health: "healthy"}, RawURL: "http://b"},
|
||||
}}}
|
||||
s := &Server{m: m}
|
||||
deleteEntry := func(id string) {
|
||||
r := httptest.NewRequest(http.MethodDelete, "/api/settings/proxy-pool/"+id, nil)
|
||||
r.SetPathValue("id", id)
|
||||
w := httptest.NewRecorder()
|
||||
s.deleteProxyPool(w, r)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("delete %s status=%d body=%s", id, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
deleteEntry("a")
|
||||
if got := m.GlobalProxy(); got != "http://b" {
|
||||
t.Fatalf("surviving pool member was not activated: %q", got)
|
||||
}
|
||||
deleteEntry("b")
|
||||
if got := m.GlobalProxy(); got != "" || m.proxyPool.active != "" {
|
||||
t.Fatalf("deleted last member left runtime proxy=%q active=%q", got, m.proxyPool.active)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetGlobalProxyIsReadOnlyWhenPoolManaged(t *testing.T) {
|
||||
m := &Manager{globalProxy: "http://pool.example:8080", proxyPool: &proxyPoolState{entries: []proxyPoolEntry{{
|
||||
ProxyPoolEntry: ProxyPoolEntry{ID: "pool", Enabled: true, Health: "healthy"}, RawURL: "http://pool.example:8080",
|
||||
}}}}
|
||||
if err := m.SetGlobalProxy("http://other.example:8080"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := m.GlobalProxy(); got != "http://pool.example:8080" {
|
||||
t.Fatalf("managed pool runtime changed through legacy setting: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyPoolEmptyPersistenceDoesNotResurrectLegacyProxy(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
m, err := NewManager(dir, "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
m.proxyPool = &proxyPoolState{active: "a", entries: []proxyPoolEntry{{
|
||||
ProxyPoolEntry: ProxyPoolEntry{ID: "a", Enabled: true, Health: "healthy"}, RawURL: "http://deleted.example:8080",
|
||||
}}}
|
||||
m.globalProxy = "http://deleted.example:8080"
|
||||
if err := m.persistProxyPoolLocked(); err != nil {
|
||||
_ = m.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &Server{m: m}
|
||||
r := httptest.NewRequest(http.MethodDelete, "/api/settings/proxy-pool/a", nil)
|
||||
r.SetPathValue("id", "a")
|
||||
w := httptest.NewRecorder()
|
||||
s.deleteProxyPool(w, r)
|
||||
if w.Code != http.StatusOK {
|
||||
_ = m.Close()
|
||||
t.Fatalf("delete status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if got := m.GlobalProxy(); got != "" {
|
||||
t.Fatalf("delete left runtime proxy=%q", got)
|
||||
}
|
||||
if err := m.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m2, err := NewManager(dir, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "http://newuser:[email protected]:9090" {
|
||||
defer m2.Close()
|
||||
if got := m2.GlobalProxy(); got != "" || len(m2.proxyPoolEntries()) != 0 {
|
||||
t.Fatalf("empty persisted pool resurrected proxy=%q entries=%d", got, len(m2.proxyPoolEntries()))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeMaskedProxyURLPreservesOnlyPassword(t *testing.T) {
|
||||
got, err := mergeMaskedProxyURL("http://***@NEW.example:9090", "http://old:[email protected]:8080")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "http://old:[email protected]:9090" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -105,3 +305,155 @@ func TestDynamicForwardProxyUsesCurrentUpstream(t *testing.T) {
|
||||
t.Fatalf("status %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDynamicForwardProxyConnectAuthenticatedUpstreamAndBufferedBytes(t *testing.T) {
|
||||
const user, pass = "alice", "s3cret"
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodConnect {
|
||||
http.Error(w, "connect required", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
want := "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))
|
||||
if r.Header.Get("Proxy-Authorization") != want {
|
||||
w.Header().Set("Proxy-Authenticate", `Basic realm="test"`)
|
||||
w.WriteHeader(http.StatusProxyAuthRequired)
|
||||
return
|
||||
}
|
||||
h, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "no hijack", 500)
|
||||
return
|
||||
}
|
||||
c, rw, err := h.Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
_, _ = rw.WriteString("HTTP/1.1 200 Connection Established\r\n\r\nupstream-buffer")
|
||||
_ = rw.Flush()
|
||||
}))
|
||||
defer upstream.Close()
|
||||
up, _ := url.Parse(upstream.URL)
|
||||
up.User = url.UserPassword(user, pass)
|
||||
fp, err := newDynamicForwardProxy(func() string { return up.String() })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fp.Close()
|
||||
|
||||
c, err := net.Dial("tcp", strings.TrimPrefix(fp.Addr(), "http://"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
_, _ = fmt.Fprintf(c, "CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\n")
|
||||
rd := bufio.NewReader(c)
|
||||
resp, err := http.ReadResponse(rd, &http.Request{Method: http.MethodConnect})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("local CONNECT status %s", resp.Status)
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(rd, int64(len("upstream-buffer"))))
|
||||
if err != nil || string(b) != "upstream-buffer" {
|
||||
t.Fatalf("buffered bytes=%q err=%v", b, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDynamicForwardProxyConnectForwardsHijackBufferedClientBytes(t *testing.T) {
|
||||
targetLn, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer targetLn.Close()
|
||||
go func() {
|
||||
c, err := targetLn.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer c.Close()
|
||||
buf := make([]byte, len("hello"))
|
||||
if _, err := io.ReadFull(c, buf); err == nil {
|
||||
_, _ = c.Write([]byte("target"))
|
||||
}
|
||||
}()
|
||||
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodConnect {
|
||||
http.Error(w, "connect required", 405)
|
||||
return
|
||||
}
|
||||
c, err := net.Dial("tcp", targetLn.Addr().String())
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 502)
|
||||
return
|
||||
}
|
||||
h, _ := w.(http.Hijacker)
|
||||
client, rw, err := h.Hijack()
|
||||
if err != nil {
|
||||
_ = c.Close()
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
defer c.Close()
|
||||
_, _ = rw.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
_ = rw.Flush()
|
||||
buf := make([]byte, len("hello"))
|
||||
if _, err := io.ReadFull(rw.Reader, buf); err != nil {
|
||||
return
|
||||
}
|
||||
_, _ = c.Write(buf)
|
||||
response := make([]byte, len("target"))
|
||||
if _, err := io.ReadFull(c, response); err == nil {
|
||||
_, _ = client.Write(response)
|
||||
}
|
||||
}))
|
||||
defer proxyServer.Close()
|
||||
fp, err := newDynamicForwardProxy(func() string { return proxyServer.URL })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fp.Close()
|
||||
c, err := net.Dial("tcp", strings.TrimPrefix(fp.Addr(), "http://"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
_, _ = fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\nhello", targetLn.Addr().String(), targetLn.Addr().String())
|
||||
rd := bufio.NewReader(c)
|
||||
resp, err := http.ReadResponse(rd, &http.Request{Method: http.MethodConnect})
|
||||
if err != nil || resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("CONNECT response=%v status=%v", err, resp)
|
||||
}
|
||||
_ = c.SetReadDeadline(time.Now().Add(2 * time.Second))
|
||||
b, err := io.ReadAll(io.LimitReader(rd, int64(len("target"))))
|
||||
if err != nil || string(b) != "target" {
|
||||
t.Fatalf("target response=%q err=%v", b, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialHTTPConnectBlackholeHonorsContext(t *testing.T) {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
go func() {
|
||||
c, err := ln.Accept()
|
||||
if err == nil {
|
||||
defer c.Close()
|
||||
_, _ = io.Copy(io.Discard, c)
|
||||
}
|
||||
}()
|
||||
u, _ := url.Parse("http://" + ln.Addr().String())
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
started := time.Now()
|
||||
_, err = dialHTTPConnect(ctx, u, "example.test:443")
|
||||
if err == nil {
|
||||
t.Fatal("blackholed CONNECT unexpectedly succeeded")
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed > time.Second {
|
||||
t.Fatalf("context cancellation took %s", elapsed)
|
||||
}
|
||||
}
|
||||
@@ -445,6 +445,10 @@ export default function SystemSettingsPage() {
|
||||
};
|
||||
|
||||
const saveGlobalProxy = () => {
|
||||
if (proxyPool.length > 0) {
|
||||
toast.info("代理池非空时,全局代理输入框仅用于回显,请在代理池中编辑或切换");
|
||||
return;
|
||||
}
|
||||
setSavingGlobalProxy(true);
|
||||
api
|
||||
.setSettings({ global_proxy: globalProxyInput.trim() })
|
||||
@@ -490,6 +494,7 @@ export default function SystemSettingsPage() {
|
||||
api
|
||||
.testEgressProxy({
|
||||
global_proxy: globalProxyInput.trim(),
|
||||
resume: true,
|
||||
|
||||
...(egressProbeUrl.trim() ? { probe_url: egressProbeUrl.trim() } : {}),
|
||||
})
|
||||
|
||||
+1
-1
@@ -992,7 +992,7 @@ export const api = {
|
||||
}) => post<{ ok: boolean; error?: string; count?: number; backend?: string }>(`/settings/web-search/test`, patch),
|
||||
|
||||
// global_proxy 传空 = 测直连;probe_url 可覆盖默认探测地址(隔离网用)。
|
||||
testEgressProxy: (patch: { global_proxy?: string; probe_url?: string }) =>
|
||||
testEgressProxy: (patch: { global_proxy?: string; probe_url?: string; resume?: boolean }) =>
|
||||
post<EgressReport>(`/settings/proxy/test`, patch),
|
||||
proxyPool: () => get<{ entries: ProxyPoolEntry[]; active_id: string; active_proxy: string; switch_log: ProxySwitchLog[] }>(`/settings/proxy-pool`),
|
||||
importProxyPool: (payload: Record<string, unknown>) => post<{ entries: ProxyPoolEntry[]; active_id: string; switch_log: ProxySwitchLog[]; errors: Array<{ line: number; input: string; error: string }> }>(`/settings/proxy-pool/import`, payload),
|
||||
|
||||
Reference in new issue
Block a user