Add Selectable.withUnsafeFileDescriptor and use it through the code. (#28)

Motivation:

We missed to check if the file descriptor is still open in ServerSocket before we act on it. We can remove a lot of complexity by just providing a withUnsafeFileDescriptor which will do this for us and use it through out the code-base.

Modifications:

Introduce withUnsafeFileDescriptor and use it to ensure we always only act on open Selectables.

Result:

More correct code.
This commit is contained in:
Norman Maurer authored and Johannes Weiß committed 2018-02-26 11:30:37 +00:00
1 parent 9652984b60
commit 580924909d
6 files changed
+164 -161

No files matched your search

+58 -52
View File
@@ -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<T>(_ 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<T>(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<T>(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<T>.size)
var val = UnsafeMutablePointer<T>.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<T>.size)
var val = UnsafeMutablePointer<T>.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<sockaddr>, 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<sockaddr>, 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) } "
}
}
+8 -3
View File
@@ -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<T>(_ 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
}
+53 -48
View File
@@ -179,18 +179,20 @@ final class Selector<R: Registration> {
private func register_kqueue<S: Selectable>(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<R: Registration> {
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<R: Registration> {
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<R: Registration> {
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).
+16 -12
View File
@@ -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<sockaddr_in>.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<sockaddr_in>.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)
}
}
+26 -43
View File
@@ -67,13 +67,12 @@ final class Socket : BaseSocket {
/// Private helper function to handle connection attempts.
private func connectSocket<T>(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<T>.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<T>.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<UInt8>, size: Int) throws -> IOResult<Int> {
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<IOVector>) throws -> IOResult<Int> {
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<UInt8>, size: Int, destinationPtr: UnsafePointer<sockaddr>, destinationSize: socklen_t) throws -> IOResult<Int> {
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<UInt8>, size: Int) throws -> IOResult<Int> {
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<UInt8>, 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<Int> {
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<MMsgHdr>) throws -> IOResult<Int> {
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<MMsgHdr>) throws -> IOResult<Int> {
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)
}
}
+3 -3
View File
@@ -1284,18 +1284,18 @@ final class DatagramChannel: BaseSocketChannel<Socket> {
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) }"
}
}