Refactor interface name query

Signed-off-by: Andrej Mihajlov <and@mullvad.net>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Andrej Mihajlov 2020-06-19 12:37:34 +02:00 committed by Jason A. Donenfeld
parent 112545248e
commit 35300d1c5f
1 changed files with 25 additions and 7 deletions

View File

@ -62,14 +62,10 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
startTunnelCompletionHandler(PacketTunnelProviderError.couldNotDetermineFileDescriptor)
return
}
var ifnameSize = socklen_t(IFNAMSIZ)
let ifnamePtr = UnsafeMutablePointer<CChar>.allocate(capacity: Int(ifnameSize))
ifnamePtr.initialize(repeating: 0, count: Int(ifnameSize))
if getsockopt(fileDescriptor, 2 /* SYSPROTO_CONTROL */, 2 /* UTUN_OPT_IFNAME */, ifnamePtr, &ifnameSize) == 0 {
self.ifname = String(cString: ifnamePtr)
}
ifnamePtr.deallocate()
self.ifname = Self.getInterfaceName(fileDescriptor: fileDescriptor)
wg_log(.info, message: "Tunnel interface is \(self.ifname ?? "unknown")")
let handle = self.packetTunnelSettingsGenerator!.uapiConfiguration()
.withCString { return wgTurnOn($0, fileDescriptor) }
if handle < 0 {
@ -122,6 +118,28 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
}
}
private class func getInterfaceName(fileDescriptor: Int32) -> String? {
var ifnameBytes = [CChar](repeating: 0, count: Int(IF_NAMESIZE))
return ifnameBytes.withUnsafeMutableBufferPointer { bufferPointer -> String? in
guard let baseAddress = bufferPointer.baseAddress else { return nil }
var ifnameSize = socklen_t(bufferPointer.count)
let result = getsockopt(
fileDescriptor,
2 /* SYSPROTO_CONTROL */,
2 /* UTUN_OPT_IFNAME */,
baseAddress, &ifnameSize
)
if result == 0 {
return String(cString: baseAddress)
} else {
return nil
}
}
}
private func configureLogger() {
Logger.configureGlobal(tagged: "NET", withFilePath: FileManager.logFileURL?.path)
wgSetLogger { level, msgC in