Improve host name resolution for TCP proxy

This commit is contained in:
HMH 2021-03-23 10:24:03 +00:00 committed by GitHub
parent 29908098e4
commit 8947f85ddd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 59 deletions

View file

@ -31,7 +31,7 @@ func NewProxy(address string, terminationDelay time.Duration, proxyProtocol *dyn
return nil, fmt.Errorf("unknown proxyProtocol version: %d", proxyProtocol.Version)
}
// enable the refresh of the target only if the address in an IP
// enable the refresh of the target only if the address in not an IP
refreshTarget := false
if host, _, err := net.SplitHostPort(address); err == nil && net.ParseIP(host) == nil {
refreshTarget = true
@ -48,23 +48,14 @@ func NewProxy(address string, terminationDelay time.Duration, proxyProtocol *dyn
// ServeTCP forwards the connection to a service.
func (p *Proxy) ServeTCP(conn WriteCloser) {
log.Debugf("Handling connection from %s", conn.RemoteAddr())
log.WithoutContext().Debugf("Handling connection from %s", conn.RemoteAddr())
// needed because of e.g. server.trackedConnection
defer conn.Close()
if p.refreshTarget {
tcpAddr, err := net.ResolveTCPAddr("tcp", p.address)
if err != nil {
log.Errorf("Error resolving tcp address: %v", err)
return
}
p.target = tcpAddr
}
connBackend, err := net.DialTCP("tcp", nil, p.target)
connBackend, err := p.dialBackend()
if err != nil {
log.Errorf("Error while connection to backend: %v", err)
log.WithoutContext().Errorf("Error while connecting to backend: %v", err)
return
}
@ -91,6 +82,19 @@ func (p *Proxy) ServeTCP(conn WriteCloser) {
<-errChan
}
func (p Proxy) dialBackend() (*net.TCPConn, error) {
if !p.refreshTarget {
return net.DialTCP("tcp", nil, p.target)
}
conn, err := net.Dial("tcp", p.address)
if err != nil {
return nil, err
}
return conn.(*net.TCPConn), nil
}
func (p Proxy) connCopy(dst, src WriteCloser, errCh chan error) {
_, err := io.Copy(dst, src)
errCh <- err