Skip to content

Commit a614461

Browse files
database64128seankhliao
authored andcommitted
crypto/tls: use context.AfterFunc in handshakeContext
This saves a goroutine when ctx can be canceled but is not canceled during the handshakeContext call. Use ctx consistently, because in this path (c.quic == nil) handshakeCtx will only be canceled when ctx is canceled. Change-Id: I7f4565119f30d589dce026b0d7ef3c324220525a Reviewed-on: https://go-review.googlesource.com/c/go/+/699895 Reviewed-by: Roland Shoemaker <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Daniel McCarney <[email protected]> Reviewed-by: Michael Pratt <[email protected]>
1 parent e8126bc commit a614461

File tree

1 file changed

+7
-21
lines changed

1 file changed

+7
-21
lines changed

src/crypto/tls/conn.go

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1524,7 +1524,7 @@ func (c *Conn) handshakeContext(ctx context.Context) (ret error) {
15241524
}
15251525

15261526
handshakeCtx, cancel := context.WithCancel(ctx)
1527-
// Note: defer this before starting the "interrupter" goroutine
1527+
// Note: defer this before calling context.AfterFunc
15281528
// so that we can tell the difference between the input being canceled and
15291529
// this cancellation. In the former case, we need to close the connection.
15301530
defer cancel()
@@ -1533,28 +1533,14 @@ func (c *Conn) handshakeContext(ctx context.Context) (ret error) {
15331533
c.quic.cancelc = handshakeCtx.Done()
15341534
c.quic.cancel = cancel
15351535
} else if ctx.Done() != nil {
1536-
// Start the "interrupter" goroutine, if this context might be canceled.
1537-
// (The background context cannot).
1538-
//
1539-
// The interrupter goroutine waits for the input context to be done and
1540-
// closes the connection if this happens before the function returns.
1541-
done := make(chan struct{})
1542-
interruptRes := make(chan error, 1)
1536+
// Close the connection if ctx is canceled before the function returns.
1537+
stop := context.AfterFunc(ctx, func() {
1538+
_ = c.conn.Close()
1539+
})
15431540
defer func() {
1544-
close(done)
1545-
if ctxErr := <-interruptRes; ctxErr != nil {
1541+
if !stop() {
15461542
// Return context error to user.
1547-
ret = ctxErr
1548-
}
1549-
}()
1550-
go func() {
1551-
select {
1552-
case <-handshakeCtx.Done():
1553-
// Close the connection, discarding the error
1554-
_ = c.conn.Close()
1555-
interruptRes <- handshakeCtx.Err()
1556-
case <-done:
1557-
interruptRes <- nil
1543+
ret = ctx.Err()
15581544
}
15591545
}()
15601546
}

0 commit comments

Comments
 (0)