diff --git a/doc/go1.16.html b/doc/go1.16.html index 99e8e3c980d..a97c3698855 100644 --- a/doc/go1.16.html +++ b/doc/go1.16.html @@ -237,12 +237,18 @@ Do not send CLs removing the interior tags from such phrases.

I/O operations on closing or closed TLS connections can now be detected using - the new ErrClosed error. A typical use - would be errors.Is(err, net.ErrClosed). In earlier releases + the new ErrClosed error. A typical use + would be errors.Is(err, net.ErrClosed). In earlier releases the only way to reliably detect this case was to match the string returned by the Error method with "tls: use of closed connection".

+

+ A default deadline is set in Close + before sending the close notify alert, in order to prevent blocking + indefinitely. +

+

crypto/x509

diff --git a/src/crypto/tls/conn.go b/src/crypto/tls/conn.go index f1d4cb926c0..ada19d6e7ae 100644 --- a/src/crypto/tls/conn.go +++ b/src/crypto/tls/conn.go @@ -1074,6 +1074,11 @@ var ( ) // Write writes data to the connection. +// +// As Write calls Handshake, in order to prevent indefinite blocking a deadline +// must be set for both Read and Write before Write is called when the handshake +// has not yet completed. See SetDeadline, SetReadDeadline, and +// SetWriteDeadline. func (c *Conn) Write(b []byte) (int, error) { // interlock with Close below for { @@ -1232,8 +1237,12 @@ func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error { return nil } -// Read can be made to time out and return a net.Error with Timeout() == true -// after a fixed time limit; see SetDeadline and SetReadDeadline. +// Read reads data from the connection. +// +// As Read calls Handshake, in order to prevent indefinite blocking a deadline +// must be set for both Read and Write before Read is called when the handshake +// has not yet completed. See SetDeadline, SetReadDeadline, and +// SetWriteDeadline. func (c *Conn) Read(b []byte) (int, error) { if err := c.Handshake(); err != nil { return 0, err @@ -1301,9 +1310,10 @@ func (c *Conn) Close() error { } var alertErr error - if c.handshakeComplete() { - alertErr = c.closeNotify() + if err := c.closeNotify(); err != nil { + alertErr = fmt.Errorf("tls: failed to send closeNotify alert (but connection was closed anyway): %w", err) + } } if err := c.conn.Close(); err != nil { @@ -1330,8 +1340,12 @@ func (c *Conn) closeNotify() error { defer c.out.Unlock() if !c.closeNotifySent { + // Set a Write Deadline to prevent possibly blocking forever. + c.SetWriteDeadline(time.Now().Add(time.Second * 5)) c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify) c.closeNotifySent = true + // Any subsequent writes will fail. + c.SetWriteDeadline(time.Now()) } return c.closeNotifyErr }