From 5db9436e872075dbb82b1ebf9d4d60ab47b98c6e Mon Sep 17 00:00:00 2001 From: Shmuel Kallner Date: Mon, 5 Dec 2016 19:05:38 +0200 Subject: [PATCH 1/2] IBM-Swift/Kitura#902 Fix leaks when errors occur and when keep alive closes a socket --- Sources/KituraNet/IncomingSocketHandler.swift | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/Sources/KituraNet/IncomingSocketHandler.swift b/Sources/KituraNet/IncomingSocketHandler.swift index 8ed011e..45022b5 100644 --- a/Sources/KituraNet/IncomingSocketHandler.swift +++ b/Sources/KituraNet/IncomingSocketHandler.swift @@ -200,6 +200,11 @@ public class IncomingSocketHandler { } else { Log.error("Write to socket (file descriptor \(socket.socketfd)) failed. Error = \(error).") } + + // There was an error writing to the socket, close the socket + writeBuffer.length = 0 + writeBufferPosition = 0 + prepareToClose() } #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || GCD_ASYNCH @@ -209,7 +214,7 @@ public class IncomingSocketHandler { #endif } - if preparingToClose { + if preparingToClose && writeBuffer.length == writeBufferPosition { close() } } @@ -277,11 +282,12 @@ public class IncomingSocketHandler { /// be closed when all the buffered data has been written. /// Otherwise, immediately close the socket. public func prepareToClose() { - if writeBuffer.length == writeBufferPosition { - close() - } - else { + if !preparingToClose { preparingToClose = true + + if writeBuffer.length == writeBufferPosition { + close() + } } } @@ -304,5 +310,6 @@ public class IncomingSocketHandler { } processor?.inProgress = false processor?.keepAliveUntil = 0.0 + processor?.close() } } From e2599d30911721092a0fb4af181eb7328e590fdd Mon Sep 17 00:00:00 2001 From: Shmuel Kallner Date: Mon, 5 Dec 2016 19:06:20 +0200 Subject: [PATCH 2/2] IBM-Swift/Kitura#902 Prevent unwrapping failure if the IncomingSockettProcessor was freed --- Sources/KituraNet/HTTP/HTTPServerResponse.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/KituraNet/HTTP/HTTPServerResponse.swift b/Sources/KituraNet/HTTP/HTTPServerResponse.swift index 913642f..88ebb01 100644 --- a/Sources/KituraNet/HTTP/HTTPServerResponse.swift +++ b/Sources/KituraNet/HTTP/HTTPServerResponse.swift @@ -118,8 +118,8 @@ public class HTTPServerResponse : ServerResponse { if !keepAlive && !processor.isUpgrade { processor.close() } + Monitor.delegate?.finished(request: processor.request, response: self) } - Monitor.delegate?.finished(request: processor?.request, response: self) } /// Begin flushing the buffer