2019-03-14 08:30:04 +00:00
|
|
|
package tcp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
|
2019-08-03 01:58:23 +00:00
|
|
|
"github.com/containous/traefik/v2/pkg/log"
|
2019-03-14 08:30:04 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Proxy forwards a TCP request to a TCP service
|
|
|
|
type Proxy struct {
|
|
|
|
target *net.TCPAddr
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewProxy creates a new Proxy
|
|
|
|
func NewProxy(address string) (*Proxy, error) {
|
|
|
|
tcpAddr, err := net.ResolveTCPAddr("tcp", address)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-05-09 12:30:06 +00:00
|
|
|
|
|
|
|
return &Proxy{target: tcpAddr}, nil
|
2019-03-14 08:30:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ServeTCP forwards the connection to a service
|
|
|
|
func (p *Proxy) ServeTCP(conn net.Conn) {
|
|
|
|
log.Debugf("Handling connection from %s", conn.RemoteAddr())
|
|
|
|
defer conn.Close()
|
2019-05-09 12:30:06 +00:00
|
|
|
|
2019-03-14 08:30:04 +00:00
|
|
|
connBackend, err := net.DialTCP("tcp", nil, p.target)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Error while connection to backend: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer connBackend.Close()
|
|
|
|
|
|
|
|
errChan := make(chan error, 1)
|
|
|
|
go connCopy(conn, connBackend, errChan)
|
|
|
|
go connCopy(connBackend, conn, errChan)
|
|
|
|
|
|
|
|
err = <-errChan
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Error during connection: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func connCopy(dst, src net.Conn, errCh chan error) {
|
|
|
|
_, err := io.Copy(dst, src)
|
|
|
|
errCh <- err
|
|
|
|
}
|