diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index 4ee32ef1b..b9f1fd003 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -573,12 +573,13 @@ final class SocketChannel: BaseSocketChannel { self.parent = parent } - override fileprivate func readFromSocket() throws { + override fileprivate func readFromSocket() throws -> ReadResult { // Just allocate one time for the while read loop. This is fine as ByteBuffer is a struct and uses COW. var buffer = recvAllocator.buffer(allocator: allocator) + var result = ReadResult.none for i in 1...maxMessagesPerRead { if closed { - return + return result } switch try buffer.withMutableWritePointer(body: self.socket.read(pointer:size:)) { case .processed(let bytesRead): @@ -597,15 +598,17 @@ final class SocketChannel: BaseSocketChannel { // Reset reader and writerIndex and so allow to have the buffer filled again buffer.clear() } + result = .some } else { // end-of-file throw ChannelError.eof } case .wouldBlock(let bytesRead): assert(bytesRead == 0) - return + return result } } + return result } override fileprivate func writeToSocket(pendingWrites: PendingWritesManager) throws -> WriteResult { @@ -746,14 +749,15 @@ final class ServerSocketChannel : BaseSocketChannel { throw ChannelError.operationUnsupported } - override fileprivate func readFromSocket() throws { + override fileprivate func readFromSocket() throws -> ReadResult { + var result = ReadResult.none for _ in 1...maxMessagesPerRead { if closed { - return + return result } if let accepted = try self.socket.accept() { readPending = false - + result = .some do { let chan = try SocketChannel(socket: accepted, eventLoop: group.next() as! SelectableEventLoop, parent: self) pipeline.fireChannelRead0(data: NIOAny(chan)) @@ -762,9 +766,10 @@ final class ServerSocketChannel : BaseSocketChannel { throw err } } else { - return + break } } + return result } override fileprivate func writeToSocket(pendingWrites: PendingWritesManager) throws -> WriteResult { @@ -941,6 +946,9 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { public final var _unsafe: ChannelCore { return self } + // Guard against re-entrance of flushNow() method. + private var inFlushNow: Bool = false + // Visible to access from EventLoop directly let socket: T public var interestedEvent: IOEvent = .none @@ -1078,11 +1086,16 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } } - final func readIfNeeded0() { + /// Triggers a `ChannelPipeline.read()` if `autoRead` is enabled.` + /// + /// - returns: `true` if `readPending` is `true`, `false` otherwise. + @discardableResult final func readIfNeeded0() -> Bool { assert(eventLoop.inEventLoop) - if autoRead { + + if !readPending && autoRead { pipeline.read0(promise: nil) } + return readPending } // Methods invoked from the HeadHandler of the ChannelPipeline @@ -1360,11 +1373,26 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { } } - fileprivate func readFromSocket() throws { + /// Read data from the underlying socket and dispatch it to the `ChannelPipeline` + /// + /// - returns: `true` if any data was read, `false` otherwise. + @discardableResult fileprivate func readFromSocket() throws -> ReadResult { fatalError("this must be overridden by sub class") } + + fileprivate enum ReadResult { + /// Nothing was read by the read operation. + case none + + /// Some data was read by the read operation. + case some + } - + /// Write data from the underlying socket. + /// + /// - parameters: + /// - pendingWrites: `PendingWritesManager` that holds all the pending writes that may be ready to be written to the underlying socket. + /// - returns: `true` if any data was read, `false` otherwise. fileprivate func writeToSocket(pendingWrites: PendingWritesManager) throws -> WriteResult { fatalError("this must be overridden by sub class") } @@ -1417,8 +1445,20 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { return false } } - + private func flushNow() -> Bool { + // Guard against re-entry as data that will be put into `pendingWrites` will just be picked up by + // `writeToSocket`. + guard !inFlushNow else { + return true + } + + defer { + inFlushNow = false + } + + inFlushNow = true + while !closed { do { switch try self.writeToSocket(pendingWrites: pendingWrites) { @@ -1435,6 +1475,16 @@ class BaseSocketChannel : SelectableChannel, ChannelCore { return true } } catch let err { + // If there is a write error we should try drain the inbound before closing the socket as there may be some data pending. + // We ignore any error that is thrown as we will use the original err to close the channel and notify the user. + if readIfNeeded0() { + + // We need to continue reading until there is nothing more to be read from the socket as we will not have another chance to drain it. + while let read = try? readFromSocket(), read == .some { + pipeline.fireChannelReadComplete() + } + } + close0(error: err, promise: nil) // we handled all writes diff --git a/Sources/NIO/System.swift b/Sources/NIO/System.swift index 8aad504f9..c49bee8d5 100644 --- a/Sources/NIO/System.swift +++ b/Sources/NIO/System.swift @@ -130,9 +130,17 @@ internal enum Posix { public static func socket(domain: Int32, type: Int32, `protocol`: Int32) throws -> Int32 { return try wrapSyscall({ #if os(Linux) + /* no SO_NOSIGPIPE on Linux :( */ + let _ = unsafeBitCast(Glibc.signal(SIGPIPE, SIG_IGN) as sighandler_t?, to: Int.self) + return Int32(Glibc.socket(domain, type, `protocol`)) #else - return Int32(Darwin.socket(domain, type, `protocol`)) + let fd = Darwin.socket(domain, type, `protocol`) + if fd != -1 { + _ = try? Posix.fcntl(descriptor: fd, command: F_SETNOSIGPIPE, value: 1) + } + + return Int32(fd) #endif }) } @@ -164,9 +172,6 @@ internal enum Posix { public static func listen(descriptor: Int32, backlog: Int32) throws { _ = try wrapSyscall({ () -> Int32 in #if os(Linux) - /* no SO_NOSIGPIPE on Linux :( */ - let _ = unsafeBitCast(Glibc.signal(SIGPIPE, SIG_IGN) as sighandler_t?, to: Int.self) - return Glibc.listen(descriptor, backlog) #else return Darwin.listen(descriptor, backlog) @@ -202,6 +207,7 @@ internal enum Posix { public static func connect(descriptor: Int32, addr: UnsafePointer, size: Int) throws -> Bool { do { _ = try wrapSyscall({ () -> Int in + #if os(Linux) return Int(Glibc.connect(descriptor, addr, socklen_t(size))) #else diff --git a/Tests/NIOTests/EchoServerClientTest+XCTest.swift b/Tests/NIOTests/EchoServerClientTest+XCTest.swift index 50994f409..cf0cbff0e 100644 --- a/Tests/NIOTests/EchoServerClientTest+XCTest.swift +++ b/Tests/NIOTests/EchoServerClientTest+XCTest.swift @@ -37,6 +37,7 @@ extension EchoServerClientTest { ("testWriteOnConnect", testWriteOnConnect), ("testWriteOnAccept", testWriteOnAccept), ("testWriteAfterChannelIsDead", testWriteAfterChannelIsDead), + ("testPendingReadProcessedAfterWriteError", testPendingReadProcessedAfterWriteError), ] } } diff --git a/Tests/NIOTests/EchoServerClientTest.swift b/Tests/NIOTests/EchoServerClientTest.swift index 55768bd07..f248a5a56 100644 --- a/Tests/NIOTests/EchoServerClientTest.swift +++ b/Tests/NIOTests/EchoServerClientTest.swift @@ -635,4 +635,99 @@ class EchoServerClientTest : XCTestCase { try! group.syncShutdownGracefully() } + + func testPendingReadProcessedAfterWriteError() throws { + let group = MultiThreadedEventLoopGroup(numThreads: 1) + let dpGroup = DispatchGroup() + + dpGroup.enter() + + let str = "hi there" + + let countingHandler = ByteCountingHandler(numBytes: str.utf8.count * 4, promise: group.next().newPromise()) + + class WriteHandler : ChannelInboundHandler { + typealias InboundIn = ByteBuffer + + private var writeFailed = false + + func channelActive(ctx: ChannelHandlerContext) { + var buffer = ctx.channel!.allocator.buffer(capacity: 4) + buffer.write(string: "test") + writeUntilFailed(ctx, buffer) + } + + private func writeUntilFailed(_ ctx: ChannelHandlerContext, _ buffer: ByteBuffer) { + ctx.writeAndFlush(data: NIOAny(buffer)).whenSuccess { _ in + ctx.eventLoop.execute { + self.writeUntilFailed(ctx, buffer) + } + } + } + } + + class WriteWhenActiveHandler: ChannelInboundHandler { + typealias InboundIn = ByteBuffer + let str: String + let dpGroup: DispatchGroup + + init(_ str: String, _ dpGroup: DispatchGroup) { + self.str = str + self.dpGroup = dpGroup + } + + func channelActive(ctx: ChannelHandlerContext) { + ctx.fireChannelActive() + var buffer = ctx.channel!.allocator.buffer(capacity: str.utf8.count) + buffer.write(string: str) + + // write it four times and then close the connect. + ctx.writeAndFlush(data: NIOAny(buffer)).then{ _ in + ctx.writeAndFlush(data: NIOAny(buffer)).then{ _ in + ctx.writeAndFlush(data: NIOAny(buffer)).then{ _ in + ctx.writeAndFlush(data: NIOAny(buffer)).then{ _ in + ctx.close() + } + } + } + }.whenComplete{ _ in + self.dpGroup.leave() + } + } + } + let serverChannel = try ServerBootstrap(group: group) + .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) + .childChannelOption(ChannelOptions.socket(SocketOptionLevel(IPPROTO_TCP), TCP_NODELAY), value: 1) + .childChannelInitializer { channel in + return channel.pipeline.add(handler: WriteWhenActiveHandler(str, dpGroup)) + }.bind(to: "127.0.0.1", on: 0).wait() + + defer { + _ = serverChannel.close() + } + + let clientChannel = try ClientBootstrap(group: group) + // We will only start reading once we wrote all data on the accepted channel. + //.channelOption(ChannelOptions.autoRead, value: false) + .channelOption(ChannelOptions.recvAllocator, value: FixedSizeRecvByteBufferAllocator(capacity: 2)) + .channelInitializer{ channel in + return channel.pipeline.add(handler: WriteHandler()).then{ _ in + return channel.pipeline.add(handler: countingHandler) + } + }.connect(to: serverChannel.localAddress!).wait() + defer { + _ = clientChannel.close() + } + dpGroup.wait() + + var completeBuffer = clientChannel.allocator.buffer(capacity: str.utf8.count * 4) + completeBuffer.write(string: str) + completeBuffer.write(string: str) + completeBuffer.write(string: str) + completeBuffer.write(string: str) + + try countingHandler.assertReceived(buffer: completeBuffer) + + try! group.syncShutdownGracefully() + } }