diff --git a/Sources/NIO/BaseSocket.swift b/Sources/NIO/BaseSocket.swift index 07b91c2e6..b91af079c 100644 --- a/Sources/NIO/BaseSocket.swift +++ b/Sources/NIO/BaseSocket.swift @@ -180,10 +180,17 @@ extension sockaddr_storage { /// /// This should not be created directly but one of its sub-classes should be used, like `ServerSocket` or `Socket`. class BaseSocket: Selectable { - - public let descriptor: Int32 + + private let descriptor: Int32 public private(set) var open: Bool + func withUnsafeFileDescriptor(_ fn: (Int32) throws -> T) throws -> T { + guard self.open else { + throw IOError(errnoCode: EBADF, reason: "file descriptor already closed!") + } + return try fn(descriptor) + } + /// Returns the local bound `SocketAddress` of the socket. /// /// - returns: The local bound address. @@ -206,7 +213,10 @@ class BaseSocket: Selectable { try addr.withMutableSockAddr { addressPtr, size in var size = socklen_t(size) - try fn(self.descriptor, addressPtr, &size) + + try withUnsafeFileDescriptor { fd in + try fn(fd, addressPtr, &size) + } } return addr.convert() } @@ -264,11 +274,9 @@ class BaseSocket: Selectable { /// /// throws: An `IOError` if the operation failed. final func setNonBlocking() throws { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't control file descriptor as it's not open anymore.") + return try withUnsafeFileDescriptor { fd in + try Posix.fcntl(descriptor: fd, command: F_SETFL, value: O_NONBLOCK) } - - try Posix.fcntl(descriptor: descriptor, command: F_SETFL, value: O_NONBLOCK) } /// Set the given socket option. @@ -281,18 +289,16 @@ class BaseSocket: Selectable { /// - value: The value for the option. /// - throws: An `IOError` if the operation failed. final func setOption(level: Int32, name: Int32, value: T) throws { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't set socket options as it's not open anymore.") + try withUnsafeFileDescriptor { fd in + var val = value + + _ = try Posix.setsockopt( + socket: fd, + level: level, + optionName: name, + optionValue: &val, + optionLen: socklen_t(MemoryLayout.size(ofValue: val))) } - - var val = value - - _ = try Posix.setsockopt( - socket: self.descriptor, - level: level, - optionName: name, - optionValue: &val, - optionLen: socklen_t(MemoryLayout.size(ofValue: val))) } /// Get the given socket option value. @@ -304,19 +310,17 @@ class BaseSocket: Selectable { /// - name: The name of the option to set. /// - throws: An `IOError` if the operation failed. final func getOption(level: Int32, name: Int32) throws -> T { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't get socket options as it's not open anymore.") + return try withUnsafeFileDescriptor { fd in + var length = socklen_t(MemoryLayout.size) + var val = UnsafeMutablePointer.allocate(capacity: 1) + defer { + val.deinitialize(count: 1) + val.deallocate() + } + + try Posix.getsockopt(socket: fd, level: level, optionName: name, optionValue: val, optionLen: &length) + return val.pointee } - - var length = socklen_t(MemoryLayout.size) - var val = UnsafeMutablePointer.allocate(capacity: 1) - defer { - val.deinitialize(count: 1) - val.deallocate() - } - - try Posix.getsockopt(socket: self.descriptor, level: level, optionName: name, optionValue: val, optionLen: &length) - return val.pointee } /// Bind the socket to the given `SocketAddress`. @@ -325,24 +329,22 @@ class BaseSocket: Selectable { /// - address: The `SocketAddress` to which the socket should be bound. /// - throws: An `IOError` if the operation failed. final func bind(to address: SocketAddress) throws { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't bind socket as it's not open anymore.") - } - - func doBind(ptr: UnsafePointer, bytes: Int) throws { - try Posix.bind(descriptor: self.descriptor, ptr: ptr, bytes: bytes) - } - - switch address { - case .v4(let address): - var addr = address.address - try addr.withSockAddr(doBind) - case .v6(let address): - var addr = address.address - try addr.withSockAddr(doBind) - case .unixDomainSocket(let address): - var addr = address.address - try addr.withSockAddr(doBind) + try withUnsafeFileDescriptor { fd in + func doBind(ptr: UnsafePointer, bytes: Int) throws { + try Posix.bind(descriptor: fd, ptr: ptr, bytes: bytes) + } + + switch address { + case .v4(let address): + var addr = address.address + try addr.withSockAddr(doBind) + case .v6(let address): + var addr = address.address + try addr.withSockAddr(doBind) + case .unixDomainSocket(let address): + var addr = address.address + try addr.withSockAddr(doBind) + } } } @@ -352,12 +354,16 @@ class BaseSocket: Selectable { /// /// - throws: An `IOError` if the operation failed. final func close() throws { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't close socket (as it's not open anymore.") + try withUnsafeFileDescriptor { fd in + try Posix.close(descriptor: fd) } - try Posix.close(descriptor: self.descriptor) - self.open = false } } + +extension BaseSocket: CustomStringConvertible { + var description: String { + return "BaseSocket { fd=\(self.descriptor) } " + } +} diff --git a/Sources/NIO/Selectable.swift b/Sources/NIO/Selectable.swift index ab6119707..2747eec82 100644 --- a/Sources/NIO/Selectable.swift +++ b/Sources/NIO/Selectable.swift @@ -17,12 +17,17 @@ /// - warning: `Selectable`s are not thread-safe, only to be used on the appropriate `EventLoop`. protocol Selectable { - /// The file descriptor itself. - var descriptor: Int32 { get } + /// Will be called with the file descriptor of the `Selectable` if still open, if not it will + /// throw an `IOError`. + /// + /// - parameters: + /// - fn: The closure to execute if the `Selectable` is still open. + /// - throws: If either the `Selectable` was closed before or the closure throws by itself. + func withUnsafeFileDescriptor(_ fn: (Int32) throws -> T) throws -> T /// `true` if this `Selectable` is open (which means it was not closed yet). var open: Bool { get } - /// Close this `Selectable` (and so its `descriptor`). + /// Close this `Selectable` (and so its file descriptor). func close() throws } diff --git a/Sources/NIO/Selector.swift b/Sources/NIO/Selector.swift index 65c0eee91..de543c550 100644 --- a/Sources/NIO/Selector.swift +++ b/Sources/NIO/Selector.swift @@ -179,18 +179,20 @@ final class Selector { private func register_kqueue(selectable: S, interested: IOEvent, oldInterested: IOEvent?) throws { // Allocated on the stack var events = (kevent(), kevent()) - - events.0.ident = UInt(selectable.descriptor) - events.0.filter = Int16(EVFILT_READ) - events.0.fflags = 0 - events.0.data = 0 - events.0.udata = nil - - events.1.ident = UInt(selectable.descriptor) - events.1.filter = Int16(EVFILT_WRITE) - events.1.fflags = 0 - events.1.data = 0 - events.1.udata = nil + try selectable.withUnsafeFileDescriptor { fd in + + events.0.ident = UInt(fd) + events.0.filter = Int16(EVFILT_READ) + events.0.fflags = 0 + events.0.data = 0 + events.0.udata = nil + + events.1.ident = UInt(fd) + events.1.filter = Int16(EVFILT_WRITE) + events.1.fflags = 0 + events.1.data = 0 + events.1.udata = nil + } switch interested { case .read: @@ -267,18 +269,19 @@ final class Selector { throw IOError(errnoCode: EBADF, reason: "can't register on selector as it's \(self.lifecycleState).") } - assert(selectable.open) - assert(registrations[Int(selectable.descriptor)] == nil) -#if os(Linux) - var ev = Epoll.epoll_event() - ev.events = Selector.toEpollEvents(interested: interested) - ev.data.fd = selectable.descriptor - - _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_ADD, fd: selectable.descriptor, event: &ev) -#else - try register_kqueue(selectable: selectable, interested: interested, oldInterested: nil) -#endif - registrations[Int(selectable.descriptor)] = makeRegistration(interested) + try selectable.withUnsafeFileDescriptor { fd in + assert(registrations[Int(fd)] == nil) + #if os(Linux) + var ev = Epoll.epoll_event() + ev.events = Selector.toEpollEvents(interested: interested) + ev.data.fd = fd + + _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_ADD, fd: fd, event: &ev) + #else + try register_kqueue(selectable: selectable, interested: interested, oldInterested: nil) + #endif + registrations[Int(fd)] = makeRegistration(interested) + } } /// Re-register `Selectable`, must be registered via `register` before. @@ -290,21 +293,22 @@ final class Selector { guard self.lifecycleState == .open else { throw IOError(errnoCode: EBADF, reason: "can't re-register on selector as it's \(self.lifecycleState).") } - assert(selectable.open) - var reg = registrations[Int(selectable.descriptor)]! - -#if os(Linux) - var ev = Epoll.epoll_event() - ev.events = Selector.toEpollEvents(interested: interested) - ev.data.fd = selectable.descriptor - - _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_MOD, fd: selectable.descriptor, event: &ev) -#else - try register_kqueue(selectable: selectable, interested: interested, oldInterested: reg.interested) -#endif - reg.interested = interested - registrations[Int(selectable.descriptor)] = reg + try selectable.withUnsafeFileDescriptor { fd in + var reg = registrations[Int(fd)]! + + #if os(Linux) + var ev = Epoll.epoll_event() + ev.events = Selector.toEpollEvents(interested: interested) + ev.data.fd = fd + + _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_MOD, fd: fd, event: &ev) + #else + try register_kqueue(selectable: selectable, interested: interested, oldInterested: reg.interested) + #endif + reg.interested = interested + registrations[Int(fd)] = reg + } } /// Deregister `Selectable`, must be registered via `register` before. @@ -317,18 +321,19 @@ final class Selector { guard self.lifecycleState == .open else { throw IOError(errnoCode: EBADF, reason: "can't deregister from selector as it's \(self.lifecycleState).") } - assert(selectable.open) - guard let reg = registrations.removeValue(forKey: Int(selectable.descriptor)) else { - return + try selectable.withUnsafeFileDescriptor { fd in + guard let reg = registrations.removeValue(forKey: Int(fd)) else { + return + } + + #if os(Linux) + var ev = Epoll.epoll_event() + _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_DEL, fd: fd, event: &ev) + #else + try register_kqueue(selectable: selectable, interested: .none, oldInterested: reg.interested) + #endif } - -#if os(Linux) - var ev = Epoll.epoll_event() - _ = try Epoll.epoll_ctl(epfd: self.fd, op: Epoll.EPOLL_CTL_DEL, fd: selectable.descriptor, event: &ev) -#else - try register_kqueue(selectable: selectable, interested: .none, oldInterested: reg.interested) -#endif } /// Apply the given `SelectorStrategy` and execute `fn` once it's complete (which may produce `SelectorEvent`s to handle). diff --git a/Sources/NIO/ServerSocket.swift b/Sources/NIO/ServerSocket.swift index 9c81caf5d..9f6e46140 100644 --- a/Sources/NIO/ServerSocket.swift +++ b/Sources/NIO/ServerSocket.swift @@ -37,7 +37,9 @@ final class ServerSocket: BaseSocket { /// - backlog: The backlog to use. /// - throws: An `IOError` if creation of the socket failed. func listen(backlog: Int32 = 128) throws { - _ = try Posix.listen(descriptor: descriptor, backlog: backlog) + try withUnsafeFileDescriptor { fd in + _ = try Posix.listen(descriptor: fd, backlog: backlog) + } } /// Accept a new connection @@ -45,18 +47,20 @@ final class ServerSocket: BaseSocket { /// - returns: A `Socket` once a new connection was established or `nil` if this `ServerSocket` is in non-blocking mode and there is no new connection that can be accepted when this method is called. /// - throws: An `IOError` if the operation failed. func accept() throws -> Socket? { - var acceptAddr = sockaddr_in() - var addrSize = socklen_t(MemoryLayout.size) - - let result = try withUnsafeMutablePointer(to: &acceptAddr) { ptr in - try ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { ptr in - try Posix.accept(descriptor: self.descriptor, addr: ptr, len: &addrSize) + return try withUnsafeFileDescriptor { fd in + var acceptAddr = sockaddr_in() + var addrSize = socklen_t(MemoryLayout.size) + + let result = try withUnsafeMutablePointer(to: &acceptAddr) { ptr in + try ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { ptr in + try Posix.accept(descriptor: fd, addr: ptr, len: &addrSize) + } } + + guard let fd = result else { + return nil + } + return Socket(descriptor: fd) } - - guard let fd = result else { - return nil - } - return Socket(descriptor: fd) } } diff --git a/Sources/NIO/Socket.swift b/Sources/NIO/Socket.swift index 3928db6cf..a1e683cf4 100644 --- a/Sources/NIO/Socket.swift +++ b/Sources/NIO/Socket.swift @@ -67,13 +67,12 @@ final class Socket : BaseSocket { /// Private helper function to handle connection attempts. private func connectSocket(addr: T) throws -> Bool { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't connect socket as it's not open anymore.") - } - var addr = addr - return try withUnsafePointer(to: &addr) { ptr in - try ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { ptr in - try Posix.connect(descriptor: self.descriptor, addr: ptr, size: socklen_t(MemoryLayout.size)) + return try withUnsafeFileDescriptor { fd in + var addr = addr + return try withUnsafePointer(to: &addr) { ptr in + try ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { ptr in + try Posix.connect(descriptor: fd, addr: ptr, size: socklen_t(MemoryLayout.size)) + } } } } @@ -96,10 +95,9 @@ final class Socket : BaseSocket { /// - returns: The `IOResult` which indicates how much data could be written and if the operation returned before all could be written (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. func write(pointer: UnsafePointer, size: Int) throws -> IOResult { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't write to socket as it's not open anymore.") + return try withUnsafeFileDescriptor { fd in + try Posix.write(descriptor: fd, pointer: pointer, size: size) } - return try Posix.write(descriptor: self.descriptor, pointer: pointer, size: size) } /// Write data to the remote peer (gathering writes). @@ -109,11 +107,9 @@ final class Socket : BaseSocket { /// - returns: The `IOResult` which indicates how much data could be written and if the operation returned before all could be written (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. func writev(iovecs: UnsafeBufferPointer) throws -> IOResult { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't writev to socket as it's not open anymore.") + return try withUnsafeFileDescriptor { fd in + try Posix.writev(descriptor: fd, iovecs: iovecs) } - - return try Posix.writev(descriptor: self.descriptor, iovecs: iovecs) } /// Send data to a destination. @@ -125,11 +121,9 @@ final class Socket : BaseSocket { /// - returns: The `IOResult` which indicates how much data could be written and if the operation returned before all could be written (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. func sendto(pointer: UnsafePointer, size: Int, destinationPtr: UnsafePointer, destinationSize: socklen_t) throws -> IOResult { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't sendto to socket as it's not open anymore.") + return try withUnsafeFileDescriptor { fd in + try Posix.sendto(descriptor: fd, pointer: UnsafeMutablePointer(mutating: pointer), size: size, destinationPtr: destinationPtr, destinationSize: destinationSize) } - - return try Posix.sendto(descriptor: self.descriptor, pointer: UnsafeMutablePointer(mutating: pointer), size: size, destinationPtr: destinationPtr, destinationSize: destinationSize) } /// Read data from the socket. @@ -140,11 +134,9 @@ final class Socket : BaseSocket { /// - returns: The `IOResult` which indicates how much data could be read and if the operation returned before all could be read (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. func read(pointer: UnsafeMutablePointer, size: Int) throws -> IOResult { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't read from socket as it's not open anymore.") + return try withUnsafeFileDescriptor { fd in + try Posix.read(descriptor: fd, pointer: pointer, size: size) } - - return try Posix.read(descriptor: self.descriptor, pointer: pointer, size: size) } /// Receive data from the socket. @@ -157,12 +149,10 @@ final class Socket : BaseSocket { /// - returns: The `IOResult` which indicates how much data could be received and if the operation returned before all could be received (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. func recvfrom(pointer: UnsafeMutablePointer, size: Int, storage: inout sockaddr_storage, storageLen: inout socklen_t) throws -> IOResult<(Int)> { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't recvfrom socket as it's not open anymore") - } - - return try storage.withMutableSockAddr { (storagePtr, _) in - try Posix.recvfrom(descriptor: self.descriptor, pointer: pointer, len: size, addr: storagePtr, addrlen: &storageLen) + return try withUnsafeFileDescriptor { fd in + try storage.withMutableSockAddr { (storagePtr, _) in + try Posix.recvfrom(descriptor: fd, pointer: pointer, len: size, addr: storagePtr, addrlen: &storageLen) + } } } @@ -175,11 +165,9 @@ final class Socket : BaseSocket { /// - returns: The `IOResult` which indicates how much data could be send and if the operation returned before all could be send (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. func sendFile(fd: Int32, offset: Int, count: Int) throws -> IOResult { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't write to socket as it's not open anymore.") + return try withUnsafeFileDescriptor { desc in + try Posix.sendfile(descriptor: desc, fd: fd, offset: off_t(offset), count: count) } - - return try Posix.sendfile(descriptor: self.descriptor, fd: fd, offset: off_t(offset), count: count) } /// Receive `MMsgHdr`s. @@ -189,11 +177,9 @@ final class Socket : BaseSocket { /// - returns: The `IOResult` which indicates how many messages could be received and if the operation returned before all messages could be received (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. func recvmmsg(msgs: UnsafeMutableBufferPointer) throws -> IOResult { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't read from socket as it's not open anymore.") + return try withUnsafeFileDescriptor { fd in + try Posix.recvmmsg(sockfd: fd, msgvec: msgs.baseAddress!, vlen: CUnsignedInt(msgs.count), flags: 0, timeout: nil) } - - return try Posix.recvmmsg(sockfd: self.descriptor, msgvec: msgs.baseAddress!, vlen: CUnsignedInt(msgs.count), flags: 0, timeout: nil) } /// Send `MMsgHdr`s. @@ -203,11 +189,9 @@ final class Socket : BaseSocket { /// - returns: The `IOResult` which indicates how many messages could be send and if the operation returned before all messages could be send (because the socket is in non-blocking mode). /// - throws: An `IOError` if the operation failed. func sendmmsg(msgs: UnsafeMutableBufferPointer) throws -> IOResult { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't write to socket as it's not open anymore.") + return try withUnsafeFileDescriptor { fd in + try Posix.sendmmsg(sockfd: fd, msgvec: msgs.baseAddress!, vlen: CUnsignedInt(msgs.count), flags: 0) } - - return try Posix.sendmmsg(sockfd: self.descriptor, msgvec: msgs.baseAddress!, vlen: CUnsignedInt(msgs.count), flags: 0) } /// Shutdown the socket. @@ -216,9 +200,8 @@ final class Socket : BaseSocket { /// - how: the mode of `Shutdown`. /// - throws: An `IOError` if the operation failed. func shutdown(how: Shutdown) throws { - guard self.open else { - throw IOError(errnoCode: EBADF, reason: "can't shutdown socket as it's not open anymore.") + return try withUnsafeFileDescriptor { fd in + try Posix.shutdown(descriptor: fd, how: how) } - try Posix.shutdown(descriptor: self.descriptor, how: how) } } diff --git a/Sources/NIO/SocketChannel.swift b/Sources/NIO/SocketChannel.swift index cf461fe44..dc2a30f8a 100644 --- a/Sources/NIO/SocketChannel.swift +++ b/Sources/NIO/SocketChannel.swift @@ -1284,18 +1284,18 @@ final class DatagramChannel: BaseSocketChannel { extension SocketChannel: CustomStringConvertible { var description: String { - return "SocketChannel { descriptor = \(self.selectable.descriptor), localAddress = \(self.localAddress.debugDescription), remoteAddress = \(self.remoteAddress.debugDescription) }" + return "SocketChannel { selectable = \(self.selectable), localAddress = \(self.localAddress.debugDescription), remoteAddress = \(self.remoteAddress.debugDescription) }" } } extension ServerSocketChannel: CustomStringConvertible { var description: String { - return "ServerSocketChannel { descriptor = \(self.selectable.descriptor), localAddress = \(self.localAddress.debugDescription), remoteAddress = \(self.remoteAddress.debugDescription) }" + return "ServerSocketChannel { selectable = \(self.selectable), localAddress = \(self.localAddress.debugDescription), remoteAddress = \(self.remoteAddress.debugDescription) }" } } extension DatagramChannel: CustomStringConvertible { var description: String { - return "DatagramChannel { descriptor = \(self.selectable.descriptor), localAddress = \(self.localAddress.debugDescription), remoteAddress = \(self.remoteAddress.debugDescription) }" + return "DatagramChannel { selectable = \(self.selectable), localAddress = \(self.localAddress.debugDescription), remoteAddress = \(self.remoteAddress.debugDescription) }" } }