Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set read deadline while making tlsConn handshake #267

Merged
merged 4 commits into from
Jun 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 19 additions & 10 deletions pkg/tlsx/ztls/ztls.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,6 @@ func (c *Client) ConnectWithOptions(hostname, ip, port string, options clients.C

// new tls connection
tlsConn := tls.Client(conn, config)

if err := c.tlsHandshakeWithTimeout(tlsConn, ctx); err != nil {
return nil, errorutil.NewWithTag("ztls", "could not do tls handshake").Wrap(err)
}
Expand Down Expand Up @@ -269,18 +268,28 @@ func (c *Client) getConfig(hostname, ip, port string, options clients.ConnectOpt

// tlsHandshakeWithCtx attempts tls handshake with given timeout
func (c *Client) tlsHandshakeWithTimeout(tlsConn *tls.Conn, ctx context.Context) error {
// set read deadline
ShubhamRasal marked this conversation as resolved.
Show resolved Hide resolved
if err := tlsConn.SetReadDeadline(time.Now().Add(time.Duration(c.options.Timeout) * time.Second)); err != nil {
return errorutil.NewWithTag("ztls", "could not set read deadline").Wrap(err)
}
errChan := make(chan error, 1)
defer close(errChan)
done := make(chan struct{})
defer close(done)

go func() {
select {
case errChan <- tlsConn.Handshake():
case <-done:
}
}()

select {
case <-ctx.Done():
errChan <- errorutil.NewWithTag("ztls", "timeout while attempting handshake")
case errChan <- tlsConn.Handshake():
}

err := <-errChan
if err == tls.ErrCertsOnly {
err = nil
return errorutil.NewWithTag("ztls", "timeout while attempting handshake")
case err := <-errChan:
if err == tls.ErrCertsOnly {
err = nil
}
return err
}
return err
}