mirror of
https://github.com/apple/swift-nio
synced 2026-11-29 05:24:21 +00:00
Feature: Datagram Packet Info (#1888)
* Break out control message parsing by IP version * Add shims for Darwin packet info * Add shims for Linux packet info * Add channel option for receiving datagram packet info * Add NIOPacketInfo to AddressedEnvelope.Metadata * Pipe up packet info channel option to receive path * Add NIOPacketInfo info and fix backwards compatability * Document packet info socket options * Cleanup packet info control message parsing * Add packet info and ECN combined tests * Find real interface index during NIOPacketInfo tests * Add PacketInfo tests to Linux tests
This commit is contained in:
1 parent
3f33ef369f
commit
ffa6a871f7
14 files changed
+284
-24
No files matched your search
+1
-1
@@ -29,7 +29,7 @@ var targets: [PackageDescription.Target] = [
|
||||
.target(name: "CNIOAtomics", dependencies: []),
|
||||
.target(name: "CNIOSHA1", dependencies: []),
|
||||
.target(name: "CNIOLinux", dependencies: []),
|
||||
.target(name: "CNIODarwin", dependencies: []),
|
||||
.target(name: "CNIODarwin", dependencies: [], cSettings: [.define("__APPLE_USE_RFC_3542")]),
|
||||
.target(name: "CNIOWindows", dependencies: []),
|
||||
.target(name: "NIOConcurrencyHelpers",
|
||||
dependencies: ["CNIOAtomics"]),
|
||||
|
||||
@@ -36,6 +36,8 @@ extern const int CNIODarwin_IPTOS_ECN_MASK;
|
||||
extern const int CNIODarwin_IPTOS_ECN_ECT0;
|
||||
extern const int CNIODarwin_IPTOS_ECN_ECT1;
|
||||
extern const int CNIODarwin_IPTOS_ECN_CE;
|
||||
extern const int CNIODarwin_IPV6_RECVPKTINFO;
|
||||
extern const int CNIODarwin_IPV6_PKTINFO;
|
||||
|
||||
int CNIODarwin_sendmmsg(int sockfd, CNIODarwin_mmsghdr *msgvec, unsigned int vlen, int flags);
|
||||
int CNIODarwin_recvmmsg(int sockfd, CNIODarwin_mmsghdr *msgvec, unsigned int vlen, int flags, struct timespec *timeout);
|
||||
|
||||
@@ -86,5 +86,7 @@ const int CNIODarwin_IPTOS_ECN_MASK = IPTOS_ECN_MASK;
|
||||
const int CNIODarwin_IPTOS_ECN_ECT0 = IPTOS_ECN_ECT0;
|
||||
const int CNIODarwin_IPTOS_ECN_ECT1 = IPTOS_ECN_ECT1;
|
||||
const int CNIODarwin_IPTOS_ECN_CE = IPTOS_ECN_CE;
|
||||
const int CNIODarwin_IPV6_RECVPKTINFO = IPV6_RECVPKTINFO;
|
||||
const int CNIODarwin_IPV6_PKTINFO = IPV6_PKTINFO;
|
||||
|
||||
#endif // __APPLE__
|
||||
@@ -48,6 +48,11 @@ typedef struct {
|
||||
unsigned int msg_len;
|
||||
} CNIOLinux_mmsghdr;
|
||||
|
||||
typedef struct {
|
||||
struct in6_addr ipi6_addr;
|
||||
unsigned int ipi6_ifindex;
|
||||
} CNIOLinux_in6_pktinfo;
|
||||
|
||||
int CNIOLinux_sendmmsg(int sockfd, CNIOLinux_mmsghdr *msgvec, unsigned int vlen, int flags);
|
||||
int CNIOLinux_recvmmsg(int sockfd, CNIOLinux_mmsghdr *msgvec, unsigned int vlen, int flags, struct timespec *timeout);
|
||||
|
||||
|
||||
@@ -30,6 +30,9 @@ void CNIOLinux_i_do_nothing_just_working_around_a_darwin_toolchain_bug(void) {}
|
||||
_Static_assert(sizeof(CNIOLinux_mmsghdr) == sizeof(struct mmsghdr),
|
||||
"sizes of CNIOLinux_mmsghdr and struct mmsghdr differ");
|
||||
|
||||
_Static_assert(sizeof(CNIOLinux_in6_pktinfo) == sizeof(struct in6_pktinfo),
|
||||
"sizes of CNIOLinux_in6_pktinfo and struct in6_pktinfo differ");
|
||||
|
||||
int CNIOLinux_sendmmsg(int sockfd, CNIOLinux_mmsghdr *msgvec, unsigned int vlen, int flags) {
|
||||
// This is technically undefined behaviour, but it's basically fine because these types are the same size, and we
|
||||
// don't think the compiler is inclined to blow anything up here.
|
||||
|
||||
@@ -38,9 +38,16 @@ public struct AddressedEnvelope<DataType> {
|
||||
public struct Metadata: Hashable {
|
||||
/// Details of any congestion state.
|
||||
public var ecnState: NIOExplicitCongestionNotificationState
|
||||
public var packetInfo: NIOPacketInfo?
|
||||
|
||||
public init(ecnState: NIOExplicitCongestionNotificationState) {
|
||||
self.ecnState = ecnState
|
||||
self.packetInfo = nil
|
||||
}
|
||||
|
||||
public init(ecnState: NIOExplicitCongestionNotificationState, packetInfo: NIOPacketInfo?) {
|
||||
self.ecnState = ecnState
|
||||
self.packetInfo = packetInfo
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,3 +69,13 @@ public enum NIOExplicitCongestionNotificationState: Hashable {
|
||||
/// Congestion Experienced.
|
||||
case congestionExperienced
|
||||
}
|
||||
|
||||
public struct NIOPacketInfo: Hashable {
|
||||
public var destinationAddress: SocketAddress
|
||||
public var interfaceIndex: Int
|
||||
|
||||
public init(destinationAddress: SocketAddress, interfaceIndex: Int) {
|
||||
self.destinationAddress = destinationAddress
|
||||
self.interfaceIndex = interfaceIndex
|
||||
}
|
||||
}
|
||||
@@ -308,6 +308,15 @@ extension NIOBSDSocket.Option {
|
||||
/// IPv4 and IPv6.
|
||||
static let ip_recv_tos: NIOBSDSocket.Option =
|
||||
NIOBSDSocket.Option(rawValue: IP_RECVTOS)
|
||||
|
||||
/// Request that we are passed destination address and the receiving interface index when
|
||||
/// receiving datagrams.
|
||||
///
|
||||
/// This option is not public as the way to request this is to use
|
||||
/// `ChannelOptions.receivePacketInfo` which works for both
|
||||
/// IPv4 and IPv6.
|
||||
static let ip_recv_pktinfo: NIOBSDSocket.Option =
|
||||
NIOBSDSocket.Option(rawValue: Posix.IP_RECVPKTINFO)
|
||||
}
|
||||
|
||||
// IPv6 Options
|
||||
@@ -345,6 +354,15 @@ extension NIOBSDSocket.Option {
|
||||
/// IPv4 and IPv6.
|
||||
static let ipv6_recv_tclass: NIOBSDSocket.Option =
|
||||
NIOBSDSocket.Option(rawValue: IPV6_RECVTCLASS)
|
||||
|
||||
/// Request that we are passed destination address and the receiving interface index when
|
||||
/// receiving datagrams.
|
||||
///
|
||||
/// This option is not public as the way to request this is to use
|
||||
/// `ChannelOptions.receivePacketInfo` which works for both
|
||||
/// IPv4 and IPv6.
|
||||
static let ipv6_recv_pktinfo: NIOBSDSocket.Option =
|
||||
NIOBSDSocket.Option(rawValue: Posix.IPV6_RECVPKTINFO)
|
||||
}
|
||||
|
||||
// TCP Options
|
||||
|
||||
@@ -255,6 +255,12 @@ extension ChannelOptions {
|
||||
|
||||
public init() {}
|
||||
}
|
||||
|
||||
/// When set to true IP level Packet Info information will be reported through `AddressedEnvelope.Metadata` for UDP packets.
|
||||
public struct ReceivePacketInfo: ChannelOption {
|
||||
public typealias Value = Bool
|
||||
public init() {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,6 +314,9 @@ public struct ChannelOptions {
|
||||
|
||||
/// - seealso: `ExplicitCongestionNotificationsOption`
|
||||
public static let explicitCongestionNotification = Types.ExplicitCongestionNotificationsOption()
|
||||
|
||||
/// - seealso: `ReceivePacketInfo`
|
||||
public static let receivePacketInfo = Types.ReceivePacketInfo()
|
||||
}
|
||||
|
||||
extension ChannelOptions {
|
||||
|
||||
@@ -148,6 +148,7 @@ struct UnsafeReceivedControlBytes {
|
||||
/// Extract information from a collection of control messages.
|
||||
struct ControlMessageParser {
|
||||
var ecnValue: NIOExplicitCongestionNotificationState = .transportNotCapable // Default
|
||||
var packetInfo: NIOPacketInfo? = nil
|
||||
|
||||
init(parsing controlMessagesReceived: UnsafeControlMessageCollection) {
|
||||
for controlMessage in controlMessagesReceived {
|
||||
@@ -171,19 +172,54 @@ struct ControlMessageParser {
|
||||
return readValue
|
||||
}
|
||||
|
||||
mutating func receiveMessage(_ controlMessage: UnsafeControlMessage) {
|
||||
if controlMessage.level == IPPROTO_IP && controlMessage.type == ControlMessageParser.ipv4TosType {
|
||||
private mutating func receiveMessage(_ controlMessage: UnsafeControlMessage) {
|
||||
if controlMessage.level == IPPROTO_IP {
|
||||
self.receiveIPv4Message(controlMessage)
|
||||
} else if controlMessage.level == IPPROTO_IPV6 {
|
||||
self.receiveIPv6Message(controlMessage)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func receiveIPv4Message(_ controlMessage: UnsafeControlMessage) {
|
||||
if controlMessage.type == ControlMessageParser.ipv4TosType {
|
||||
if let data = controlMessage.data {
|
||||
assert(data.count == 1)
|
||||
precondition(data.count >= 1)
|
||||
let readValue = CInt(data[0])
|
||||
self.ecnValue = .init(receivedValue: readValue)
|
||||
}
|
||||
} else if controlMessage.level == IPPROTO_IPV6 && controlMessage.type == IPV6_TCLASS {
|
||||
} else if controlMessage.type == Posix.IP_PKTINFO {
|
||||
if let data = controlMessage.data {
|
||||
let info = data.load(as: in_pktinfo.self)
|
||||
var addr = sockaddr_in()
|
||||
addr.sin_family = sa_family_t(NIOBSDSocket.AddressFamily.inet.rawValue)
|
||||
addr.sin_port = in_port_t(0)
|
||||
addr.sin_addr = info.ipi_addr
|
||||
self.packetInfo = NIOPacketInfo(destinationAddress: SocketAddress(addr, host: ""),
|
||||
interfaceIndex: Int(info.ipi_ifindex))
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func receiveIPv6Message(_ controlMessage: UnsafeControlMessage) {
|
||||
if controlMessage.type == IPV6_TCLASS {
|
||||
if let data = controlMessage.data {
|
||||
let readValue = ControlMessageParser._readCInt(data: data)
|
||||
self.ecnValue = .init(receivedValue: readValue)
|
||||
}
|
||||
} else if controlMessage.type == Posix.IPV6_PKTINFO {
|
||||
if let data = controlMessage.data {
|
||||
let info = data.load(as: in6_pktinfo.self)
|
||||
var addr = sockaddr_in6()
|
||||
addr.sin6_family = sa_family_t(NIOBSDSocket.AddressFamily.inet6.rawValue)
|
||||
addr.sin6_port = in_port_t(0)
|
||||
addr.sin6_flowinfo = 0
|
||||
addr.sin6_addr = info.ipi6_addr
|
||||
addr.sin6_scope_id = 0
|
||||
self.packetInfo = NIOPacketInfo(destinationAddress: SocketAddress(addr, host: ""),
|
||||
interfaceIndex: Int(info.ipi6_ifindex))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -297,6 +333,6 @@ extension AddressedEnvelope.Metadata {
|
||||
/// It's assumed the caller has checked that congestion information is required before calling.
|
||||
internal init(from controlMessagesReceived: UnsafeControlMessageCollection) {
|
||||
let controlMessageReceiver = ControlMessageParser(parsing: controlMessagesReceived)
|
||||
self.init(ecnState: controlMessageReceiver.ecnValue)
|
||||
self.init(ecnState: controlMessageReceiver.ecnValue, packetInfo: controlMessageReceiver.packetInfo)
|
||||
}
|
||||
}
|
||||
@@ -87,10 +87,10 @@ struct DatagramVectorReadManager {
|
||||
/// - parameters:
|
||||
/// - socket: The underlying socket from which to read.
|
||||
/// - buffer: The single large buffer into which reads will be written.
|
||||
/// - reportExplicitCongestionNotifications: Should explicit congestion notifications be reported up using metadata.
|
||||
/// - parseControlMessages: Should control messages be reported up using metadata.
|
||||
func readFromSocket(socket: Socket,
|
||||
buffer: inout ByteBuffer,
|
||||
reportExplicitCongestionNotifications: Bool) throws -> ReadResult {
|
||||
parseControlMessages: Bool) throws -> ReadResult {
|
||||
assert(buffer.readerIndex == 0, "Buffer was not cleared between calls to readFromSocket!")
|
||||
|
||||
let messageSize = buffer.capacity / self.messageCount
|
||||
@@ -103,7 +103,7 @@ struct DatagramVectorReadManager {
|
||||
self.ioVector[i] = IOVector(iov_base: bufferPointer.baseAddress! + (i * messageSize), iov_len: numericCast(messageSize))
|
||||
|
||||
let controlBytes: UnsafeMutableRawBufferPointer
|
||||
if reportExplicitCongestionNotifications {
|
||||
if parseControlMessages {
|
||||
// This will be used in buildMessages below but should not be used beyond return of this function.
|
||||
controlBytes = self.controlMessageStorage[i]
|
||||
} else {
|
||||
@@ -137,7 +137,7 @@ struct DatagramVectorReadManager {
|
||||
return self.buildMessages(messageCount: messagesProcessed,
|
||||
sliceSize: messageSize,
|
||||
buffer: &buffer,
|
||||
reportExplicitCongestionNotifications: reportExplicitCongestionNotifications)
|
||||
parseControlMessages: parseControlMessages)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ struct DatagramVectorReadManager {
|
||||
private func buildMessages(messageCount: Int,
|
||||
sliceSize: Int,
|
||||
buffer: inout ByteBuffer,
|
||||
reportExplicitCongestionNotifications: Bool) -> ReadResult {
|
||||
parseControlMessages: Bool) -> ReadResult {
|
||||
var sliceOffset = buffer.readerIndex
|
||||
var totalReadSize = 0
|
||||
|
||||
@@ -176,7 +176,7 @@ struct DatagramVectorReadManager {
|
||||
|
||||
// Extract congestion information if requested.
|
||||
let metadata: AddressedEnvelope<ByteBuffer>.Metadata?
|
||||
if reportExplicitCongestionNotifications {
|
||||
if parseControlMessages {
|
||||
let controlMessagesReceived =
|
||||
UnsafeControlMessageCollection(messageHeader: self.messageVector[i].msg_hdr)
|
||||
metadata = .init(from: controlMessagesReceived)
|
||||
|
||||
@@ -346,6 +346,7 @@ final class ServerSocketChannel: BaseSocketChannel<ServerSocket> {
|
||||
/// Currently, it does not support connected mode which is well worth adding.
|
||||
final class DatagramChannel: BaseSocketChannel<Socket> {
|
||||
private var reportExplicitCongestionNotifications = false
|
||||
private var receivePacketInfo = false
|
||||
|
||||
// Guard against re-entrance of flushNow() method.
|
||||
private let pendingWrites: PendingDatagramWritesManager
|
||||
@@ -435,7 +436,7 @@ final class DatagramChannel: BaseSocketChannel<Socket> {
|
||||
break
|
||||
#endif
|
||||
case _ as ChannelOptions.Types.ExplicitCongestionNotificationsOption:
|
||||
let valueAsInt: Int32 = value as! Bool ? 1 : 0
|
||||
let valueAsInt: CInt = value as! Bool ? 1 : 0
|
||||
switch self.localAddress?.protocol {
|
||||
case .some(.inet):
|
||||
self.reportExplicitCongestionNotifications = true
|
||||
@@ -451,6 +452,24 @@ final class DatagramChannel: BaseSocketChannel<Socket> {
|
||||
// Explicit congestion notification is only supported for IP
|
||||
throw ChannelError.operationUnsupported
|
||||
}
|
||||
case _ as ChannelOptions.Types.ReceivePacketInfo:
|
||||
let valueAsInt: CInt = value as! Bool ? 1 : 0
|
||||
switch self.localAddress?.protocol {
|
||||
case .some(.inet):
|
||||
self.receivePacketInfo = true
|
||||
try self.socket.setOption(level: .ip,
|
||||
name: .ip_recv_pktinfo,
|
||||
value: valueAsInt)
|
||||
case .some(.inet6):
|
||||
self.receivePacketInfo = true
|
||||
try self.socket.setOption(level: .ipv6,
|
||||
name: .ipv6_recv_pktinfo,
|
||||
value: valueAsInt)
|
||||
default:
|
||||
// Receiving packet info is only supported for IP
|
||||
throw ChannelError.operationUnsupported
|
||||
}
|
||||
break
|
||||
default:
|
||||
try super.setOption0(option, value: value)
|
||||
}
|
||||
@@ -482,6 +501,18 @@ final class DatagramChannel: BaseSocketChannel<Socket> {
|
||||
// Explicit congestion notification is only supported for IP
|
||||
throw ChannelError.operationUnsupported
|
||||
}
|
||||
case _ as ChannelOptions.Types.ReceivePacketInfo:
|
||||
switch self.localAddress?.protocol {
|
||||
case .some(.inet):
|
||||
return try (self.socket.getOption(level: .ip,
|
||||
name: .ip_recv_pktinfo) != 0) as! Option.Value
|
||||
case .some(.inet6):
|
||||
return try (self.socket.getOption(level: .ipv6,
|
||||
name: .ipv6_recv_pktinfo) != 0) as! Option.Value
|
||||
default:
|
||||
// Receiving packet info is only supported for IP
|
||||
throw ChannelError.operationUnsupported
|
||||
}
|
||||
default:
|
||||
return try super.getOption0(option)
|
||||
}
|
||||
@@ -519,7 +550,7 @@ final class DatagramChannel: BaseSocketChannel<Socket> {
|
||||
|
||||
// These control bytes must not escape the current call stack
|
||||
let controlBytesBuffer: UnsafeMutableRawBufferPointer
|
||||
if self.reportExplicitCongestionNotifications {
|
||||
if self.reportExplicitCongestionNotifications || self.receivePacketInfo {
|
||||
controlBytesBuffer = self.selectableEventLoop.controlMessageStorage[0]
|
||||
} else {
|
||||
controlBytesBuffer = UnsafeMutableRawBufferPointer(start: nil, count: 0)
|
||||
@@ -547,7 +578,7 @@ final class DatagramChannel: BaseSocketChannel<Socket> {
|
||||
readPending = false
|
||||
|
||||
let metadata: AddressedEnvelope<ByteBuffer>.Metadata?
|
||||
if self.reportExplicitCongestionNotifications,
|
||||
if self.reportExplicitCongestionNotifications || self.receivePacketInfo,
|
||||
let controlMessagesReceived = controlBytes.receivedControlMessages {
|
||||
metadata = .init(from: controlMessagesReceived)
|
||||
} else {
|
||||
@@ -591,7 +622,7 @@ final class DatagramChannel: BaseSocketChannel<Socket> {
|
||||
let result = try vectorReadManager.readFromSocket(
|
||||
socket: self.socket,
|
||||
buffer: &buffer,
|
||||
reportExplicitCongestionNotifications: self.reportExplicitCongestionNotifications)
|
||||
parseControlMessages: self.reportExplicitCongestionNotifications || self.receivePacketInfo)
|
||||
switch result {
|
||||
case .some(let results, let totalRead):
|
||||
assert(self.isOpen)
|
||||
|
||||
@@ -26,6 +26,7 @@ internal typealias MMsgHdr = CNIODarwin_mmsghdr
|
||||
@_exported import Glibc
|
||||
import CNIOLinux
|
||||
internal typealias MMsgHdr = CNIOLinux_mmsghdr
|
||||
internal typealias in6_pktinfo = CNIOLinux_in6_pktinfo
|
||||
#elseif os(Windows)
|
||||
import CNIOWindows
|
||||
internal typealias sockaddr = WinSDK.SOCKADDR
|
||||
@@ -204,6 +205,10 @@ internal enum Posix {
|
||||
static let IPTOS_ECN_ECT0: CInt = CNIODarwin_IPTOS_ECN_ECT0
|
||||
static let IPTOS_ECN_ECT1: CInt = CNIODarwin_IPTOS_ECN_ECT1
|
||||
static let IPTOS_ECN_CE: CInt = CNIODarwin_IPTOS_ECN_CE
|
||||
static let IP_RECVPKTINFO: CInt = CNIODarwin.IP_RECVPKTINFO
|
||||
static let IP_PKTINFO: CInt = CNIODarwin.IP_PKTINFO
|
||||
static let IPV6_RECVPKTINFO: CInt = CNIODarwin_IPV6_RECVPKTINFO
|
||||
static let IPV6_PKTINFO: CInt = CNIODarwin_IPV6_PKTINFO
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
|
||||
static let UIO_MAXIOV: Int = Int(Glibc.UIO_MAXIOV)
|
||||
@@ -219,6 +224,10 @@ internal enum Posix {
|
||||
static let IPTOS_ECN_ECT0: CInt = CInt(CNIOLinux.IPTOS_ECN_ECT0)
|
||||
static let IPTOS_ECN_ECT1: CInt = CInt(CNIOLinux.IPTOS_ECN_ECT1)
|
||||
static let IPTOS_ECN_CE: CInt = CInt(CNIOLinux.IPTOS_ECN_CE)
|
||||
static let IP_RECVPKTINFO: CInt = CInt(CNIOLinux.IP_PKTINFO)
|
||||
static let IP_PKTINFO: CInt = CInt(CNIOLinux.IP_PKTINFO)
|
||||
static let IPV6_RECVPKTINFO: CInt = CInt(CNIOLinux.IPV6_RECVPKTINFO)
|
||||
static let IPV6_PKTINFO: CInt = CInt(CNIOLinux.IPV6_PKTINFO)
|
||||
#else
|
||||
static var UIO_MAXIOV: Int {
|
||||
fatalError("unsupported OS")
|
||||
|
||||
@@ -58,6 +58,15 @@ extension DatagramChannelTests {
|
||||
("testEcnSendReceiveIPV4VectorReadVectorWrite", testEcnSendReceiveIPV4VectorReadVectorWrite),
|
||||
("testEcnSendReceiveIPV6VectorReadVectorWrite", testEcnSendReceiveIPV6VectorReadVectorWrite),
|
||||
("testWritabilityChangeDuringReentrantFlushNow", testWritabilityChangeDuringReentrantFlushNow),
|
||||
("testSetGetPktInfoOption", testSetGetPktInfoOption),
|
||||
("testSimpleReceivePacketInfoIPV4", testSimpleReceivePacketInfoIPV4),
|
||||
("testSimpleReceivePacketInfoIPV6", testSimpleReceivePacketInfoIPV6),
|
||||
("testReceiveEcnAndPacketInfoIPV4", testReceiveEcnAndPacketInfoIPV4),
|
||||
("testReceiveEcnAndPacketInfoIPV6", testReceiveEcnAndPacketInfoIPV6),
|
||||
("testReceiveEcnAndPacketInfoIPV4VectorRead", testReceiveEcnAndPacketInfoIPV4VectorRead),
|
||||
("testReceiveEcnAndPacketInfoIPV6VectorRead", testReceiveEcnAndPacketInfoIPV6VectorRead),
|
||||
("testReceiveEcnAndPacketInfoIPV4VectorReadVectorWrite", testReceiveEcnAndPacketInfoIPV4VectorReadVectorWrite),
|
||||
("testReceiveEcnAndPacketInfoIPV6VectorReadVectorWrite", testReceiveEcnAndPacketInfoIPV6VectorReadVectorWrite),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -666,9 +666,11 @@ final class DatagramChannelTests: XCTestCase {
|
||||
XCTAssertFalse(try channel2.getOption(ChannelOptions.explicitCongestionNotification).wait())
|
||||
} ())
|
||||
}
|
||||
|
||||
private func testEcnReceive(address: String, vectorRead: Bool, vectorSend: Bool) {
|
||||
|
||||
private func testEcnAndPacketInfoReceive(address: String, vectorRead: Bool, vectorSend: Bool, receivePacketInfo: Bool = false) {
|
||||
XCTAssertNoThrow(try {
|
||||
// Fake sending packet to self on the loopback interface if requested
|
||||
let expectedPacketInfo = receivePacketInfo ? try constructNIOPacketInfo(address: address) : nil
|
||||
let receiveBootstrap: DatagramBootstrap
|
||||
if vectorRead {
|
||||
receiveBootstrap = DatagramBootstrap(group: group)
|
||||
@@ -679,6 +681,7 @@ final class DatagramChannelTests: XCTestCase {
|
||||
|
||||
let receiveChannel = try receiveBootstrap
|
||||
.channelOption(ChannelOptions.explicitCongestionNotification, value: true)
|
||||
.channelOption(ChannelOptions.receivePacketInfo, value: receivePacketInfo)
|
||||
.channelInitializer { channel in
|
||||
channel.pipeline.addHandler(DatagramReadRecorder<ByteBuffer>(), name: "ByteReadRecorder")
|
||||
}
|
||||
@@ -703,7 +706,7 @@ final class DatagramChannelTests: XCTestCase {
|
||||
for ecnState in ecnStates {
|
||||
let writeData = AddressedEnvelope(remoteAddress: receiveChannel.localAddress!,
|
||||
data: buffer,
|
||||
metadata: .init(ecnState: ecnState))
|
||||
metadata: .init(ecnState: ecnState, packetInfo: expectedPacketInfo))
|
||||
// Sending extra data without flushing should trigger a vector send.
|
||||
if (vectorSend) {
|
||||
sendChannel.write(writeData, promise: nil)
|
||||
@@ -717,41 +720,52 @@ final class DatagramChannelTests: XCTestCase {
|
||||
for readNumber in 0..<reads.count {
|
||||
let read = reads[readNumber]
|
||||
XCTAssertEqual(read.metadata?.ecnState, ecnStates[readNumber / (vectorSend ? 2 : 1)])
|
||||
XCTAssertEqual(read.metadata?.packetInfo, expectedPacketInfo)
|
||||
}
|
||||
} ())
|
||||
}
|
||||
|
||||
private func constructNIOPacketInfo(address: String) throws -> NIOPacketInfo {
|
||||
struct InterfaceIndexNotFound: Error {}
|
||||
let destinationAddress = try SocketAddress(ipAddress: address, port: 0)
|
||||
guard let ingressIfaceIndex = try System.enumerateDevices()
|
||||
.first(where: {$0.address == destinationAddress })?.interfaceIndex else {
|
||||
throw InterfaceIndexNotFound()
|
||||
}
|
||||
return NIOPacketInfo(destinationAddress: destinationAddress, interfaceIndex: ingressIfaceIndex)
|
||||
}
|
||||
|
||||
func testEcnSendReceiveIPV4() {
|
||||
testEcnReceive(address: "127.0.0.1", vectorRead: false, vectorSend: false)
|
||||
testEcnAndPacketInfoReceive(address: "127.0.0.1", vectorRead: false, vectorSend: false)
|
||||
}
|
||||
|
||||
func testEcnSendReceiveIPV6() {
|
||||
guard System.supportsIPv6 else {
|
||||
return // need to skip IPv6 tests if we don't support it.
|
||||
}
|
||||
testEcnReceive(address: "::1", vectorRead: false, vectorSend: false)
|
||||
testEcnAndPacketInfoReceive(address: "::1", vectorRead: false, vectorSend: false)
|
||||
}
|
||||
|
||||
func testEcnSendReceiveIPV4VectorRead() {
|
||||
testEcnReceive(address: "127.0.0.1", vectorRead: true, vectorSend: false)
|
||||
testEcnAndPacketInfoReceive(address: "127.0.0.1", vectorRead: true, vectorSend: false)
|
||||
}
|
||||
|
||||
func testEcnSendReceiveIPV6VectorRead() {
|
||||
guard System.supportsIPv6 else {
|
||||
return // need to skip IPv6 tests if we don't support it.
|
||||
}
|
||||
testEcnReceive(address: "::1", vectorRead: true, vectorSend: false)
|
||||
testEcnAndPacketInfoReceive(address: "::1", vectorRead: true, vectorSend: false)
|
||||
}
|
||||
|
||||
func testEcnSendReceiveIPV4VectorReadVectorWrite() {
|
||||
testEcnReceive(address: "127.0.0.1", vectorRead: true, vectorSend: true)
|
||||
testEcnAndPacketInfoReceive(address: "127.0.0.1", vectorRead: true, vectorSend: true)
|
||||
}
|
||||
|
||||
func testEcnSendReceiveIPV6VectorReadVectorWrite() {
|
||||
guard System.supportsIPv6 else {
|
||||
return // need to skip IPv6 tests if we don't support it.
|
||||
}
|
||||
testEcnReceive(address: "::1", vectorRead: true, vectorSend: true)
|
||||
testEcnAndPacketInfoReceive(address: "::1", vectorRead: true, vectorSend: true)
|
||||
}
|
||||
|
||||
func testWritabilityChangeDuringReentrantFlushNow() throws {
|
||||
@@ -791,4 +805,109 @@ final class DatagramChannelTests: XCTestCase {
|
||||
XCTAssertNoThrow(try handler.becameUnwritable.futureResult.wait())
|
||||
XCTAssertNoThrow(try handler.becameWritable.futureResult.wait())
|
||||
}
|
||||
|
||||
func testSetGetPktInfoOption() {
|
||||
XCTAssertNoThrow(try {
|
||||
// IPv4
|
||||
try self.firstChannel.setOption(ChannelOptions.receivePacketInfo, value: true).wait()
|
||||
XCTAssertTrue(try self.firstChannel.getOption(ChannelOptions.receivePacketInfo).wait())
|
||||
|
||||
try self.secondChannel.setOption(ChannelOptions.receivePacketInfo, value: false).wait()
|
||||
XCTAssertFalse(try self.secondChannel.getOption(ChannelOptions.receivePacketInfo).wait())
|
||||
|
||||
// IPv6
|
||||
guard self.supportsIPv6 else {
|
||||
// Skip on non-IPv6 systems
|
||||
return
|
||||
}
|
||||
|
||||
let channel1 = try buildChannel(group: self.group, host: "::1")
|
||||
try channel1.setOption(ChannelOptions.receivePacketInfo, value: true).wait()
|
||||
XCTAssertTrue(try channel1.getOption(ChannelOptions.receivePacketInfo).wait())
|
||||
|
||||
let channel2 = try buildChannel(group: self.group, host: "::1")
|
||||
try channel2.setOption(ChannelOptions.receivePacketInfo, value: false).wait()
|
||||
XCTAssertFalse(try channel2.getOption(ChannelOptions.receivePacketInfo).wait())
|
||||
} ())
|
||||
}
|
||||
|
||||
private func testSimpleReceivePacketInfo(address: String) throws {
|
||||
// Fake sending packet to self on the loopback interface
|
||||
let expectedPacketInfo = try constructNIOPacketInfo(address: address)
|
||||
|
||||
let receiveChannel = try DatagramBootstrap(group: group)
|
||||
.channelOption(ChannelOptions.receivePacketInfo, value: true)
|
||||
.channelInitializer { channel in
|
||||
channel.pipeline.addHandler(DatagramReadRecorder<ByteBuffer>(), name: "ByteReadRecorder")
|
||||
}
|
||||
.bind(host: address, port: 0)
|
||||
.wait()
|
||||
defer {
|
||||
XCTAssertNoThrow(try receiveChannel.close().wait())
|
||||
}
|
||||
let sendChannel = try DatagramBootstrap(group: group)
|
||||
.bind(host: address, port: 0)
|
||||
.wait()
|
||||
defer {
|
||||
XCTAssertNoThrow(try sendChannel.close().wait())
|
||||
}
|
||||
|
||||
var buffer = sendChannel.allocator.buffer(capacity: 1)
|
||||
buffer.writeRepeatingByte(0, count: 1)
|
||||
|
||||
let writeData = AddressedEnvelope(remoteAddress: receiveChannel.localAddress!,
|
||||
data: buffer,
|
||||
metadata: .init(ecnState: .transportNotCapable,
|
||||
packetInfo: expectedPacketInfo))
|
||||
try sendChannel.writeAndFlush(writeData).wait()
|
||||
|
||||
let expectedReads = 1
|
||||
let reads = try receiveChannel.waitForDatagrams(count: 1)
|
||||
XCTAssertEqual(reads.count, expectedReads)
|
||||
XCTAssertEqual(reads[0].metadata?.packetInfo, expectedPacketInfo)
|
||||
}
|
||||
|
||||
func testSimpleReceivePacketInfoIPV4() throws {
|
||||
try testSimpleReceivePacketInfo(address: "127.0.0.1")
|
||||
}
|
||||
|
||||
func testSimpleReceivePacketInfoIPV6() throws {
|
||||
guard System.supportsIPv6 else {
|
||||
return // need to skip IPv6 tests if we don't support it.
|
||||
}
|
||||
try testSimpleReceivePacketInfo(address: "::1")
|
||||
}
|
||||
|
||||
func testReceiveEcnAndPacketInfoIPV4() {
|
||||
testEcnAndPacketInfoReceive(address: "127.0.0.1", vectorRead: false, vectorSend: false, receivePacketInfo: true)
|
||||
}
|
||||
|
||||
func testReceiveEcnAndPacketInfoIPV6() {
|
||||
guard System.supportsIPv6 else {
|
||||
return // need to skip IPv6 tests if we don't support it.
|
||||
}
|
||||
testEcnAndPacketInfoReceive(address: "::1", vectorRead: false, vectorSend: false, receivePacketInfo: true)
|
||||
}
|
||||
|
||||
func testReceiveEcnAndPacketInfoIPV4VectorRead() {
|
||||
testEcnAndPacketInfoReceive(address: "127.0.0.1", vectorRead: true, vectorSend: false, receivePacketInfo: true)
|
||||
}
|
||||
|
||||
func testReceiveEcnAndPacketInfoIPV6VectorRead() {
|
||||
guard System.supportsIPv6 else {
|
||||
return // need to skip IPv6 tests if we don't support it.
|
||||
}
|
||||
testEcnAndPacketInfoReceive(address: "::1", vectorRead: true, vectorSend: false, receivePacketInfo: true)
|
||||
}
|
||||
|
||||
func testReceiveEcnAndPacketInfoIPV4VectorReadVectorWrite() {
|
||||
testEcnAndPacketInfoReceive(address: "127.0.0.1", vectorRead: true, vectorSend: true, receivePacketInfo: true)
|
||||
}
|
||||
|
||||
func testReceiveEcnAndPacketInfoIPV6VectorReadVectorWrite() {
|
||||
guard System.supportsIPv6 else {
|
||||
return // need to skip IPv6 tests if we don't support it.
|
||||
}
|
||||
testEcnAndPacketInfoReceive(address: "::1", vectorRead: true, vectorSend: true, receivePacketInfo: true)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user