diff --git a/Sources/NIO/BaseSocket.swift b/Sources/NIO/BaseSocket.swift index 5463b6226..0e0c8800e 100644 --- a/Sources/NIO/BaseSocket.swift +++ b/Sources/NIO/BaseSocket.swift @@ -32,6 +32,27 @@ protocol Registration { var interested: IOEvent { get set } } +protocol SockAddrProtocol { + mutating func withSockAddr(_ fn: (UnsafePointer, Int) throws -> R) rethrows -> R +} +extension sockaddr_in: SockAddrProtocol { + mutating func withSockAddr(_ fn: (UnsafePointer, Int) throws -> R) rethrows -> R { + var me = self + return try withUnsafeBytes(of: &me) { p in + try fn(p.baseAddress!.assumingMemoryBound(to: sockaddr.self), p.count) + } + } +} + +extension sockaddr_in6: SockAddrProtocol { + mutating func withSockAddr(_ fn: (UnsafePointer, Int) throws -> R) rethrows -> R { + var me = self + return try withUnsafeBytes(of: &me) { p in + try fn(p.baseAddress!.assumingMemoryBound(to: sockaddr.self), p.count) + } + } +} + class BaseSocket : Selectable { public let descriptor: Int32 public private(set) var open: Bool @@ -48,10 +69,29 @@ class BaseSocket : Selectable { } } - static func newSocket() throws -> Int32 { - return try wrapSyscall({ $0 >= 0 }, function: "socket") { () -> Int32 in - sysSocket(AF_INET, Int32(sysSOCK_STREAM), 0) + static func newSocket(protocolFamily: Int32) throws -> Int32 { + let sock = try wrapSyscall({ $0 >= 0 }, function: "socket") { () -> Int32 in + sysSocket(protocolFamily, Int32(sysSOCK_STREAM), 0) } + if protocolFamily == AF_INET6 { + var zero: Int32 = 0 + do { + _ = try wrapSyscall({ $0 == 0 }, function: "setsockopt") { () -> Int32 in + setsockopt(sock, Int32(IPPROTO_IPV6), IPV6_V6ONLY, &zero, socklen_t(MemoryLayout.size(ofValue: zero))) + } + } catch let e as IOError { + if e.errno != EAFNOSUPPORT { + _ = try wrapSyscall({ $0 == 0 }, function: "close") { () -> Int32 in + sysClose(sock) + } + throw e + } + /* we couldn't enable dual IP4/6 support, that's okay too. */ + } catch let e { + fatalError("Unexpected error type \(e)") + } + } + return sock } // TODO: This needs a way to encourage proper open/close behavior. @@ -107,27 +147,22 @@ class BaseSocket : Selectable { } final func bind(to address: SocketAddress) throws { - switch address { - case .v4(address: let addr, _): - try bindSocket(addr: addr) - case .v6(address: let addr, _): - try bindSocket(addr: addr) - } - } - - private func bindSocket(addr: T) throws { guard self.open else { throw IOError(errno: EBADF, reason: "can't bind socket as it's not open anymore.") } - var addr = addr - try withUnsafePointer(to: &addr) { p in - try p.withMemoryRebound(to: sockaddr.self, capacity: 1) { ptr in - _ = try wrapSyscall({ $0 != -1 }, function: "bind") { - sysBind(self.descriptor, ptr, socklen_t(MemoryLayout.size(ofValue: addr))) - } + func doBind(ptr: UnsafePointer, bytes: Int) throws { + _ = try wrapSyscall({ $0 == 0 }, function: "bind") { + sysBind(self.descriptor, ptr, socklen_t(bytes)) } } + + switch address { + case .v4(address: var addr, _): + try addr.withSockAddr(doBind) + case .v6(address: var addr, _): + try addr.withSockAddr(doBind) + } } final func close() throws { diff --git a/Sources/NIO/Bootstrap.swift b/Sources/NIO/Bootstrap.swift index 1ffc21e7f..6397c7e33 100644 --- a/Sources/NIO/Bootstrap.swift +++ b/Sources/NIO/Bootstrap.swift @@ -76,7 +76,9 @@ public final class ServerBootstrap { let promise: Promise = eventLoop.newPromise() do { - let serverChannel = try ServerSocketChannel(eventLoop: eventLoop as! SelectableEventLoop, group: chEvGroup) + let serverChannel = try ServerSocketChannel(eventLoop: eventLoop as! SelectableEventLoop, + group: chEvGroup, + protocolFamily: address.protocolFamily) func finishServerSetup() { do { @@ -198,23 +200,23 @@ public final class ClientBootstrap { return self } - public func bind(to host: String, on port: Int32) -> Future { + public func bind(protocolFamily: Int32, to host: String, on port: Int32) -> Future { let evGroup = group do { let address = try SocketAddress.newAddressResolving(host: host, port: port) - return execute(evGroup: evGroup, fn: { channel in + return execute(evGroup: evGroup, protocolFamily: protocolFamily) { channel in return channel.bind(to: address) - }) + } } catch let err { return evGroup.next().newFailedFuture(error: err) } } public func bind(to address: SocketAddress) -> Future { - return execute(evGroup: group, fn: { channel in + return execute(evGroup: group, protocolFamily: address.protocolFamily) { channel in return channel.bind(to: address) - }) + } } public func connect(to host: String, on port: Int32) -> Future { @@ -222,28 +224,30 @@ public final class ClientBootstrap { do { let address = try SocketAddress.newAddressResolving(host: host, port: port) - return execute(evGroup: group, fn: { channel in + return execute(evGroup: group, protocolFamily: address.protocolFamily) { channel in return channel.connect(to: address) - }) + } } catch let err { return evGroup.next().newFailedFuture(error: err) } } public func connect(to address: SocketAddress) -> Future { - return execute(evGroup: group, fn: { channel in + return execute(evGroup: group, protocolFamily: address.protocolFamily) { channel in return channel.connect(to: address) - }) + } } - private func execute(evGroup: EventLoopGroup, fn: @escaping (Channel) -> Future) -> Future { + private func execute(evGroup: EventLoopGroup, + protocolFamily: Int32, + fn: @escaping (Channel) -> Future) -> Future { let eventLoop = evGroup.next() let h = handler let opts = options let promise: Promise = eventLoop.newPromise() do { - let channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop) + let channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, protocolFamily: protocolFamily) func finishClientSetup() { do { diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index e19696265..0c42db705 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -397,8 +397,8 @@ extension ByteBuffer { */ final class SocketChannel : BaseSocketChannel { - init(eventLoop: SelectableEventLoop) throws { - let socket = try Socket() + init(eventLoop: SelectableEventLoop, protocolFamily: Int32) throws { + let socket = try Socket(protocolFamily: protocolFamily) do { try socket.setNonBlocking() } catch let err { @@ -498,8 +498,8 @@ final class ServerSocketChannel : BaseSocketChannel { private var backlog: Int32 = 128 private let group: EventLoopGroup - init(eventLoop: SelectableEventLoop, group: EventLoopGroup) throws { - let serverSocket = try ServerSocket() + init(eventLoop: SelectableEventLoop, group: EventLoopGroup, protocolFamily: Int32) throws { + let serverSocket = try ServerSocket(protocolFamily: protocolFamily) do { try serverSocket.setNonBlocking() } catch let err { diff --git a/Sources/NIO/ServerSocket.swift b/Sources/NIO/ServerSocket.swift index a53a4efef..5369d471a 100644 --- a/Sources/NIO/ServerSocket.swift +++ b/Sources/NIO/ServerSocket.swift @@ -28,15 +28,15 @@ import Foundation // TODO: Handle AF_INET6 as well final class ServerSocket: BaseSocket { - public class func bootstrap(host: String, port: Int32) throws -> ServerSocket { - let socket = try ServerSocket() - try socket.bind(to: try SocketAddress.newAddressResolving(host: host, port: port)) + public class func bootstrap(protocolFamily: Int32, host: String, port: Int32) throws -> ServerSocket { + let socket = try ServerSocket(protocolFamily: protocolFamily) + try socket.bind(to: SocketAddress.newAddressResolving(host: host, port: port)) try socket.listen() return socket } - init() throws { - let sock = try BaseSocket.newSocket() + init(protocolFamily: Int32) throws { + let sock = try BaseSocket.newSocket(protocolFamily: protocolFamily) super.init(descriptor: sock) } diff --git a/Sources/NIO/Socket.swift b/Sources/NIO/Socket.swift index f5b17dca5..bb90fa509 100644 --- a/Sources/NIO/Socket.swift +++ b/Sources/NIO/Socket.swift @@ -43,8 +43,8 @@ final class Socket : BaseSocket { #endif } - init() throws { - let sock = try BaseSocket.newSocket() + init(protocolFamily: Int32) throws { + let sock = try BaseSocket.newSocket(protocolFamily: protocolFamily) super.init(descriptor: sock) } diff --git a/Sources/NIO/SocketAddresses.swift b/Sources/NIO/SocketAddresses.swift index fd5431b4e..2db68b04c 100644 --- a/Sources/NIO/SocketAddresses.swift +++ b/Sources/NIO/SocketAddresses.swift @@ -65,6 +65,15 @@ public enum SocketAddress: CustomStringConvertible { return "[\(type)]\(host):\(port)" } + public var protocolFamily: Int32 { + switch self { + case .v4(address: _, host: _): + return PF_INET + case .v6(address: _, host: _): + return PF_INET6 + } + } + public init(IPv4Address addr: sockaddr_in, host: String) { self = .v4(address: addr, host: host) } diff --git a/Sources/NIOEchoServer/main.swift b/Sources/NIOEchoServer/main.swift index bf83b8842..4e4732510 100644 --- a/Sources/NIOEchoServer/main.swift +++ b/Sources/NIOEchoServer/main.swift @@ -66,11 +66,26 @@ defer { // First argument is the program path let arguments = CommandLine.arguments -let port = arguments.count == 2 ? Int32(arguments[1])! : 9999 +let arg1 = arguments.dropFirst().first +let arg2 = arguments.dropFirst().dropFirst().first -let channel = try bootstrap.bind(to: "0.0.0.0", on: port).wait() +var host: String = "::1" +var port: Int32 = 9999 +switch (arg1, arg1.flatMap { Int32($0) }, arg2.flatMap { Int32($0) }) { +case (.some(let h), _ , .some(let p)): + /* we got two arguments, let's interpret that as host and port */ + host = h + port = p +case (_, .some(let p), _): + /* only one argument --> port */ + port = p +default: + () +} -print("Server started and listening on 0.0.0.0:\(port)") +let channel = try bootstrap.bind(to: host, on: port).wait() + +print("Server started and listening on \(host):\(port)") // This will never unblock as we not close the ServerChannel try channel.closeFuture.wait() diff --git a/Sources/NIOHTTP1Server/main.swift b/Sources/NIOHTTP1Server/main.swift index 4efe86534..c69ff0946 100644 --- a/Sources/NIOHTTP1Server/main.swift +++ b/Sources/NIOHTTP1Server/main.swift @@ -87,11 +87,26 @@ defer { // First argument is the program path let arguments = CommandLine.arguments -let port = arguments.count == 2 ? Int32(arguments[1])! : 8888 +let arg1 = arguments.dropFirst().first +let arg2 = arguments.dropFirst().dropFirst().first -let channel = try bootstrap.bind(to: "0.0.0.0", on: port).wait() +var host: String = "::1" +var port: Int32 = 8888 +switch (arg1, arg1.flatMap { Int32($0) }, arg2.flatMap { Int32($0) }) { +case (.some(let h), _ , .some(let p)): + /* we got two arguments, let's interpret that as host and port */ + host = h + port = p +case (_, .some(let p), _): + /* only one argument --> port */ + port = p +default: + () +} -print("Server started and listening on 0.0.0.0:\(port)") +let channel = try bootstrap.bind(to: host, on: port).wait() + +print("Server started and listening on \(host):\(port)") // This will never unblock as we not close the ServerChannel try channel.closeFuture.wait()