Skip to content

Commit

Permalink
iOS logging fix
Browse files Browse the repository at this point in the history
  • Loading branch information
pokamest committed Aug 24, 2023
1 parent c2c602b commit 7cb7b9b
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 43 deletions.
19 changes: 9 additions & 10 deletions client/platforms/ios/ioslogger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@ public class Logger {
deinit {}

func log(message: String) {
print(message)
NSLog("AmneziaVPN NE: \(message)")

write_msg_to_log(tag, message.trimmingCharacters(in: .newlines))

let suiteName = "group.org.amnezia.AmneziaVPN"
let logKey = "logMessages"
let sharedDefaults = UserDefaults(suiteName: suiteName)
var logs = sharedDefaults?.array(forKey: logKey) as? [String] ?? []
logs.append(message)
sharedDefaults?.set(logs, forKey: logKey)
// let suiteName = "group.org.amnezia.AmneziaVPN"
// let logKey = "logMessages"
// let sharedDefaults = UserDefaults(suiteName: suiteName)
// var logs = sharedDefaults?.array(forKey: logKey) as? [String] ?? []
// logs.append(message)
// sharedDefaults?.set(logs, forKey: logKey)
}

func writeLog(to targetFile: String) -> Bool {
Expand All @@ -45,8 +46,7 @@ public class Logger {
appVersion += " (\(appBuild))"
}

let goBackendVersion = "1"
Logger.global?.log(message: "App version: \(appVersion); Go backend version: \(goBackendVersion)")
Logger.global?.log(message: "App version: \(appVersion)")
}
}

Expand All @@ -58,5 +58,4 @@ func wg_log(_ type: OSLogType, staticMessage msg: StaticString) {
func wg_log(_ type: OSLogType, message msg: String) {
os_log("%{AMNEZIA}s", log: OSLog.default, type: type, msg)
Logger.global?.log(message: msg)
NSLog("AMNEZIA: \(msg)")
}
104 changes: 71 additions & 33 deletions client/platforms/ios/iostunnel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
wg_log(logLevel.osLogLevel, message: message)
}
}()

