fix(mail): enforce end-to-end timeout for SOCKS5 IMAP dial

Use context-based SOCKS dialing and bounded TLS handshake so proxy negotiation and handshake cannot hang indefinitely, with regression tests for both paths.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-04-27 22:10:20 +07:00
co-authored by Claude Opus 4.7
parent d0c22a0554
commit d1c35e0b57
2 changed files with 92 additions and 19 deletions
+24 -6
View File
@@ -39,12 +39,18 @@ type IMAPWatcher struct {
const imapDialTimeout = 30 * time.Second
type timeoutDialer struct {
type timeoutContextDialer struct {
timeout time.Duration
}
func (d timeoutDialer) Dial(network, address string) (net.Conn, error) {
return (&net.Dialer{Timeout: d.timeout}).Dial(network, address)
func (d timeoutContextDialer) Dial(network, address string) (net.Conn, error) {
ctx, cancel := context.WithTimeout(context.Background(), d.timeout)
defer cancel()
return d.DialContext(ctx, network, address)
}
func (d timeoutContextDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
return (&net.Dialer{Timeout: d.timeout}).DialContext(ctx, network, address)
}
var socks5DialerFactory = proxy.SOCKS5
@@ -189,12 +195,20 @@ func dialTLSViaSOCKS5(addr, proxyURL string, options *imapclient.Options) (*imap
auth = &proxy.Auth{User: u.User.Username(), Password: pw}
}
dialer, err := socks5DialerFactory("tcp", u.Host, auth, timeoutDialer{timeout: imapDialTimeout})
dialer, err := socks5DialerFactory("tcp", u.Host, auth, timeoutContextDialer{timeout: imapDialTimeout})
if err != nil {
return nil, fmt.Errorf("create socks5 dialer: %w", err)
}
conn, err := dialer.Dial("tcp", addr)
dialCtx, dialCancel := context.WithTimeout(context.Background(), imapDialTimeout)
defer dialCancel()
var conn net.Conn
if cd, ok := dialer.(proxy.ContextDialer); ok {
conn, err = cd.DialContext(dialCtx, "tcp", addr)
} else {
conn, err = dialer.Dial("tcp", addr)
}
if err != nil {
return nil, fmt.Errorf("proxy dial: %w", err)
}
@@ -204,10 +218,14 @@ func dialTLSViaSOCKS5(addr, proxyURL string, options *imapclient.Options) (*imap
host = addr
}
tlsConn := tls.Client(conn, &tls.Config{ServerName: host})
if err := tlsConn.Handshake(); err != nil {
_ = tlsConn.SetDeadline(time.Now().Add(imapDialTimeout))
handshakeCtx, handshakeCancel := context.WithTimeout(context.Background(), imapDialTimeout)
defer handshakeCancel()
if err := tlsConn.HandshakeContext(handshakeCtx); err != nil {
_ = tlsConn.Close()
return nil, fmt.Errorf("tls handshake: %w", err)
}
_ = tlsConn.SetDeadline(time.Time{})
return imapclient.New(tlsConn, options), nil
}