Skip to content

Fix crash if connection is closed very early #671

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

Merged
merged 3 commits into from
Mar 14, 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
Original file line number Diff line number Diff line change
Expand Up @@ -361,14 +361,19 @@ extension HTTPConnectionPool.ConnectionFactory {
var channelFuture = bootstrapFuture.flatMap { bootstrap -> EventLoopFuture<Channel> in
return bootstrap.connect(target: self.key.connectionTarget)
}.flatMap { channel -> EventLoopFuture<(Channel, String?)> in
// It is save to use `try!` here, since we are sure, that a `TLSEventsHandler` exists
// within the pipeline. It is added in `makeTLSBootstrap`.
let tlsEventHandler = try! channel.pipeline.syncOperations.handler(type: TLSEventsHandler.self)

// The tlsEstablishedFuture is set as soon as the TLSEventsHandler is in a
// pipeline. It is created in TLSEventsHandler's handlerAdded method.
return tlsEventHandler.tlsEstablishedFuture!.flatMap { negotiated in
channel.pipeline.removeHandler(tlsEventHandler).map { (channel, negotiated) }
do {
// if the channel is closed before flatMap is executed, all ChannelHandler are removed
// and TLSEventsHandler is therefore not present either
let tlsEventHandler = try channel.pipeline.syncOperations.handler(type: TLSEventsHandler.self)

// The tlsEstablishedFuture is set as soon as the TLSEventsHandler is in a
// pipeline. It is created in TLSEventsHandler's handlerAdded method.
return tlsEventHandler.tlsEstablishedFuture!.flatMap { negotiated in
channel.pipeline.removeHandler(tlsEventHandler).map { (channel, negotiated) }
}
} catch {
assert(channel.isActive == false, "if the channel is still active then TLSEventsHandler must be present but got error \(error)")
return channel.eventLoop.makeFailedFuture(HTTPClientError.remoteConnectionClosed)
}
}

Expand Down