private lazy var ovpnAdapter: OpenVPNAdapter = {
let adapter = OpenVPNAdapter()
adapter.delegate = self
Expand All @@ -56,6 +56,7 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
var protoType: TunnelProtoType = .none

override init() {
Logger.configureGlobal(tagged: Constants.loggerTag, withFilePath: FileManager.logFileURL?.path)
Logger.global?.log(message: "Init NEPacketTunnelProvider")
super.init()
}
Expand Down Expand Up @@ -119,7 +120,6 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
let activationAttemptId = options?[Constants.kActivationAttemptId] as? String
let errorNotifier = ErrorNotifier(activationAttemptId: activationAttemptId)

Logger.configureGlobal(tagged: Constants.loggerTag, withFilePath: FileManager.logFileURL?.path)
Logger.global?.log(message: "PacketTunnelProvider startTunnel")

if let protocolConfiguration = self.protocolConfiguration as? NETunnelProviderProtocol {
Expand Down Expand Up @@ -174,6 +174,8 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
self.protoType = .none
}

// self.startEmptyTunnel(completionHandler: completionHandler)
// return


switch self.protoType {
Expand Down Expand Up @@ -239,36 +241,36 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
wgAdapter.start(tunnelConfiguration: tunnelConfiguration) { adapterError in
guard let adapterError = adapterError else {
let interfaceName = self.wgAdapter.interfaceName ?? "unknown"

wg_log(.info, message: "Tunnel interface is \(interfaceName)")

completionHandler(nil)
return
}

switch adapterError {
case .cannotLocateTunnelFileDescriptor:
wg_log(.error, staticMessage: "Starting tunnel failed: could not determine file descriptor")
errorNotifier.notify(PacketTunnelProviderError.couldNotDetermineFileDescriptor)
completionHandler(PacketTunnelProviderError.couldNotDetermineFileDescriptor)

case .dnsResolution(let dnsErrors):
let hostnamesWithDnsResolutionFailure = dnsErrors.map { $0.address }
.joined(separator: ", ")
wg_log(.error, message: "DNS resolution failed for the following hostnames: \(hostnamesWithDnsResolutionFailure)")
errorNotifier.notify(PacketTunnelProviderError.dnsResolutionFailure)
completionHandler(PacketTunnelProviderError.dnsResolutionFailure)

case .setNetworkSettings(let error):
wg_log(.error, message: "Starting tunnel failed with setTunnelNetworkSettings returning \(error.localizedDescription)")
errorNotifier.notify(PacketTunnelProviderError.couldNotSetNetworkSettings)
completionHandler(PacketTunnelProviderError.couldNotSetNetworkSettings)

case .startWireGuardBackend(let errorCode):
wg_log(.error, message: "Starting tunnel failed with wgTurnOn returning \(errorCode)")
errorNotifier.notify(PacketTunnelProviderError.couldNotStartBackend)
completionHandler(PacketTunnelProviderError.couldNotStartBackend)

case .invalidState:
// Must never happen
fatalError()
Expand All @@ -293,12 +295,12 @@ class PacketTunnelProvider: NEPacketTunnelProvider {

wgAdapter.stop { error in
ErrorNotifier.removeLastErrorFile()

if let error = error {
wg_log(.error, message: "Failed to stop WireGuard adapter: \(error.localizedDescription)")
}
completionHandler()

#if os(macOS)
// HACK: This is a filthy hack to work around Apple bug 32073323 (dup'd by us as 47526107).
// Remove it when they finally fix this upstream and the fix has been rolled out to
Expand Down Expand Up @@ -334,7 +336,7 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
completionHandler(nil)
return
}

do {
let tunnelConfiguration = try TunnelConfiguration(fromWgQuickConfig: configString)
wgAdapter.update(tunnelConfiguration: tunnelConfiguration) { error in
Expand All @@ -343,7 +345,7 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
completionHandler(nil)
return
}

self.wgAdapter.getRuntimeConfiguration { settings in
var data: Data?
if let settings = settings {
Expand All @@ -359,24 +361,24 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
completionHandler(nil)
}
}

private func handleOpenVPNAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) {
guard let completionHandler = completionHandler else { return }
if messageData.count == 1 && messageData[0] == 0 {
let bytesin = ovpnAdapter.transportStatistics.bytesIn
let strBytesin = "rx_bytes=" + String(bytesin);

let bytesout = ovpnAdapter.transportStatistics.bytesOut
let strBytesout = "tx_bytes=" + String(bytesout);

let strData = strBytesin + "\n" + strBytesout;
let data = Data(strData.utf8)
completionHandler(data)
}
}



//
private func setupAndlaunchOpenVPN(withConfig ovpnConfiguration: Data, withShadowSocks viaSS: Bool = false, completionHandler: @escaping (Error?) -> Void) {
wg_log(.info, message: "setupAndlaunchOpenVPN")

Expand All @@ -391,33 +393,33 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
let evaluation: OpenVPNConfigurationEvaluation
do {
evaluation = try ovpnAdapter.apply(configuration: configuration)

} catch {
completionHandler(error)
return
}

if !evaluation.autologin {
wg_log(.info, message: "Implement login with user credentials")
}

vpnReachability.startTracking { [weak self] status in
guard status == .reachableViaWiFi else { return }
self?.ovpnAdapter.reconnect(afterTimeInterval: 5)
}

startHandler = completionHandler
ovpnAdapter.connect(using: packetFlow)

// let ifaces = Interface.allInterfaces()
// .filter { $0.family == .ipv4 }
// .map { iface in iface.name }

// wg_log(.error, message: "Available TUN Interfaces: \(ifaces)")
}

// MARK: -- Network observing methods

private func startListeningForNetworkChanges() {
stopListeningForNetworkChanges()
addObserver(self, forKeyPath: Constants.kDefaultPathKey, options: .old, context: nil)
Expand Down Expand Up @@ -451,17 +453,39 @@ class PacketTunnelProvider: NEPacketTunnelProvider {
wg_log(.info, message: "Tunnel restarted.")
startTunnel(options: nil, completionHandler: completion)
}
}

extension WireGuardLogLevel {
var osLogLevel: OSLogType {
switch self {
case .verbose:
return .debug
case .error:
return .error
private func startEmptyTunnel(completionHandler: @escaping (Error?) -> Void) {
dispatchPrecondition(condition: .onQueue(dispatchQueue))

let emptyTunnelConfiguration = TunnelConfiguration(
name: nil,
interface: InterfaceConfiguration(privateKey: PrivateKey()),
peers: []
)

wgAdapter.start(tunnelConfiguration: emptyTunnelConfiguration) { error in
self.dispatchQueue.async {
if let error {
Logger.global?.log(message: "Failed to start an empty tunnel")
completionHandler(error)
} else {
Logger.global?.log(message: "Started an empty tunnel")
self.tunnelAdapterDidStart()
}
}
}

let settings = NETunnelNetworkSettings(tunnelRemoteAddress: "1.1.1.1")

self.setTunnelNetworkSettings(settings) { error in
completionHandler(error)
}
}

private func tunnelAdapterDidStart() {
dispatchPrecondition(condition: .onQueue(dispatchQueue))
// ...
}
}

extension NEPacketTunnelFlow: OpenVPNAdapterPacketFlow {}
Expand Down Expand Up @@ -543,3 +567,17 @@ extension PacketTunnelProvider: OpenVPNAdapterDelegate {
wg_log(.info, message: logMessage)
}
}




extension WireGuardLogLevel {
var osLogLevel: OSLogType {
switch self {
case .verbose:
return .debug
case .error:
return .error
}
}
}

0 comments on commit 7cb7b9b

Please sign in to comment.