diff --git a/pkg/tlsx/ztls/ztls.go b/pkg/tlsx/ztls/ztls.go index a03b7267..cf5b7427 100644 --- a/pkg/tlsx/ztls/ztls.go +++ b/pkg/tlsx/ztls/ztls.go @@ -320,20 +320,22 @@ func (c *Client) getConfig(hostname, ip, port string, options clients.ConnectOpt return config, nil } -// tlsHandshakeWithCtx attempts tls handshake with given timeout +// tlsHandshakeWithTimeout attempts tls handshake with given timeout func (c *Client) tlsHandshakeWithTimeout(tlsConn *tls.Conn, ctx context.Context) error { errChan := make(chan error, 1) - defer close(errChan) + go func() { + errChan <- tlsConn.Handshake() + }() select { case <-ctx.Done(): + // Close the connection to abort the handshake + _ = tlsConn.Close() return errorutil.NewWithTag("ztls", "timeout while attempting handshake") //nolint - case errChan <- tlsConn.Handshake(): - } - - err := <-errChan - if err == tls.ErrCertsOnly { - err = nil + case err := <-errChan: + if err == tls.ErrCertsOnly { + err = nil + } + return err } - return err }