IPv6 support

This commit is contained in:
Johannes Weiß committed 2017-07-25 16:55:27 +01:00
1 parent 78ba7a819e
commit 55bed8359b
8 files changed
+125 -47

No files matched your search

+53 -18
View File
@@ -32,6 +32,27 @@ protocol Registration {
var interested: IOEvent { get set }
}
protocol SockAddrProtocol {
mutating func withSockAddr<R>(_ fn: (UnsafePointer<sockaddr>, Int) throws -> R) rethrows -> R
}
extension sockaddr_in: SockAddrProtocol {
mutating func withSockAddr<R>(_ fn: (UnsafePointer<sockaddr>, 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<R>(_ fn: (UnsafePointer<sockaddr>, 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<T>(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<sockaddr>, 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 {
+16 -12
View File
@@ -76,7 +76,9 @@ public final class ServerBootstrap {
let promise: Promise<Channel> = 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<Channel> {
public func bind(protocolFamily: Int32, to host: String, on port: Int32) -> Future<Channel> {
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<Channel> {
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<Channel> {
@@ -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<Channel> {
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<Void>) -> Future<Channel> {
private func execute(evGroup: EventLoopGroup,
protocolFamily: Int32,
fn: @escaping (Channel) -> Future<Void>) -> Future<Channel> {
let eventLoop = evGroup.next()
let h = handler
let opts = options
let promise: Promise<Channel> = eventLoop.newPromise()
do {
let channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop)
let channel = try SocketChannel(eventLoop: eventLoop as! SelectableEventLoop, protocolFamily: protocolFamily)
func finishClientSetup() {
do {
+4 -4
View File
@@ -397,8 +397,8 @@ extension ByteBuffer {
*/
final class SocketChannel : BaseSocketChannel<Socket> {
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<ServerSocket> {
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 {
+5 -5
View File
@@ -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)
}
+2 -2
View File
@@ -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)
}
+9
View File
@@ -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)
}
+18 -3
View File
@@ -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()
+18 -3
View File
@@ -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()