diff --git a/Sources/NIO/BaseSocket.swift b/Sources/NIO/BaseSocket.swift index e8829dcd8..07b91c2e6 100644 --- a/Sources/NIO/BaseSocket.swift +++ b/Sources/NIO/BaseSocket.swift @@ -12,7 +12,9 @@ // //===----------------------------------------------------------------------===// +/// A Registration on a `Selector`, which is interested in an `IOEvent`. protocol Registration { + /// The `IOEvent` in which the `Registration` is interested. var interested: IOEvent { get set } } @@ -21,6 +23,7 @@ protocol SockAddrProtocol { mutating func withMutableSockAddr(_ fn: (UnsafeMutablePointer, Int) throws -> R) rethrows -> R } +/// Returns a description for the given address. private func descriptionForAddress(family: CInt, bytes: UnsafeRawPointer, length byteCount: Int) -> String { var addressBytes: [Int8] = Array(repeating: 0, count: byteCount) return addressBytes.withUnsafeMutableBufferPointer { (addressBytesPtr: inout UnsafeMutableBufferPointer) -> String in @@ -49,6 +52,7 @@ extension sockaddr_in: SockAddrProtocol { } } + /// Returns a description of the `sockaddr_in`. mutating func addressDescription() -> String { return withUnsafePointer(to: &self.sin_addr) { addrPtr in descriptionForAddress(family: AF_INET, bytes: addrPtr, length: Int(INET_ADDRSTRLEN)) @@ -71,6 +75,7 @@ extension sockaddr_in6: SockAddrProtocol { } } + /// Returns a description of the `sockaddr_in6`. mutating func addressDescription() -> String { return withUnsafePointer(to: &self.sin6_addr) { addrPtr in descriptionForAddress(family: AF_INET6, bytes: addrPtr, length: Int(INET6_ADDRSTRLEN)) @@ -118,6 +123,9 @@ extension sockaddr_storage: SockAddrProtocol { // avoid getting the Swift compiler to copy the sockaddr_storage for any reason: // only our rebinding copy here is allowed. extension sockaddr_storage { + /// Converts the `socketaddr_storage` to a `sockaddr_in`. + /// + /// This will crash if `ss_family` != AF_INET! mutating func convert() -> sockaddr_in { precondition(self.ss_family == AF_INET) return withUnsafePointer(to: &self) { @@ -127,6 +135,9 @@ extension sockaddr_storage { } } + /// Converts the `socketaddr_storage` to a `sockaddr_in6`. + /// + /// This will crash if `ss_family` != AF_INET6! mutating func convert() -> sockaddr_in6 { precondition(self.ss_family == AF_INET6) return withUnsafePointer(to: &self) { @@ -136,6 +147,9 @@ extension sockaddr_storage { } } + /// Converts the `socketaddr_storage` to a `sockaddr_un`. + /// + /// This will crash if `ss_family` != AF_UNIX! mutating func convert() -> sockaddr_un { precondition(self.ss_family == AF_UNIX) return withUnsafePointer(to: &self) { @@ -145,6 +159,7 @@ extension sockaddr_storage { } } + /// Converts the `socketaddr_storage` to a `SocketAddress`. mutating func convert() -> SocketAddress { switch self.ss_family { case Posix.AF_INET: @@ -161,18 +176,31 @@ extension sockaddr_storage { } } +/// Base class for sockets. +/// +/// 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 public private(set) var open: Bool + /// Returns the local bound `SocketAddress` of the socket. + /// + /// - returns: The local bound address. + /// - throws: An `IOError` if the retrieval of the address failed. final func localAddress() throws -> SocketAddress { return try get_addr { try Posix.getsockname(socket: $0, address: $1, addressLength: $2) } } + /// Returns the connected `SocketAddress` of the socket. + /// + /// - returns: The connected address. + /// - throws: An `IOError` if the retrieval of the address failed. final func remoteAddress() throws -> SocketAddress { return try get_addr { try Posix.getpeername(socket: $0, address: $1, addressLength: $2) } } + /// Internal helper function for retrieval of a `SocketAddress`. private func get_addr(_ fn: (Int32, UnsafeMutablePointer, UnsafeMutablePointer) throws -> Void) throws -> SocketAddress { var addr = sockaddr_storage() @@ -183,6 +211,13 @@ class BaseSocket: Selectable { return addr.convert() } + /// Create a new socket and return the file descriptor of it. + /// + /// - parameters: + /// - protocolFamily: The protocol family to use (usually `AF_INET6` or `AF_INET`). + /// - type: The type of the socket to create. + /// - returns: the file descriptor of the socket that was created. + /// - throws: An `IOError` if creation of the socket failed. static func newSocket(protocolFamily: Int32, type: CInt) throws -> Int32 { let sock = try Posix.socket(domain: protocolFamily, type: type, @@ -206,7 +241,14 @@ class BaseSocket: Selectable { } return sock } - + + /// Create a new instance. + /// + /// The ownership of the passed in descriptor is transferred to this class. A user must call `close` to close the underlying + /// file descriptor once its not needed / used anymore. + /// + /// - parameters: + /// - descriptor: The file descriptor to wrap. init(descriptor : Int32) { self.descriptor = descriptor self.open = true @@ -216,6 +258,11 @@ class BaseSocket: Selectable { assert(!self.open, "leak of open BaseSocket") } + /// Set the socket as non-blocking. + /// + /// All I/O operations will not block and so may return before the actual action could be completed. + /// + /// 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.") @@ -224,6 +271,15 @@ class BaseSocket: Selectable { try Posix.fcntl(descriptor: descriptor, command: F_SETFL, value: O_NONBLOCK) } + /// Set the given socket option. + /// + /// This basically just delegates to `setsockopt` syscall. + /// + /// - parameters: + /// - level: The protocol level (see `man setsockopt`). + /// - name: The name of the option to set. + /// - 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.") @@ -239,6 +295,14 @@ class BaseSocket: Selectable { optionLen: socklen_t(MemoryLayout.size(ofValue: val))) } + /// Get the given socket option value. + /// + /// This basically just delegates to `getsockopt` syscall. + /// + /// - parameters: + /// - level: The protocol level (see `man getsockopt`). + /// - 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.") @@ -255,6 +319,11 @@ class BaseSocket: Selectable { return val.pointee } + /// Bind the socket to the given `SocketAddress`. + /// + /// - parameters: + /// - 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.") @@ -277,6 +346,11 @@ class BaseSocket: Selectable { } } + /// Close the socket. + /// + /// After the socket was closed all other methods will throw an `IOError` when called. + /// + /// - 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.") diff --git a/Sources/NIO/ServerSocket.swift b/Sources/NIO/ServerSocket.swift index 9f48444e7..9c81caf5d 100644 --- a/Sources/NIO/ServerSocket.swift +++ b/Sources/NIO/ServerSocket.swift @@ -12,6 +12,7 @@ // //===----------------------------------------------------------------------===// +/// A server socket that can accept new connections. final class ServerSocket: BaseSocket { public class func bootstrap(protocolFamily: Int32, host: String, port: Int) throws -> ServerSocket { let socket = try ServerSocket(protocolFamily: protocolFamily) @@ -20,15 +21,29 @@ final class ServerSocket: BaseSocket { return socket } + /// Create a new instance. + /// + /// - parameters: + /// - protocolFamily: The protocol family to use (usually `AF_INET6` or `AF_INET`). + /// - throws: An `IOError` if creation of the socket failed. init(protocolFamily: Int32) throws { let sock = try BaseSocket.newSocket(protocolFamily: protocolFamily, type: Posix.SOCK_STREAM) super.init(descriptor: sock) } + /// Start to listen for new connections. + /// + /// - parameters: + /// - 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) } + /// Accept a new connection + /// + /// - 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) diff --git a/Sources/NIO/Socket.swift b/Sources/NIO/Socket.swift index 9ba008229..3928db6cf 100644 --- a/Sources/NIO/Socket.swift +++ b/Sources/NIO/Socket.swift @@ -12,24 +12,48 @@ // //===----------------------------------------------------------------------===// +/// The container used for writing multiple buffers via `writev`. public typealias IOVector = iovec // TODO: scattering support final class Socket : BaseSocket { + + /// The maximum number of bytes to write per `writev` call. static var writevLimitBytes: Int { return Int(Int32.max) } + + /// The maximum number of `IOVector`s to write per `writev` call. static let writevLimitIOVectors: Int = Posix.UIO_MAXIOV + /// Create a new instance. + /// + /// - parameters: + /// - protocolFamily: The protocol family to use (usually `AF_INET6` or `AF_INET`). + /// - type: The type of the socket to create. + /// - throws: An `IOError` if creation of the socket failed. init(protocolFamily: CInt, type: CInt) throws { let sock = try BaseSocket.newSocket(protocolFamily: protocolFamily, type: type) super.init(descriptor: sock) } + /// Create a new instance. + /// + /// The ownership of the passed in descriptor is transferred to this class. A user must call `close` to close the underlying + /// file descriptor once its not needed / used anymore. + /// + /// - parameters: + /// - descriptor: The file descriptor to wrap. override init(descriptor : Int32) { super.init(descriptor: descriptor) } + /// Connect to the `SocketAddress`. + /// + /// - parameters: + /// - address: The `SocketAddress` to which the connection should be established. + /// - returns: `true` if the connection attempt completes, `false` if `finishConnect` must be called later to complete the connection attempt. + /// - throws: An `IOError` if the operation failed. func connect(to address: SocketAddress) throws -> Bool { switch address { case .v4(let addr): @@ -41,6 +65,7 @@ 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.") @@ -53,6 +78,9 @@ final class Socket : BaseSocket { } } + /// Finish a previous non-blocking `connect` operation. + /// + /// - throws: An `IOError` if the operation failed. func finishConnect() throws { let result: Int32 = try getOption(level: SOL_SOCKET, name: SO_ERROR) if result != 0 { @@ -60,6 +88,13 @@ final class Socket : BaseSocket { } } + /// Write data to the remote peer. + /// + /// - parameters: + /// - pointer: The data to write. + /// - size: The number of bytes to write. + /// - 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.") @@ -67,6 +102,12 @@ final class Socket : BaseSocket { return try Posix.write(descriptor: self.descriptor, pointer: pointer, size: size) } + /// Write data to the remote peer (gathering writes). + /// + /// - parameters: + /// - iovecs: The `IOVector`s to write. + /// - 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.") @@ -75,6 +116,14 @@ final class Socket : BaseSocket { return try Posix.writev(descriptor: self.descriptor, iovecs: iovecs) } + /// Send data to a destination. + /// + /// - parameters: + /// - pointer: The data to send. + /// - size: The number of bytes to send. + /// - destinationPtr: The destination to which the data should be sent. + /// - 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.") @@ -83,6 +132,13 @@ final class Socket : BaseSocket { return try Posix.sendto(descriptor: self.descriptor, pointer: UnsafeMutablePointer(mutating: pointer), size: size, destinationPtr: destinationPtr, destinationSize: destinationSize) } + /// Read data from the socket. + /// + /// - parameters: + /// - pointer: The pointer to the storage into which the data should be read. + /// - size: The (max) number of bytes to read. + /// - 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.") @@ -91,6 +147,15 @@ final class Socket : BaseSocket { return try Posix.read(descriptor: self.descriptor, pointer: pointer, size: size) } + /// Receive data from the socket. + /// + /// - parameters: + /// - pointer: The pointer to the storage into which the data should be read. + /// - size: The (max) number of bytes to read. + /// - storage: The address from which the data was received + /// - storageLen: The size of the storage itself. + /// - 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") @@ -101,6 +166,14 @@ final class Socket : BaseSocket { } } + /// Send the content of a file descriptor to the remote peer (if possible a zero-copy strategy is applied). + /// + /// - parameters: + /// - fd: The file descriptor of the file to send. + /// - offset: The offset in the file. + /// - count: The number of bytes to send. + /// - 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.") @@ -109,6 +182,12 @@ final class Socket : BaseSocket { return try Posix.sendfile(descriptor: self.descriptor, fd: fd, offset: off_t(offset), count: count) } + /// Receive `MMsgHdr`s. + /// + /// - parameters: + /// - msgs: The pointer to the `MMsgHdr`s into which the received message will be stored. + /// - 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.") @@ -117,6 +196,12 @@ final class Socket : BaseSocket { return try Posix.recvmmsg(sockfd: self.descriptor, msgvec: msgs.baseAddress!, vlen: CUnsignedInt(msgs.count), flags: 0, timeout: nil) } + /// Send `MMsgHdr`s. + /// + /// - parameters: + /// - msgs: The pointer to the `MMsgHdr`s which will be send. + /// - 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.") @@ -125,6 +210,11 @@ final class Socket : BaseSocket { return try Posix.sendmmsg(sockfd: self.descriptor, msgvec: msgs.baseAddress!, vlen: CUnsignedInt(msgs.count), flags: 0) } + /// Shutdown the socket. + /// + /// - parameters: + /// - 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.")