perf(proxy): use mutex-based connection pool (#7790)
* perf(proxy): use mutex-based connection pool
The proxy package (used for example by the forward plugin) utilized
an actor model where a single connManager goroutine managed
connection pooling via unbuffered channels (dial, yield, ret). This
design serialized all connection acquisition and release operations
through a single goroutine, creating a bottleneck under high
concurrency. This was observable as a performance degradation when
using a single upstream backend compared to multiple backends
(which sharded the bottleneck).
Changes:
- Removed dial, yield, and ret channels from the Transport struct.
- Removed the connManager goroutine's request processing loop.
- Implemented Dial() and Yield() using a sync.Mutex to protect the
connection slice, allowing for fast concurrent access without
context switching.
- Downgraded connManager to a simple background cleanup loop that
only handles connection expiration on a ticker.
- Updated plugin/pkg/proxy/connect.go to use direct method calls
instead of channel sends.
- Updated tests to reflect the removal of internal channels.
Benchmarks show that this change eliminates the single-backend
bottleneck. Now a single upstream backend performs on par with
multiple backends, and overall throughput is improved.
The implementation aligns with standard Go patterns for connection
pooling (e.g., net/http.Transport).
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address PR review for persistent.go
- Named mutex field instead of embedding, to not expose
Lock() and Unlock()
- Move stop check outside of lock in Yield()
- Close() without a separate goroutine
- Change stop channel to struct
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address code review feedback for conn pool
- Switch from LIFO to FIFO connection selection for source port
diversity, reducing DNS cache poisoning risk (RFC 5452).
- Remove "clear entire cache" optimization as it was LIFO-specific.
FIFO naturally iterates and skips expired connections.
- Remove all goroutines for closing connections; collect connections
while holding lock, close synchronously after releasing lock.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: remove unused error consts
No longer utilised after refactoring the channel based approach.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* feat(forward): add max_idle_conns option
Add configurable connection pool limit for the forward plugin via
the max_idle_conns Corefile option.
Changes:
- Add SetMaxIdleConns to proxy
- Add maxIdleConns field to Forward struct
- Add max_idle_conns parsing in forward plugin setup
- Apply setting to each proxy during configuration
- Update forward plugin README with new option
By default the value is 0 (unbounded). When set, excess
connections returned to the pool are closed immediately
rather than cached.
Also add a yield related test.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore(proxy): simple Dial by closing conns inline
Remove toClose slice collection to reduce complexity. Instead close
expired connections directly while iterating. Reduces complexity with
negligible lock-time impact.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: fewer explicit Unlock calls
Cleaner and less chance of forgetting to unlock on new possible
code paths.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2026-01-14 03:49:46 +02:00
|
|
|
// Package proxy implements a forwarding proxy with connection caching.
|
2026-09-08 12:51:18 +08:00
|
|
|
// It reuses upstream DNS, DoT, DoH, and DoQ connections to reduce latency and
|
|
|
|
|
// handshake overhead. It supports in-band health checking.
|
2023-03-24 12:55:51 +00:00
|
|
|
package proxy
|
2018-02-05 22:00:47 +00:00
|
|
|
|
|
|
|
|
import (
|
2018-04-22 08:34:35 +01:00
|
|
|
"context"
|
2023-09-07 12:01:45 -07:00
|
|
|
"errors"
|
2026-06-15 02:54:05 +02:00
|
|
|
"fmt"
|
2018-04-06 15:41:48 +03:00
|
|
|
"io"
|
2026-07-01 23:04:04 -05:00
|
|
|
"net"
|
|
|
|
|
"net/http/httptrace"
|
2018-02-05 22:00:47 +00:00
|
|
|
"strconv"
|
2023-09-07 12:01:45 -07:00
|
|
|
"strings"
|
2018-04-11 09:50:06 +03:00
|
|
|
"sync/atomic"
|
2018-02-05 22:00:47 +00:00
|
|
|
"time"
|
|
|
|
|
|
2026-06-15 02:54:05 +02:00
|
|
|
"github.com/coredns/coredns/plugin/pkg/doh"
|
|
|
|
|
"github.com/coredns/coredns/plugin/pkg/transport"
|
2018-02-05 22:00:47 +00:00
|
|
|
"github.com/coredns/coredns/request"
|
|
|
|
|
|
|
|
|
|
"github.com/miekg/dns"
|
|
|
|
|
)
|
|
|
|
|
|
2025-05-28 16:58:48 +03:00
|
|
|
const (
|
perf(proxy): use mutex-based connection pool (#7790)
* perf(proxy): use mutex-based connection pool
The proxy package (used for example by the forward plugin) utilized
an actor model where a single connManager goroutine managed
connection pooling via unbuffered channels (dial, yield, ret). This
design serialized all connection acquisition and release operations
through a single goroutine, creating a bottleneck under high
concurrency. This was observable as a performance degradation when
using a single upstream backend compared to multiple backends
(which sharded the bottleneck).
Changes:
- Removed dial, yield, and ret channels from the Transport struct.
- Removed the connManager goroutine's request processing loop.
- Implemented Dial() and Yield() using a sync.Mutex to protect the
connection slice, allowing for fast concurrent access without
context switching.
- Downgraded connManager to a simple background cleanup loop that
only handles connection expiration on a ticker.
- Updated plugin/pkg/proxy/connect.go to use direct method calls
instead of channel sends.
- Updated tests to reflect the removal of internal channels.
Benchmarks show that this change eliminates the single-backend
bottleneck. Now a single upstream backend performs on par with
multiple backends, and overall throughput is improved.
The implementation aligns with standard Go patterns for connection
pooling (e.g., net/http.Transport).
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address PR review for persistent.go
- Named mutex field instead of embedding, to not expose
Lock() and Unlock()
- Move stop check outside of lock in Yield()
- Close() without a separate goroutine
- Change stop channel to struct
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address code review feedback for conn pool
- Switch from LIFO to FIFO connection selection for source port
diversity, reducing DNS cache poisoning risk (RFC 5452).
- Remove "clear entire cache" optimization as it was LIFO-specific.
FIFO naturally iterates and skips expired connections.
- Remove all goroutines for closing connections; collect connections
while holding lock, close synchronously after releasing lock.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: remove unused error consts
No longer utilised after refactoring the channel based approach.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* feat(forward): add max_idle_conns option
Add configurable connection pool limit for the forward plugin via
the max_idle_conns Corefile option.
Changes:
- Add SetMaxIdleConns to proxy
- Add maxIdleConns field to Forward struct
- Add max_idle_conns parsing in forward plugin setup
- Apply setting to each proxy during configuration
- Update forward plugin README with new option
By default the value is 0 (unbounded). When set, excess
connections returned to the pool are closed immediately
rather than cached.
Also add a yield related test.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore(proxy): simple Dial by closing conns inline
Remove toClose slice collection to reduce complexity. Instead close
expired connections directly while iterating. Reduces complexity with
negligible lock-time impact.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: fewer explicit Unlock calls
Cleaner and less chance of forgetting to unlock on new possible
code paths.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2026-01-14 03:49:46 +02:00
|
|
|
ErrTransportStopped = "proxy: transport stopped"
|
2025-05-28 16:58:48 +03:00
|
|
|
)
|
|
|
|
|
|
2026-07-19 03:48:00 -07:00
|
|
|
var ErrInvalidRequest = errors.New("proxy: invalid request")
|
|
|
|
|
|
2018-06-15 02:37:22 -04:00
|
|
|
// limitTimeout is a utility function to auto-tune timeout values
|
|
|
|
|
// average observed time is moved towards the last observed delay moderated by a weight
|
|
|
|
|
// next timeout to use will be the double of the computed average, limited by min and max frame.
|
|
|
|
|
func limitTimeout(currentAvg *int64, minValue time.Duration, maxValue time.Duration) time.Duration {
|
|
|
|
|
rt := time.Duration(atomic.LoadInt64(currentAvg))
|
|
|
|
|
if rt < minValue {
|
|
|
|
|
return minValue
|
|
|
|
|
}
|
|
|
|
|
if rt < maxValue/2 {
|
|
|
|
|
return 2 * rt
|
|
|
|
|
}
|
|
|
|
|
return maxValue
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func averageTimeout(currentAvg *int64, observedDuration time.Duration, weight int64) {
|
|
|
|
|
dt := time.Duration(atomic.LoadInt64(currentAvg))
|
|
|
|
|
atomic.AddInt64(currentAvg, int64(observedDuration-dt)/weight)
|
|
|
|
|
}
|
|
|
|
|
|
2018-09-19 07:29:37 +01:00
|
|
|
func (t *Transport) dialTimeout() time.Duration {
|
2018-06-15 02:37:22 -04:00
|
|
|
return limitTimeout(&t.avgDialTime, minDialTimeout, maxDialTimeout)
|
|
|
|
|
}
|
|
|
|
|
|
2018-09-19 07:29:37 +01:00
|
|
|
func (t *Transport) updateDialTimeout(newDialTime time.Duration) {
|
2018-06-15 02:37:22 -04:00
|
|
|
averageTimeout(&t.avgDialTime, newDialTime, cumulativeAvgWeight)
|
|
|
|
|
}
|
2018-04-16 19:51:49 +01:00
|
|
|
|
2018-06-15 02:37:22 -04:00
|
|
|
// Dial dials the address configured in transport, potentially reusing a connection or creating a new one.
|
2019-10-01 16:39:42 +01:00
|
|
|
func (t *Transport) Dial(proto string) (*persistConn, bool, error) {
|
2026-09-19 07:56:31 +08:00
|
|
|
return t.DialContext(context.Background(), proto)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// DialContext is like Dial but honors ctx while establishing a new connection,
|
|
|
|
|
// including the TLS handshake. The context does not affect the connection after dialing.
|
|
|
|
|
func (t *Transport) DialContext(ctx context.Context, proto string) (*persistConn, bool, error) {
|
|
|
|
|
return t.dial(ctx, proto, time.Time{})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (t *Transport) dial(ctx context.Context, proto string, tlsDeadline time.Time) (*persistConn, bool, error) {
|
|
|
|
|
if err := ctx.Err(); err != nil {
|
|
|
|
|
return nil, false, err
|
|
|
|
|
}
|
|
|
|
|
|
2018-06-15 02:37:22 -04:00
|
|
|
// If tls has been configured; use it.
|
|
|
|
|
if t.tlsConfig != nil {
|
|
|
|
|
proto = "tcp-tls"
|
2018-04-16 19:51:49 +01:00
|
|
|
}
|
2018-06-15 02:37:22 -04:00
|
|
|
|
2025-05-28 16:58:48 +03:00
|
|
|
// Check if transport is stopped before attempting to dial
|
|
|
|
|
select {
|
|
|
|
|
case <-t.stop:
|
|
|
|
|
return nil, false, errors.New(ErrTransportStopped)
|
|
|
|
|
default:
|
|
|
|
|
}
|
2018-06-15 02:37:22 -04:00
|
|
|
|
perf(proxy): use mutex-based connection pool (#7790)
* perf(proxy): use mutex-based connection pool
The proxy package (used for example by the forward plugin) utilized
an actor model where a single connManager goroutine managed
connection pooling via unbuffered channels (dial, yield, ret). This
design serialized all connection acquisition and release operations
through a single goroutine, creating a bottleneck under high
concurrency. This was observable as a performance degradation when
using a single upstream backend compared to multiple backends
(which sharded the bottleneck).
Changes:
- Removed dial, yield, and ret channels from the Transport struct.
- Removed the connManager goroutine's request processing loop.
- Implemented Dial() and Yield() using a sync.Mutex to protect the
connection slice, allowing for fast concurrent access without
context switching.
- Downgraded connManager to a simple background cleanup loop that
only handles connection expiration on a ticker.
- Updated plugin/pkg/proxy/connect.go to use direct method calls
instead of channel sends.
- Updated tests to reflect the removal of internal channels.
Benchmarks show that this change eliminates the single-backend
bottleneck. Now a single upstream backend performs on par with
multiple backends, and overall throughput is improved.
The implementation aligns with standard Go patterns for connection
pooling (e.g., net/http.Transport).
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address PR review for persistent.go
- Named mutex field instead of embedding, to not expose
Lock() and Unlock()
- Move stop check outside of lock in Yield()
- Close() without a separate goroutine
- Change stop channel to struct
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address code review feedback for conn pool
- Switch from LIFO to FIFO connection selection for source port
diversity, reducing DNS cache poisoning risk (RFC 5452).
- Remove "clear entire cache" optimization as it was LIFO-specific.
FIFO naturally iterates and skips expired connections.
- Remove all goroutines for closing connections; collect connections
while holding lock, close synchronously after releasing lock.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: remove unused error consts
No longer utilised after refactoring the channel based approach.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* feat(forward): add max_idle_conns option
Add configurable connection pool limit for the forward plugin via
the max_idle_conns Corefile option.
Changes:
- Add SetMaxIdleConns to proxy
- Add maxIdleConns field to Forward struct
- Add max_idle_conns parsing in forward plugin setup
- Apply setting to each proxy during configuration
- Update forward plugin README with new option
By default the value is 0 (unbounded). When set, excess
connections returned to the pool are closed immediately
rather than cached.
Also add a yield related test.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore(proxy): simple Dial by closing conns inline
Remove toClose slice collection to reduce complexity. Instead close
expired connections directly while iterating. Reduces complexity with
negligible lock-time impact.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: fewer explicit Unlock calls
Cleaner and less chance of forgetting to unlock on new possible
code paths.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2026-01-14 03:49:46 +02:00
|
|
|
transtype := stringToTransportType(proto)
|
2018-06-15 02:37:22 -04:00
|
|
|
|
perf(proxy): use mutex-based connection pool (#7790)
* perf(proxy): use mutex-based connection pool
The proxy package (used for example by the forward plugin) utilized
an actor model where a single connManager goroutine managed
connection pooling via unbuffered channels (dial, yield, ret). This
design serialized all connection acquisition and release operations
through a single goroutine, creating a bottleneck under high
concurrency. This was observable as a performance degradation when
using a single upstream backend compared to multiple backends
(which sharded the bottleneck).
Changes:
- Removed dial, yield, and ret channels from the Transport struct.
- Removed the connManager goroutine's request processing loop.
- Implemented Dial() and Yield() using a sync.Mutex to protect the
connection slice, allowing for fast concurrent access without
context switching.
- Downgraded connManager to a simple background cleanup loop that
only handles connection expiration on a ticker.
- Updated plugin/pkg/proxy/connect.go to use direct method calls
instead of channel sends.
- Updated tests to reflect the removal of internal channels.
Benchmarks show that this change eliminates the single-backend
bottleneck. Now a single upstream backend performs on par with
multiple backends, and overall throughput is improved.
The implementation aligns with standard Go patterns for connection
pooling (e.g., net/http.Transport).
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address PR review for persistent.go
- Named mutex field instead of embedding, to not expose
Lock() and Unlock()
- Move stop check outside of lock in Yield()
- Close() without a separate goroutine
- Change stop channel to struct
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address code review feedback for conn pool
- Switch from LIFO to FIFO connection selection for source port
diversity, reducing DNS cache poisoning risk (RFC 5452).
- Remove "clear entire cache" optimization as it was LIFO-specific.
FIFO naturally iterates and skips expired connections.
- Remove all goroutines for closing connections; collect connections
while holding lock, close synchronously after releasing lock.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: remove unused error consts
No longer utilised after refactoring the channel based approach.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* feat(forward): add max_idle_conns option
Add configurable connection pool limit for the forward plugin via
the max_idle_conns Corefile option.
Changes:
- Add SetMaxIdleConns to proxy
- Add maxIdleConns field to Forward struct
- Add max_idle_conns parsing in forward plugin setup
- Apply setting to each proxy during configuration
- Update forward plugin README with new option
By default the value is 0 (unbounded). When set, excess
connections returned to the pool are closed immediately
rather than cached.
Also add a yield related test.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore(proxy): simple Dial by closing conns inline
Remove toClose slice collection to reduce complexity. Instead close
expired connections directly while iterating. Reduces complexity with
negligible lock-time impact.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: fewer explicit Unlock calls
Cleaner and less chance of forgetting to unlock on new possible
code paths.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2026-01-14 03:49:46 +02:00
|
|
|
t.mu.Lock()
|
plugin/forward: add max_age option to enforce an absolute connection lifetime (#7903)
* plugin/pkg/proxy: add max_age for per-connection lifetime cap
Introduce a max_age setting on Transport that closes connections based
on creation time, independent of idle-timeout (expire).
Background: PR #7790 changed the connection pool from LIFO to FIFO for
source-port diversity. Under FIFO, every connection is cycled through
the pool and its used timestamp is refreshed continuously. When request
rate is high enough that pool_size / request_rate < expire, no
connection ever becomes idle and expire never fires. This prevents
CoreDNS from opening new connections to upstreams that scale out (e.g.
new Kubernetes pods behind a ClusterIP service with conntrack pinning).
max_age addresses this by enforcing an absolute upper bound on
connection lifetime regardless of activity:
- persistConn gains a created field set at dial time.
- Transport gains maxAge (default 0 = unlimited, preserving existing
behaviour).
- Dial(): rejects cached connections whose creation age exceeds max_age.
- cleanup(): when maxAge > 0, uses a linear scan over both idle-timeout
and max-age predicates; when maxAge == 0, preserves the original
binary-search path on used time (sorted by FIFO insertion order).
- Both hot paths pre-compute the deadline outside any inner loop to
avoid repeated time.Now() calls.
Tests added:
- TestMaxAgeExpireByCreation: connection with old created but fresh used
must be rejected even though idle-timeout would pass.
- TestMaxAgeFIFORotation: three FIFO-rotated connections (old created,
fresh used) must all be rejected, confirming that continuous rotation
cannot prevent max-age expiry.
Signed-off-by: cangming <cangming@cangming.app>
* plugin/forward: add max_age option
Expose Transport.SetMaxAge through the forward plugin so operators can
set an absolute upper bound on connection lifetime via the Corefile.
Usage:
forward . 1.2.3.4 {
max_age 30s
}
Default is 0 (unlimited), which preserves existing behaviour.
A positive value causes connections older than max_age to be closed and
re-dialled on the next request, ensuring CoreDNS reconnects to newly
scaled-out upstream pods even under sustained load where the idle
timeout (expire) would never fire.
If max_age is set, it must not be less than expire; the parser rejects
this combination at startup with a clear error message.
Signed-off-by: cangming <cangming@cangming.app>
---------
Signed-off-by: cangming <cangming@cangming.app>
2026-03-10 02:50:03 +08:00
|
|
|
// Pre-compute max-age deadline outside the loop to avoid repeated time.Now() calls.
|
|
|
|
|
var maxAgeDeadline time.Time
|
|
|
|
|
if t.maxAge > 0 {
|
|
|
|
|
maxAgeDeadline = time.Now().Add(-t.maxAge)
|
|
|
|
|
}
|
perf(proxy): use mutex-based connection pool (#7790)
* perf(proxy): use mutex-based connection pool
The proxy package (used for example by the forward plugin) utilized
an actor model where a single connManager goroutine managed
connection pooling via unbuffered channels (dial, yield, ret). This
design serialized all connection acquisition and release operations
through a single goroutine, creating a bottleneck under high
concurrency. This was observable as a performance degradation when
using a single upstream backend compared to multiple backends
(which sharded the bottleneck).
Changes:
- Removed dial, yield, and ret channels from the Transport struct.
- Removed the connManager goroutine's request processing loop.
- Implemented Dial() and Yield() using a sync.Mutex to protect the
connection slice, allowing for fast concurrent access without
context switching.
- Downgraded connManager to a simple background cleanup loop that
only handles connection expiration on a ticker.
- Updated plugin/pkg/proxy/connect.go to use direct method calls
instead of channel sends.
- Updated tests to reflect the removal of internal channels.
Benchmarks show that this change eliminates the single-backend
bottleneck. Now a single upstream backend performs on par with
multiple backends, and overall throughput is improved.
The implementation aligns with standard Go patterns for connection
pooling (e.g., net/http.Transport).
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address PR review for persistent.go
- Named mutex field instead of embedding, to not expose
Lock() and Unlock()
- Move stop check outside of lock in Yield()
- Close() without a separate goroutine
- Change stop channel to struct
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address code review feedback for conn pool
- Switch from LIFO to FIFO connection selection for source port
diversity, reducing DNS cache poisoning risk (RFC 5452).
- Remove "clear entire cache" optimization as it was LIFO-specific.
FIFO naturally iterates and skips expired connections.
- Remove all goroutines for closing connections; collect connections
while holding lock, close synchronously after releasing lock.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: remove unused error consts
No longer utilised after refactoring the channel based approach.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* feat(forward): add max_idle_conns option
Add configurable connection pool limit for the forward plugin via
the max_idle_conns Corefile option.
Changes:
- Add SetMaxIdleConns to proxy
- Add maxIdleConns field to Forward struct
- Add max_idle_conns parsing in forward plugin setup
- Apply setting to each proxy during configuration
- Update forward plugin README with new option
By default the value is 0 (unbounded). When set, excess
connections returned to the pool are closed immediately
rather than cached.
Also add a yield related test.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore(proxy): simple Dial by closing conns inline
Remove toClose slice collection to reduce complexity. Instead close
expired connections directly while iterating. Reduces complexity with
negligible lock-time impact.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: fewer explicit Unlock calls
Cleaner and less chance of forgetting to unlock on new possible
code paths.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2026-01-14 03:49:46 +02:00
|
|
|
// FIFO: take the oldest conn (front of slice) for source port diversity
|
|
|
|
|
for len(t.conns[transtype]) > 0 {
|
|
|
|
|
pc := t.conns[transtype][0]
|
|
|
|
|
t.conns[transtype] = t.conns[transtype][1:]
|
|
|
|
|
if time.Since(pc.used) > t.expire {
|
|
|
|
|
pc.c.Close()
|
|
|
|
|
continue
|
2025-05-28 16:58:48 +03:00
|
|
|
}
|
plugin/forward: add max_age option to enforce an absolute connection lifetime (#7903)
* plugin/pkg/proxy: add max_age for per-connection lifetime cap
Introduce a max_age setting on Transport that closes connections based
on creation time, independent of idle-timeout (expire).
Background: PR #7790 changed the connection pool from LIFO to FIFO for
source-port diversity. Under FIFO, every connection is cycled through
the pool and its used timestamp is refreshed continuously. When request
rate is high enough that pool_size / request_rate < expire, no
connection ever becomes idle and expire never fires. This prevents
CoreDNS from opening new connections to upstreams that scale out (e.g.
new Kubernetes pods behind a ClusterIP service with conntrack pinning).
max_age addresses this by enforcing an absolute upper bound on
connection lifetime regardless of activity:
- persistConn gains a created field set at dial time.
- Transport gains maxAge (default 0 = unlimited, preserving existing
behaviour).
- Dial(): rejects cached connections whose creation age exceeds max_age.
- cleanup(): when maxAge > 0, uses a linear scan over both idle-timeout
and max-age predicates; when maxAge == 0, preserves the original
binary-search path on used time (sorted by FIFO insertion order).
- Both hot paths pre-compute the deadline outside any inner loop to
avoid repeated time.Now() calls.
Tests added:
- TestMaxAgeExpireByCreation: connection with old created but fresh used
must be rejected even though idle-timeout would pass.
- TestMaxAgeFIFORotation: three FIFO-rotated connections (old created,
fresh used) must all be rejected, confirming that continuous rotation
cannot prevent max-age expiry.
Signed-off-by: cangming <cangming@cangming.app>
* plugin/forward: add max_age option
Expose Transport.SetMaxAge through the forward plugin so operators can
set an absolute upper bound on connection lifetime via the Corefile.
Usage:
forward . 1.2.3.4 {
max_age 30s
}
Default is 0 (unlimited), which preserves existing behaviour.
A positive value causes connections older than max_age to be closed and
re-dialled on the next request, ensuring CoreDNS reconnects to newly
scaled-out upstream pods even under sustained load where the idle
timeout (expire) would never fire.
If max_age is set, it must not be less than expire; the parser rejects
this combination at startup with a clear error message.
Signed-off-by: cangming <cangming@cangming.app>
---------
Signed-off-by: cangming <cangming@cangming.app>
2026-03-10 02:50:03 +08:00
|
|
|
if !maxAgeDeadline.IsZero() && pc.created.Before(maxAgeDeadline) {
|
|
|
|
|
pc.c.Close()
|
|
|
|
|
continue
|
|
|
|
|
}
|
perf(proxy): use mutex-based connection pool (#7790)
* perf(proxy): use mutex-based connection pool
The proxy package (used for example by the forward plugin) utilized
an actor model where a single connManager goroutine managed
connection pooling via unbuffered channels (dial, yield, ret). This
design serialized all connection acquisition and release operations
through a single goroutine, creating a bottleneck under high
concurrency. This was observable as a performance degradation when
using a single upstream backend compared to multiple backends
(which sharded the bottleneck).
Changes:
- Removed dial, yield, and ret channels from the Transport struct.
- Removed the connManager goroutine's request processing loop.
- Implemented Dial() and Yield() using a sync.Mutex to protect the
connection slice, allowing for fast concurrent access without
context switching.
- Downgraded connManager to a simple background cleanup loop that
only handles connection expiration on a ticker.
- Updated plugin/pkg/proxy/connect.go to use direct method calls
instead of channel sends.
- Updated tests to reflect the removal of internal channels.
Benchmarks show that this change eliminates the single-backend
bottleneck. Now a single upstream backend performs on par with
multiple backends, and overall throughput is improved.
The implementation aligns with standard Go patterns for connection
pooling (e.g., net/http.Transport).
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address PR review for persistent.go
- Named mutex field instead of embedding, to not expose
Lock() and Unlock()
- Move stop check outside of lock in Yield()
- Close() without a separate goroutine
- Change stop channel to struct
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address code review feedback for conn pool
- Switch from LIFO to FIFO connection selection for source port
diversity, reducing DNS cache poisoning risk (RFC 5452).
- Remove "clear entire cache" optimization as it was LIFO-specific.
FIFO naturally iterates and skips expired connections.
- Remove all goroutines for closing connections; collect connections
while holding lock, close synchronously after releasing lock.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: remove unused error consts
No longer utilised after refactoring the channel based approach.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* feat(forward): add max_idle_conns option
Add configurable connection pool limit for the forward plugin via
the max_idle_conns Corefile option.
Changes:
- Add SetMaxIdleConns to proxy
- Add maxIdleConns field to Forward struct
- Add max_idle_conns parsing in forward plugin setup
- Apply setting to each proxy during configuration
- Update forward plugin README with new option
By default the value is 0 (unbounded). When set, excess
connections returned to the pool are closed immediately
rather than cached.
Also add a yield related test.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore(proxy): simple Dial by closing conns inline
Remove toClose slice collection to reduce complexity. Instead close
expired connections directly while iterating. Reduces complexity with
negligible lock-time impact.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: fewer explicit Unlock calls
Cleaner and less chance of forgetting to unlock on new possible
code paths.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2026-01-14 03:49:46 +02:00
|
|
|
t.mu.Unlock()
|
|
|
|
|
connCacheHitsCount.WithLabelValues(t.proxyName, t.addr, proto).Add(1)
|
|
|
|
|
return pc, true, nil
|
|
|
|
|
}
|
|
|
|
|
t.mu.Unlock()
|
2025-05-28 16:58:48 +03:00
|
|
|
|
perf(proxy): use mutex-based connection pool (#7790)
* perf(proxy): use mutex-based connection pool
The proxy package (used for example by the forward plugin) utilized
an actor model where a single connManager goroutine managed
connection pooling via unbuffered channels (dial, yield, ret). This
design serialized all connection acquisition and release operations
through a single goroutine, creating a bottleneck under high
concurrency. This was observable as a performance degradation when
using a single upstream backend compared to multiple backends
(which sharded the bottleneck).
Changes:
- Removed dial, yield, and ret channels from the Transport struct.
- Removed the connManager goroutine's request processing loop.
- Implemented Dial() and Yield() using a sync.Mutex to protect the
connection slice, allowing for fast concurrent access without
context switching.
- Downgraded connManager to a simple background cleanup loop that
only handles connection expiration on a ticker.
- Updated plugin/pkg/proxy/connect.go to use direct method calls
instead of channel sends.
- Updated tests to reflect the removal of internal channels.
Benchmarks show that this change eliminates the single-backend
bottleneck. Now a single upstream backend performs on par with
multiple backends, and overall throughput is improved.
The implementation aligns with standard Go patterns for connection
pooling (e.g., net/http.Transport).
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address PR review for persistent.go
- Named mutex field instead of embedding, to not expose
Lock() and Unlock()
- Move stop check outside of lock in Yield()
- Close() without a separate goroutine
- Change stop channel to struct
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address code review feedback for conn pool
- Switch from LIFO to FIFO connection selection for source port
diversity, reducing DNS cache poisoning risk (RFC 5452).
- Remove "clear entire cache" optimization as it was LIFO-specific.
FIFO naturally iterates and skips expired connections.
- Remove all goroutines for closing connections; collect connections
while holding lock, close synchronously after releasing lock.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: remove unused error consts
No longer utilised after refactoring the channel based approach.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* feat(forward): add max_idle_conns option
Add configurable connection pool limit for the forward plugin via
the max_idle_conns Corefile option.
Changes:
- Add SetMaxIdleConns to proxy
- Add maxIdleConns field to Forward struct
- Add max_idle_conns parsing in forward plugin setup
- Apply setting to each proxy during configuration
- Update forward plugin README with new option
By default the value is 0 (unbounded). When set, excess
connections returned to the pool are closed immediately
rather than cached.
Also add a yield related test.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore(proxy): simple Dial by closing conns inline
Remove toClose slice collection to reduce complexity. Instead close
expired connections directly while iterating. Reduces complexity with
negligible lock-time impact.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: fewer explicit Unlock calls
Cleaner and less chance of forgetting to unlock on new possible
code paths.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2026-01-14 03:49:46 +02:00
|
|
|
connCacheMissesCount.WithLabelValues(t.proxyName, t.addr, proto).Add(1)
|
2025-05-28 16:58:48 +03:00
|
|
|
|
2026-09-19 07:56:31 +08:00
|
|
|
if proto == "tcp-tls" && !tlsDeadline.IsZero() {
|
|
|
|
|
var cancel context.CancelFunc
|
|
|
|
|
ctx, cancel = context.WithDeadline(ctx, tlsDeadline)
|
|
|
|
|
defer cancel()
|
|
|
|
|
}
|
perf(proxy): use mutex-based connection pool (#7790)
* perf(proxy): use mutex-based connection pool
The proxy package (used for example by the forward plugin) utilized
an actor model where a single connManager goroutine managed
connection pooling via unbuffered channels (dial, yield, ret). This
design serialized all connection acquisition and release operations
through a single goroutine, creating a bottleneck under high
concurrency. This was observable as a performance degradation when
using a single upstream backend compared to multiple backends
(which sharded the bottleneck).
Changes:
- Removed dial, yield, and ret channels from the Transport struct.
- Removed the connManager goroutine's request processing loop.
- Implemented Dial() and Yield() using a sync.Mutex to protect the
connection slice, allowing for fast concurrent access without
context switching.
- Downgraded connManager to a simple background cleanup loop that
only handles connection expiration on a ticker.
- Updated plugin/pkg/proxy/connect.go to use direct method calls
instead of channel sends.
- Updated tests to reflect the removal of internal channels.
Benchmarks show that this change eliminates the single-backend
bottleneck. Now a single upstream backend performs on par with
multiple backends, and overall throughput is improved.
The implementation aligns with standard Go patterns for connection
pooling (e.g., net/http.Transport).
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address PR review for persistent.go
- Named mutex field instead of embedding, to not expose
Lock() and Unlock()
- Move stop check outside of lock in Yield()
- Close() without a separate goroutine
- Change stop channel to struct
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address code review feedback for conn pool
- Switch from LIFO to FIFO connection selection for source port
diversity, reducing DNS cache poisoning risk (RFC 5452).
- Remove "clear entire cache" optimization as it was LIFO-specific.
FIFO naturally iterates and skips expired connections.
- Remove all goroutines for closing connections; collect connections
while holding lock, close synchronously after releasing lock.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: remove unused error consts
No longer utilised after refactoring the channel based approach.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* feat(forward): add max_idle_conns option
Add configurable connection pool limit for the forward plugin via
the max_idle_conns Corefile option.
Changes:
- Add SetMaxIdleConns to proxy
- Add maxIdleConns field to Forward struct
- Add max_idle_conns parsing in forward plugin setup
- Apply setting to each proxy during configuration
- Update forward plugin README with new option
By default the value is 0 (unbounded). When set, excess
connections returned to the pool are closed immediately
rather than cached.
Also add a yield related test.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore(proxy): simple Dial by closing conns inline
Remove toClose slice collection to reduce complexity. Instead close
expired connections directly while iterating. Reduces complexity with
negligible lock-time impact.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: fewer explicit Unlock calls
Cleaner and less chance of forgetting to unlock on new possible
code paths.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2026-01-14 03:49:46 +02:00
|
|
|
reqTime := time.Now()
|
|
|
|
|
timeout := t.dialTimeout()
|
plugin/pkg/proxy: set IP_RECVERR on upstream UDP sockets (#8628)
Without IP_RECVERR, Linux passes only some ICMP errors, such as port
unreachable, to a connected UDP socket. It drops net and host unreachable
(net/ipv4/udp.c, __udp4_lib_err), so a query to an upstream behind an
unreachable route waits out the read timeout before forward tries the
next upstream, and health checks wait out theirs before marking it down.
Set IP_RECVERR (IPV6_RECVERR for IPv6) on the UDP sockets for upstream
queries and health checks, so the read fails when the ICMP error arrives.
TCP sockets are left alone, and nothing changes outside Linux. The health
check client gets an explicit 2s dial timeout, since a Dialer replaces
dns.Client's default one. Because the Dialer now exists from the start,
setDialer no longer creates a bare one when source_address is set, which
also lost the dial timeout before.
Fixes #8621
Signed-off-by: MohibShaikh <mohibuddin9@gmail.com>
2026-10-13 12:45:06 +05:00
|
|
|
dialer := &net.Dialer{Timeout: timeout, Control: recvErr}
|
2026-07-10 02:38:22 +02:00
|
|
|
|
|
|
|
|
if t.localAddress != nil {
|
|
|
|
|
if proto == "udp" {
|
|
|
|
|
dialer.LocalAddr = &net.UDPAddr{IP: t.localAddress}
|
|
|
|
|
} else {
|
|
|
|
|
dialer.LocalAddr = &net.TCPAddr{IP: t.localAddress}
|
|
|
|
|
}
|
2018-06-15 02:37:22 -04:00
|
|
|
}
|
2026-07-10 02:38:22 +02:00
|
|
|
|
|
|
|
|
// pass nil tlsConfig to use system default
|
|
|
|
|
client := dns.Client{Net: proto, Dialer: dialer, TLSConfig: t.tlsConfig}
|
|
|
|
|
|
2026-09-19 07:56:31 +08:00
|
|
|
conn, err := client.DialContext(ctx, t.addr)
|
2026-07-10 02:38:22 +02:00
|
|
|
|
perf(proxy): use mutex-based connection pool (#7790)
* perf(proxy): use mutex-based connection pool
The proxy package (used for example by the forward plugin) utilized
an actor model where a single connManager goroutine managed
connection pooling via unbuffered channels (dial, yield, ret). This
design serialized all connection acquisition and release operations
through a single goroutine, creating a bottleneck under high
concurrency. This was observable as a performance degradation when
using a single upstream backend compared to multiple backends
(which sharded the bottleneck).
Changes:
- Removed dial, yield, and ret channels from the Transport struct.
- Removed the connManager goroutine's request processing loop.
- Implemented Dial() and Yield() using a sync.Mutex to protect the
connection slice, allowing for fast concurrent access without
context switching.
- Downgraded connManager to a simple background cleanup loop that
only handles connection expiration on a ticker.
- Updated plugin/pkg/proxy/connect.go to use direct method calls
instead of channel sends.
- Updated tests to reflect the removal of internal channels.
Benchmarks show that this change eliminates the single-backend
bottleneck. Now a single upstream backend performs on par with
multiple backends, and overall throughput is improved.
The implementation aligns with standard Go patterns for connection
pooling (e.g., net/http.Transport).
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address PR review for persistent.go
- Named mutex field instead of embedding, to not expose
Lock() and Unlock()
- Move stop check outside of lock in Yield()
- Close() without a separate goroutine
- Change stop channel to struct
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: address code review feedback for conn pool
- Switch from LIFO to FIFO connection selection for source port
diversity, reducing DNS cache poisoning risk (RFC 5452).
- Remove "clear entire cache" optimization as it was LIFO-specific.
FIFO naturally iterates and skips expired connections.
- Remove all goroutines for closing connections; collect connections
while holding lock, close synchronously after releasing lock.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix: remove unused error consts
No longer utilised after refactoring the channel based approach.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* feat(forward): add max_idle_conns option
Add configurable connection pool limit for the forward plugin via
the max_idle_conns Corefile option.
Changes:
- Add SetMaxIdleConns to proxy
- Add maxIdleConns field to Forward struct
- Add max_idle_conns parsing in forward plugin setup
- Apply setting to each proxy during configuration
- Update forward plugin README with new option
By default the value is 0 (unbounded). When set, excess
connections returned to the pool are closed immediately
rather than cached.
Also add a yield related test.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore(proxy): simple Dial by closing conns inline
Remove toClose slice collection to reduce complexity. Instead close
expired connections directly while iterating. Reduces complexity with
negligible lock-time impact.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: fewer explicit Unlock calls
Cleaner and less chance of forgetting to unlock on new possible
code paths.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2026-01-14 03:49:46 +02:00
|
|
|
t.updateDialTimeout(time.Since(reqTime))
|
plugin/forward: add max_age option to enforce an absolute connection lifetime (#7903)
* plugin/pkg/proxy: add max_age for per-connection lifetime cap
Introduce a max_age setting on Transport that closes connections based
on creation time, independent of idle-timeout (expire).
Background: PR #7790 changed the connection pool from LIFO to FIFO for
source-port diversity. Under FIFO, every connection is cycled through
the pool and its used timestamp is refreshed continuously. When request
rate is high enough that pool_size / request_rate < expire, no
connection ever becomes idle and expire never fires. This prevents
CoreDNS from opening new connections to upstreams that scale out (e.g.
new Kubernetes pods behind a ClusterIP service with conntrack pinning).
max_age addresses this by enforcing an absolute upper bound on
connection lifetime regardless of activity:
- persistConn gains a created field set at dial time.
- Transport gains maxAge (default 0 = unlimited, preserving existing
behaviour).
- Dial(): rejects cached connections whose creation age exceeds max_age.
- cleanup(): when maxAge > 0, uses a linear scan over both idle-timeout
and max-age predicates; when maxAge == 0, preserves the original
binary-search path on used time (sorted by FIFO insertion order).
- Both hot paths pre-compute the deadline outside any inner loop to
avoid repeated time.Now() calls.
Tests added:
- TestMaxAgeExpireByCreation: connection with old created but fresh used
must be rejected even though idle-timeout would pass.
- TestMaxAgeFIFORotation: three FIFO-rotated connections (old created,
fresh used) must all be rejected, confirming that continuous rotation
cannot prevent max-age expiry.
Signed-off-by: cangming <cangming@cangming.app>
* plugin/forward: add max_age option
Expose Transport.SetMaxAge through the forward plugin so operators can
set an absolute upper bound on connection lifetime via the Corefile.
Usage:
forward . 1.2.3.4 {
max_age 30s
}
Default is 0 (unlimited), which preserves existing behaviour.
A positive value causes connections older than max_age to be closed and
re-dialled on the next request, ensuring CoreDNS reconnects to newly
scaled-out upstream pods even under sustained load where the idle
timeout (expire) would never fire.
If max_age is set, it must not be less than expire; the parser rejects
this combination at startup with a clear error message.
Signed-off-by: cangming <cangming@cangming.app>
---------
Signed-off-by: cangming <cangming@cangming.app>
2026-03-10 02:50:03 +08:00
|
|
|
return &persistConn{c: conn, created: time.Now()}, false, err
|
2018-06-15 02:37:22 -04:00
|
|
|
}
|
|
|
|
|
|
2026-09-19 07:56:31 +08:00
|
|
|
func (p *Proxy) lookupDNS(ctx context.Context, state request.Request, opts Options) (*dns.Msg, net.Addr, string, error) {
|
2025-06-02 02:30:41 +03:00
|
|
|
var proto string
|
2018-07-07 10:14:21 +03:00
|
|
|
switch {
|
2023-03-24 12:55:51 +00:00
|
|
|
case opts.ForceTCP: // TCP flag has precedence over UDP flag
|
2018-02-05 22:00:47 +00:00
|
|
|
proto = "tcp"
|
2023-03-24 12:55:51 +00:00
|
|
|
case opts.PreferUDP:
|
2018-07-07 10:14:21 +03:00
|
|
|
proto = "udp"
|
|
|
|
|
default:
|
|
|
|
|
proto = state.Proto()
|
2018-02-05 22:00:47 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-19 03:48:00 -07:00
|
|
|
originId := state.Req.Id
|
|
|
|
|
state.Req.Id = dns.Id()
|
|
|
|
|
defer func() {
|
|
|
|
|
state.Req.Id = originId
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
var wire []byte
|
|
|
|
|
if state.Req.IsTsig() == nil {
|
|
|
|
|
var err error
|
|
|
|
|
wire, err = state.Req.Pack()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, nil, proto, fmt.Errorf("%w: %w", ErrInvalidRequest, err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-19 07:56:31 +08:00
|
|
|
pc, cached, err := p.transport.dial(ctx, proto, opts.TLSConnectDeadline)
|
2018-02-05 22:00:47 +00:00
|
|
|
if err != nil {
|
2026-07-01 23:04:04 -05:00
|
|
|
return nil, nil, proto, err
|
2018-02-05 22:00:47 +00:00
|
|
|
}
|
2018-04-26 09:34:58 +01:00
|
|
|
|
2026-07-01 23:04:04 -05:00
|
|
|
// Dial may have upgraded the transport (e.g. from udp to tcp for DoT),
|
|
|
|
|
// so report the transport the dialed connection actually uses, not the
|
|
|
|
|
// requested proto.
|
|
|
|
|
if p.transport.transportTypeFromConn(pc) == typeUDP {
|
|
|
|
|
proto = "udp"
|
|
|
|
|
} else {
|
|
|
|
|
proto = "tcp"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// localAddr is CoreDNS's own outbound address on the upstream socket.
|
|
|
|
|
// The forward plugin reports it as the dnstap query_address (the
|
|
|
|
|
// initiator) so that query_address and response_address describe the
|
|
|
|
|
// two ends of the same upstream connection.
|
|
|
|
|
localAddr := pc.c.LocalAddr()
|
|
|
|
|
|
2018-02-05 22:00:47 +00:00
|
|
|
// Set buffer size correctly for this client.
|
2026-01-01 13:50:29 +05:30
|
|
|
pc.c.UDPSize = max(uint16(state.Size()), 512) // #nosec G115 -- UDP size fits in uint16
|
2018-02-05 22:00:47 +00:00
|
|
|
|
2019-10-01 16:39:42 +01:00
|
|
|
pc.c.SetWriteDeadline(time.Now().Add(maxTimeout))
|
2026-07-19 03:48:00 -07:00
|
|
|
if wire != nil {
|
|
|
|
|
_, err = pc.c.Write(wire)
|
|
|
|
|
} else {
|
|
|
|
|
err = pc.c.WriteMsg(state.Req)
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
2019-10-01 16:39:42 +01:00
|
|
|
pc.c.Close() // not giving it back
|
2018-04-06 15:41:48 +03:00
|
|
|
if err == io.EOF && cached {
|
2026-07-01 23:04:04 -05:00
|
|
|
return nil, localAddr, proto, ErrCachedClosed
|
2018-04-06 15:41:48 +03:00
|
|
|
}
|
2026-07-01 23:04:04 -05:00
|
|
|
return nil, localAddr, proto, err
|
2018-02-05 22:00:47 +00:00
|
|
|
}
|
|
|
|
|
|
2019-03-01 17:40:52 +03:00
|
|
|
var ret *dns.Msg
|
2023-03-24 12:55:51 +00:00
|
|
|
pc.c.SetReadDeadline(time.Now().Add(p.readTimeout))
|
2019-03-01 17:40:52 +03:00
|
|
|
for {
|
2019-10-01 16:39:42 +01:00
|
|
|
ret, err = pc.c.ReadMsg()
|
2019-03-01 17:40:52 +03:00
|
|
|
if err != nil {
|
2026-07-21 15:21:25 -07:00
|
|
|
if p.transport.transportTypeFromConn(pc) == typeUDP &&
|
|
|
|
|
((ret == nil && errors.Is(err, dns.ErrShortRead)) ||
|
|
|
|
|
(ret != nil && ret.Id != state.Req.Id)) {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
2023-09-07 12:01:45 -07:00
|
|
|
if ret != nil && (state.Req.Id == ret.Id) && p.transport.transportTypeFromConn(pc) == typeUDP && shouldTruncateResponse(err) {
|
|
|
|
|
// For UDP, if the error is an overflow, we probably have an upstream misbehaving in some way.
|
|
|
|
|
// (e.g. sending >512 byte responses without an eDNS0 OPT RR).
|
|
|
|
|
// Instead of returning an error, return an empty response with TC bit set. This will make the
|
|
|
|
|
// client retry over TCP (if that's supported) or at least receive a clean
|
|
|
|
|
// error. The connection is still good so we break before the close.
|
|
|
|
|
|
|
|
|
|
// Truncate the response.
|
|
|
|
|
ret = truncateResponse(ret)
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-14 20:33:37 -04:00
|
|
|
pc.c.Close() // not giving it back
|
2019-03-01 17:40:52 +03:00
|
|
|
if err == io.EOF && cached {
|
2026-07-01 23:04:04 -05:00
|
|
|
return nil, localAddr, proto, ErrCachedClosed
|
2019-03-01 17:40:52 +03:00
|
|
|
}
|
2023-08-14 20:33:37 -04:00
|
|
|
// recovery the origin Id after upstream.
|
2021-10-11 10:28:01 +00:00
|
|
|
if ret != nil {
|
2021-10-09 01:34:22 +08:00
|
|
|
ret.Id = originId
|
|
|
|
|
}
|
2026-07-01 23:04:04 -05:00
|
|
|
return ret, localAddr, proto, err
|
2019-03-01 17:40:52 +03:00
|
|
|
}
|
|
|
|
|
// drop out-of-order responses
|
|
|
|
|
if state.Req.Id == ret.Id {
|
|
|
|
|
break
|
2018-04-06 15:41:48 +03:00
|
|
|
}
|
2018-02-05 22:00:47 +00:00
|
|
|
}
|
2026-06-15 02:54:05 +02:00
|
|
|
p.transport.Yield(pc)
|
|
|
|
|
|
2026-07-01 23:04:04 -05:00
|
|
|
return ret, localAddr, proto, nil
|
2026-06-15 02:54:05 +02:00
|
|
|
}
|
|
|
|
|
|
2026-07-01 23:04:04 -05:00
|
|
|
func (p *Proxy) lookupDoH(ctx context.Context, state request.Request, _ Options) (*dns.Msg, net.Addr, string, error) {
|
|
|
|
|
// DoH always runs over TCP (HTTPS), regardless of the downstream
|
|
|
|
|
// client's protocol.
|
|
|
|
|
const proto = "tcp"
|
2026-07-22 19:07:09 -07:00
|
|
|
// records the origin Id before upstream.
|
|
|
|
|
originId := state.Req.Id
|
|
|
|
|
// RFC8484 has DNS ID of 0 as a SHOULD
|
|
|
|
|
state.Req.Id = 0
|
|
|
|
|
defer func() {
|
|
|
|
|
state.Req.Id = originId
|
|
|
|
|
}()
|
2026-07-01 23:04:04 -05:00
|
|
|
|
|
|
|
|
var localAddr net.Addr
|
|
|
|
|
trace := &httptrace.ClientTrace{
|
|
|
|
|
GotConn: func(info httptrace.GotConnInfo) {
|
|
|
|
|
localAddr = info.Conn.LocalAddr()
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
ctx = httptrace.WithClientTrace(ctx, trace)
|
|
|
|
|
|
2026-07-22 19:07:09 -07:00
|
|
|
req, err := doh.NewRequestWithContext(ctx, p.dohMethod, p.addr, p.dohHost, state.Req)
|
2026-06-15 02:54:05 +02:00
|
|
|
if err != nil {
|
2026-07-01 23:04:04 -05:00
|
|
|
return nil, nil, proto, err
|
2026-06-15 02:54:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
resp, err := p.transport.httpClient.Do(req)
|
|
|
|
|
if err != nil {
|
2026-07-01 23:04:04 -05:00
|
|
|
return nil, localAddr, proto, err
|
2026-06-15 02:54:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ResponseToMsg always closes the body via defer resp.Body.Close().
|
|
|
|
|
ret, err := doh.ResponseToMsg(resp)
|
|
|
|
|
if err != nil {
|
2026-07-01 23:04:04 -05:00
|
|
|
return nil, localAddr, proto, err
|
2026-06-15 02:54:05 +02:00
|
|
|
}
|
|
|
|
|
|
2026-07-22 19:07:09 -07:00
|
|
|
// recovery the origin Id after upstream.
|
|
|
|
|
if ret != nil {
|
|
|
|
|
ret.Id = originId
|
|
|
|
|
}
|
2026-07-01 23:04:04 -05:00
|
|
|
return ret, localAddr, proto, nil
|
2026-06-15 02:54:05 +02:00
|
|
|
}
|
|
|
|
|
|
2026-09-08 12:51:18 +08:00
|
|
|
func (p *Proxy) lookupDoQ(ctx context.Context, state request.Request, _ Options) (*dns.Msg, net.Addr, string, error) {
|
|
|
|
|
// QUIC runs over UDP. Reporting udp keeps dnstap query_address and
|
|
|
|
|
// response_address consistent with the actual upstream socket.
|
|
|
|
|
const proto = "udp"
|
|
|
|
|
if p.doq == nil {
|
|
|
|
|
return nil, nil, proto, errors.New("proxy: DoQ transport is not initialized")
|
|
|
|
|
}
|
|
|
|
|
ret, localAddr, err := p.doq.exchange(ctx, state.Req, p.readTimeout)
|
|
|
|
|
return ret, localAddr, proto, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-01 23:04:04 -05:00
|
|
|
// Connect selects an upstream, sends the request and waits for a response. It
|
|
|
|
|
// also returns CoreDNS's own outbound address on the upstream socket
|
|
|
|
|
// (localAddr) and the transport proto ("udp" or "tcp") actually used to reach
|
|
|
|
|
// the upstream.
|
|
|
|
|
func (p *Proxy) Connect(ctx context.Context, state request.Request, opts Options) (*dns.Msg, net.Addr, string, error) {
|
2026-06-15 02:54:05 +02:00
|
|
|
start := time.Now()
|
|
|
|
|
originId := state.Req.Id
|
|
|
|
|
|
|
|
|
|
var (
|
2026-07-01 23:04:04 -05:00
|
|
|
ret *dns.Msg
|
|
|
|
|
localAddr net.Addr
|
|
|
|
|
proto string
|
|
|
|
|
err error
|
2026-06-15 02:54:05 +02:00
|
|
|
)
|
|
|
|
|
switch p.protocol {
|
|
|
|
|
case transport.HTTPS:
|
2026-07-01 23:04:04 -05:00
|
|
|
ret, localAddr, proto, err = p.lookupDoH(ctx, state, opts)
|
2026-09-08 12:51:18 +08:00
|
|
|
case transport.QUIC:
|
|
|
|
|
ret, localAddr, proto, err = p.lookupDoQ(ctx, state, opts)
|
2026-06-15 02:54:05 +02:00
|
|
|
case transport.DNS, transport.TLS:
|
2026-07-01 23:04:04 -05:00
|
|
|
ret, localAddr, proto, err = p.lookupDNS(ctx, state, opts)
|
2026-06-15 02:54:05 +02:00
|
|
|
default:
|
2026-07-01 23:04:04 -05:00
|
|
|
return nil, nil, "", fmt.Errorf("transport %s not supported to proxy", p.protocol)
|
2026-06-15 02:54:05 +02:00
|
|
|
}
|
|
|
|
|
if err != nil {
|
2026-07-01 23:04:04 -05:00
|
|
|
return nil, localAddr, proto, err
|
2026-06-15 02:54:05 +02:00
|
|
|
}
|
|
|
|
|
|
2021-10-09 01:34:22 +08:00
|
|
|
// recovery the origin Id after upstream.
|
|
|
|
|
ret.Id = originId
|
2018-02-05 22:00:47 +00:00
|
|
|
|
2018-07-07 10:14:21 +03:00
|
|
|
rc, ok := dns.RcodeToString[ret.Rcode]
|
|
|
|
|
if !ok {
|
|
|
|
|
rc = strconv.Itoa(ret.Rcode)
|
2018-02-05 22:00:47 +00:00
|
|
|
}
|
|
|
|
|
|
2023-07-04 15:35:55 +01:00
|
|
|
requestDuration.WithLabelValues(p.proxyName, p.addr, rc).Observe(time.Since(start).Seconds())
|
2018-07-07 10:14:21 +03:00
|
|
|
|
2026-07-01 23:04:04 -05:00
|
|
|
return ret, localAddr, proto, nil
|
2018-02-05 22:00:47 +00:00
|
|
|
}
|
2018-04-11 09:50:06 +03:00
|
|
|
|
2018-06-15 02:37:22 -04:00
|
|
|
const cumulativeAvgWeight = 4
|
2023-09-07 12:01:45 -07:00
|
|
|
|
|
|
|
|
// Function to determine if a response should be truncated.
|
|
|
|
|
func shouldTruncateResponse(err error) bool {
|
|
|
|
|
// This is to handle a scenario in which upstream sets the TC bit, but doesn't truncate the response
|
|
|
|
|
// and we get ErrBuf instead of overflow.
|
|
|
|
|
if _, isDNSErr := err.(*dns.Error); isDNSErr && errors.Is(err, dns.ErrBuf) {
|
|
|
|
|
return true
|
|
|
|
|
} else if strings.Contains(err.Error(), "overflow") {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Function to return an empty response with TC (truncated) bit set.
|
|
|
|
|
func truncateResponse(response *dns.Msg) *dns.Msg {
|
|
|
|
|
// Clear out Answer, Extra, and Ns sections
|
|
|
|
|
response.Answer = nil
|
|
|
|
|
response.Extra = nil
|
|
|
|
|
response.Ns = nil
|
|
|
|
|
|
|
|
|
|
// Set TC bit to indicate truncation.
|
|
|
|
|
response.Truncated = true
|
|
|
|
|
return response
|
|
|
|
|
}
|