From 78378a11c1f4a9df3542474c7363038c875afacb Mon Sep 17 00:00:00 2001 From: Eugene Burkov Date: Wed, 10 Apr 2024 19:02:03 +0300 Subject: [PATCH] Pull request 342: Fix config validation Squashed commit of the following: commit f4dc4f3730119d491f78ff5a11c2ef70177bb6eb Author: Eugene Burkov Date: Wed Apr 10 18:47:46 2024 +0300 proxy: imp docs commit c9ee71514de8824319c0be5785228eb3f3014e0b Author: Eugene Burkov Date: Wed Apr 10 18:39:45 2024 +0300 proxy: fix default values --- proxy/proxy.go | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/proxy/proxy.go b/proxy/proxy.go index bd1bd3b46..464cfa562 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -3,6 +3,7 @@ package proxy import ( + "cmp" "context" "fmt" "io" @@ -200,15 +201,23 @@ type Proxy struct { } // New creates a new Proxy with the specified configuration. c must not be nil. +// +// TODO(e.burkov): Cover with tests. func New(c *Config) (p *Proxy, err error) { p = &Proxy{ - Config: *c, - privateNets: netutil.SubnetSetFunc(netutil.IsLocallyServed), - beforeRequestHandler: noopRequestHandler{}, - upstreamRTTStats: map[string]upstreamRTTStats{}, - rttLock: sync.Mutex{}, - ratelimitLock: sync.Mutex{}, - RWMutex: sync.RWMutex{}, + Config: *c, + privateNets: cmp.Or[netutil.SubnetSet]( + c.PrivateSubnets, + netutil.SubnetSetFunc(netutil.IsLocallyServed), + ), + beforeRequestHandler: cmp.Or[BeforeRequestHandler]( + c.BeforeRequestHandler, + noopRequestHandler{}, + ), + upstreamRTTStats: map[string]upstreamRTTStats{}, + rttLock: sync.Mutex{}, + ratelimitLock: sync.Mutex{}, + RWMutex: sync.RWMutex{}, bytesPool: &sync.Pool{ New: func() any { // 2 bytes may be used to store packet length (see TCP/TLS). @@ -217,9 +226,12 @@ func New(c *Config) (p *Proxy, err error) { return &b }, }, - udpOOBSize: proxynetutil.UDPGetOOBSize(), - time: realClock{}, - messages: defaultMessageConstructor{}, + udpOOBSize: proxynetutil.UDPGetOOBSize(), + time: realClock{}, + messages: cmp.Or[MessageConstructor]( + c.MessageConstructor, + defaultMessageConstructor{}, + ), recDetector: newRecursionDetector(recursionTTL, cachedRecurrentReqNum), } @@ -260,16 +272,6 @@ func New(c *Config) (p *Proxy, err error) { return nil, fmt.Errorf("setting up DNS64: %w", err) } - if c.MessageConstructor != nil { - p.messages = c.MessageConstructor - } - if c.PrivateSubnets != nil { - p.privateNets = c.PrivateSubnets - } - if c.BeforeRequestHandler != nil { - p.beforeRequestHandler = c.BeforeRequestHandler - } - p.RatelimitWhitelist = slices.Clone(p.RatelimitWhitelist) slices.SortFunc(p.RatelimitWhitelist, netip.Addr.Compare)