From ae7fb7323faf6321d07dd855ea4f7641d2424ec0 Mon Sep 17 00:00:00 2001 From: Roopesh Chander Date: Thu, 13 Dec 2018 15:38:10 +0530 Subject: [PATCH] Logging: Use ringlogger for logging from the extension Signed-off-by: Roopesh Chander --- WireGuard/Shared/FileManager+Extension.swift | 10 +++- WireGuard/Shared/Logging/Logger.swift | 54 +++++++++++++++++++ .../{RingLogger => Logging}/ringlogger.c | 17 ------ .../{RingLogger => Logging}/ringlogger.h | 18 ++++++- WireGuard/WireGuard.xcodeproj/project.pbxproj | 22 ++++++++ WireGuard/WireGuard/UI/iOS/AppDelegate.swift | 8 +++ .../UI/iOS/SettingsTableViewController.swift | 18 +++---- .../WireGuard/WireGuard-Bridging-Header.h | 1 + .../PacketTunnelProvider.swift | 41 +------------- ...ireGuardNetworkExtension-Bridging-Header.h | 1 + 10 files changed, 121 insertions(+), 69 deletions(-) create mode 100644 WireGuard/Shared/Logging/Logger.swift rename WireGuard/Shared/{RingLogger => Logging}/ringlogger.c (90%) rename WireGuard/Shared/{RingLogger => Logging}/ringlogger.h (54%) diff --git a/WireGuard/Shared/FileManager+Extension.swift b/WireGuard/Shared/FileManager+Extension.swift index 535b999..06f9e44 100644 --- a/WireGuard/Shared/FileManager+Extension.swift +++ b/WireGuard/Shared/FileManager+Extension.swift @@ -14,7 +14,15 @@ extension FileManager { os_log("Can't obtain shared folder URL", log: OSLog.default, type: .error) return nil } - return sharedFolderURL.appendingPathComponent("last-activated-tunnel-log.txt") + return sharedFolderURL.appendingPathComponent("tunnel-log.txt") + } + + static var appLogFileURL: URL? { + guard let documentDirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { + os_log("Can't obtain app documents folder URL", log: OSLog.default, type: .error) + return nil + } + return documentDirURL.appendingPathComponent("app-log.txt") } static func deleteFile(at url: URL) -> Bool { diff --git a/WireGuard/Shared/Logging/Logger.swift b/WireGuard/Shared/Logging/Logger.swift new file mode 100644 index 0000000..bc0ffd4 --- /dev/null +++ b/WireGuard/Shared/Logging/Logger.swift @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: MIT +// Copyright © 2018 WireGuard LLC. All Rights Reserved. + +import os.log + +class Logger { + static var logPtr: UnsafeMutablePointer? + + static func configure(withFilePath filePath: String) -> Bool { + let logPtr = filePath.withCString { filePathCStr -> UnsafeMutablePointer? in + return open_log(filePathCStr) + } + Logger.logPtr = logPtr + return (logPtr != nil) + } + + static func writeLog(mergedWith otherLogFile: String, to targetFile: String) -> Bool { + let otherlogPtr = otherLogFile.withCString { otherLogFileCStr -> UnsafeMutablePointer? in + return open_log(otherLogFileCStr) + } + if let thisLogPtr = Logger.logPtr, let otherlogPtr = otherlogPtr { + return targetFile.withCString { targetFileCStr -> Bool in + let returnValue = write_logs_to_file(targetFileCStr, thisLogPtr, otherlogPtr) + return (returnValue == 0) + } + } + return false + } +} + +func wg_log(_ type: OSLogType, staticMessage msg: StaticString) { + // Write to os log + os_log(msg, log: OSLog.default, type: type) + // Write to file log + let msgString: String = msg.withUTF8Buffer { (ptr: UnsafeBufferPointer) -> String in + return String(decoding: ptr, as: UTF8.self) + } + file_log(type: type, message: msgString) +} + +func wg_log(_ type: OSLogType, message msg: String) { + // Write to os log + os_log("%{public}s", log: OSLog.default, type: type, msg) + // Write to file log + file_log(type: type, message: msg) +} + +private func file_log(type: OSLogType, message: String) { + message.withCString { messageCStr in + if let logPtr = Logger.logPtr { + write_msg_to_log(logPtr, messageCStr) + } + } +} diff --git a/WireGuard/Shared/RingLogger/ringlogger.c b/WireGuard/Shared/Logging/ringlogger.c similarity index 90% rename from WireGuard/Shared/RingLogger/ringlogger.c rename to WireGuard/Shared/Logging/ringlogger.c index d39b9d7..ea862de 100644 --- a/WireGuard/Shared/RingLogger/ringlogger.c +++ b/WireGuard/Shared/Logging/ringlogger.c @@ -16,23 +16,6 @@ #include #include "ringlogger.h" -enum { - MAX_LOG_LINE_LENGTH = 512, - MAX_LINES = 1024, - MAGIC = 0xdeadbeefU -}; - -struct log_line { - struct timeval tv; - char line[MAX_LOG_LINE_LENGTH]; -}; - -struct log { - struct { uint32_t first, len; } header; - struct log_line lines[MAX_LINES]; - uint32_t magic; -}; - void write_msg_to_log(struct log *log, const char *msg) { struct log_line *line = &log->lines[(log->header.first + log->header.len) % MAX_LINES]; diff --git a/WireGuard/Shared/RingLogger/ringlogger.h b/WireGuard/Shared/Logging/ringlogger.h similarity index 54% rename from WireGuard/Shared/RingLogger/ringlogger.h rename to WireGuard/Shared/Logging/ringlogger.h index d90e0c5..a8d07c0 100644 --- a/WireGuard/Shared/RingLogger/ringlogger.h +++ b/WireGuard/Shared/Logging/ringlogger.h @@ -6,7 +6,23 @@ #ifndef RINGLOGGER_H #define RINGLOGGER_H -struct log; +enum { + MAX_LOG_LINE_LENGTH = 512, + MAX_LINES = 1024, + MAGIC = 0xdeadbeefU +}; + +struct log_line { + struct timeval tv; + char line[MAX_LOG_LINE_LENGTH]; +}; + +struct log { + struct { uint32_t first, len; } header; + struct log_line lines[MAX_LINES]; + uint32_t magic; +}; + void write_msg_to_log(struct log *log, const char *msg); int write_logs_to_file(const char *file_name, const struct log *log1, const struct log *log2); struct log *open_log(const char *file_name); diff --git a/WireGuard/WireGuard.xcodeproj/project.pbxproj b/WireGuard/WireGuard.xcodeproj/project.pbxproj index 93ed1b0..049071b 100644 --- a/WireGuard/WireGuard.xcodeproj/project.pbxproj +++ b/WireGuard/WireGuard.xcodeproj/project.pbxproj @@ -45,6 +45,10 @@ 6FDEF8082187442100D8FBF6 /* WgQuickConfigFileWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FDEF8072187442100D8FBF6 /* WgQuickConfigFileWriter.swift */; }; 6FE254FB219C10800028284D /* ZipImporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FE254FA219C10800028284D /* ZipImporter.swift */; }; 6FE254FF219C60290028284D /* ZipExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FE254FE219C60290028284D /* ZipExporter.swift */; }; + 6FF3527021C240160008484E /* ringlogger.c in Sources */ = {isa = PBXBuildFile; fileRef = 6FF3526C21C23F960008484E /* ringlogger.c */; }; + 6FF3527121C240160008484E /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FF3526E21C23FA10008484E /* Logger.swift */; }; + 6FF3527221C2616C0008484E /* ringlogger.c in Sources */ = {isa = PBXBuildFile; fileRef = 6FF3526C21C23F960008484E /* ringlogger.c */; }; + 6FF3527321C2616C0008484E /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FF3526E21C23FA10008484E /* Logger.swift */; }; 6FF4AC1F211EC472002C96EB /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 6FF4AC1E211EC472002C96EB /* Assets.xcassets */; }; 6FF4AC22211EC472002C96EB /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6FF4AC20211EC472002C96EB /* LaunchScreen.storyboard */; }; 6FF717E521B2CB1E0045A474 /* InternetReachability.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6FF717E421B2CB1E0045A474 /* InternetReachability.swift */; }; @@ -139,6 +143,9 @@ 6FDEF8072187442100D8FBF6 /* WgQuickConfigFileWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WgQuickConfigFileWriter.swift; sourceTree = ""; }; 6FE254FA219C10800028284D /* ZipImporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZipImporter.swift; sourceTree = ""; }; 6FE254FE219C60290028284D /* ZipExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZipExporter.swift; sourceTree = ""; }; + 6FF3526B21C23F960008484E /* ringlogger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ringlogger.h; sourceTree = ""; }; + 6FF3526C21C23F960008484E /* ringlogger.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ringlogger.c; sourceTree = ""; }; + 6FF3526E21C23FA10008484E /* Logger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = ""; }; 6FF4AC14211EC46F002C96EB /* WireGuard.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = WireGuard.app; sourceTree = BUILT_PRODUCTS_DIR; }; 6FF4AC1E211EC472002C96EB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 6FF4AC21211EC472002C96EB /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; @@ -188,6 +195,7 @@ 6F5D0C432183B4A4000F85AD /* Shared */ = { isa = PBXGroup; children = ( + 6FF3526A21C23F720008484E /* Logging */, 6F7774E6217201E0006A79B3 /* Model */, 6FFA5D942194454A0001E2F7 /* NETunnelProviderProtocol+Extension.swift */, 6F5A2B4421AFDE020081EDD8 /* FileManager+Extension.swift */, @@ -313,6 +321,16 @@ path = minizip; sourceTree = ""; }; + 6FF3526A21C23F720008484E /* Logging */ = { + isa = PBXGroup; + children = ( + 6FF3526C21C23F960008484E /* ringlogger.c */, + 6FF3526B21C23F960008484E /* ringlogger.h */, + 6FF3526E21C23FA10008484E /* Logger.swift */, + ); + path = Logging; + sourceTree = ""; + }; 6FF4AC0B211EC46F002C96EB = { isa = PBXGroup; children = ( @@ -580,6 +598,8 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 6FF3527021C240160008484E /* ringlogger.c in Sources */, + 6FF3527121C240160008484E /* Logger.swift in Sources */, 6F5A2B4621AFDED40081EDD8 /* FileManager+Extension.swift in Sources */, 6FFA5DA021958ECC0001E2F7 /* ErrorNotifier.swift in Sources */, 6FFA5D96219446380001E2F7 /* NETunnelProviderProtocol+Extension.swift in Sources */, @@ -597,6 +617,8 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 6FF3527221C2616C0008484E /* ringlogger.c in Sources */, + 6FF3527321C2616C0008484E /* Logger.swift in Sources */, 6F6899AC218099F00012E523 /* WgQuickConfigFileParser.swift in Sources */, 6F7774E421718281006A79B3 /* TunnelsListTableViewController.swift in Sources */, 6F7774EF21722D97006A79B3 /* TunnelsManager.swift in Sources */, diff --git a/WireGuard/WireGuard/UI/iOS/AppDelegate.swift b/WireGuard/WireGuard/UI/iOS/AppDelegate.swift index 1a4f15c..5625814 100644 --- a/WireGuard/WireGuard/UI/iOS/AppDelegate.swift +++ b/WireGuard/WireGuard/UI/iOS/AppDelegate.swift @@ -13,6 +13,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + if let appLogFilePath = FileManager.appLogFileURL?.path { + if !Logger.configure(withFilePath: appLogFilePath) { + os_log("Can't open log file for writing. Log is not saved to file.", log: OSLog.default, type: .error) + } + } else { + os_log("Can't obtain log file URL. Log is not saved to file.", log: OSLog.default, type: .error) + } + let window = UIWindow(frame: UIScreen.main.bounds) window.backgroundColor = UIColor.white self.window = window diff --git a/WireGuard/WireGuard/UI/iOS/SettingsTableViewController.swift b/WireGuard/WireGuard/UI/iOS/SettingsTableViewController.swift index fe276b1..43e277e 100644 --- a/WireGuard/WireGuard/UI/iOS/SettingsTableViewController.swift +++ b/WireGuard/WireGuard/UI/iOS/SettingsTableViewController.swift @@ -108,23 +108,19 @@ class SettingsTableViewController: UITableViewController { if FileManager.default.fileExists(atPath: destinationURL.path) { let isDeleted = FileManager.deleteFile(at: destinationURL) if !isDeleted { - ErrorPresenter.showErrorAlert(title: "No log available", message: "The pre-existing log could not be cleared", from: self) + ErrorPresenter.showErrorAlert(title: "Log export failed", message: "The pre-existing log could not be cleared", from: self) return } } - guard let networkExtensionLogFileURL = FileManager.networkExtensionLogFileURL, - FileManager.default.fileExists(atPath: networkExtensionLogFileURL.path) else { - ErrorPresenter.showErrorAlert(title: "No log available", message: "Please activate a tunnel and then export the log", from: self) - return + guard let networkExtensionLogFilePath = FileManager.networkExtensionLogFileURL?.path else { + ErrorPresenter.showErrorAlert(title: "Log export failed", message: "Internal error obtaining extension log path", from: self) + return } - do { - try FileManager.default.copyItem(at: networkExtensionLogFileURL, to: destinationURL) - } catch { - os_log("Failed to copy file: %{public}@ to %{public}@: %{public}@", log: OSLog.default, type: .error, - networkExtensionLogFileURL.absoluteString, destinationURL.absoluteString, error.localizedDescription) - ErrorPresenter.showErrorAlert(title: "Log export failed", message: "The log could not be copied", from: self) + let isWritten = Logger.writeLog(mergedWith: networkExtensionLogFilePath, to: destinationURL.path) + guard isWritten else { + ErrorPresenter.showErrorAlert(title: "Log export failed", message: "Internal error merging logs", from: self) return } diff --git a/WireGuard/WireGuard/WireGuard-Bridging-Header.h b/WireGuard/WireGuard/WireGuard-Bridging-Header.h index 4fe53a7..21cd2a2 100644 --- a/WireGuard/WireGuard/WireGuard-Bridging-Header.h +++ b/WireGuard/WireGuard/WireGuard-Bridging-Header.h @@ -2,3 +2,4 @@ #include "unzip.h" #include "zip.h" #include "wireguard-go-version.h" +#include "ringlogger.h" diff --git a/WireGuard/WireGuardNetworkExtension/PacketTunnelProvider.swift b/WireGuard/WireGuardNetworkExtension/PacketTunnelProvider.swift index 5cac333..04e3893 100644 --- a/WireGuard/WireGuardNetworkExtension/PacketTunnelProvider.swift +++ b/WireGuard/WireGuardNetworkExtension/PacketTunnelProvider.swift @@ -153,15 +153,9 @@ class PacketTunnelProvider: NEPacketTunnelProvider { private func configureLogger() { // Setup writing the log to a file - if let networkExtensionLogFileURL = FileManager.networkExtensionLogFileURL { - let fileManager = FileManager.default - let filePath = networkExtensionLogFileURL.path - fileManager.createFile(atPath: filePath, contents: nil) // Create the file if it doesn't already exist - if let fileHandle = FileHandle(forWritingAtPath: filePath) { - logFileHandle = fileHandle - } else { + if let networkExtensionLogFilePath = FileManager.networkExtensionLogFileURL?.path { + if !Logger.configure(withFilePath: networkExtensionLogFilePath) { os_log("Can't open log file for writing. Log is not saved to file.", log: OSLog.default, type: .error) - logFileHandle = nil } } else { os_log("Can't obtain log file URL. Log is not saved to file.", log: OSLog.default, type: .error) @@ -213,34 +207,3 @@ private func withStringsAsGoStrings(_ str1: String, _ str2: String, closure: } } } - -private func wg_log(_ type: OSLogType, staticMessage msg: StaticString) { - // Write to os log - os_log(msg, log: OSLog.default, type: type) - // Write to file log - let msgString: String = msg.withUTF8Buffer { (ptr: UnsafeBufferPointer) -> String in - return String(decoding: ptr, as: UTF8.self) - } - file_log(type: type, message: msgString) -} - -private func wg_log(_ type: OSLogType, message msg: String) { - // Write to os log - os_log("%{public}s", log: OSLog.default, type: type, msg) - // Write to file log - file_log(type: type, message: msg) -} - -private func file_log(type: OSLogType, message: String) { - let formatter = DateFormatter() - formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS: " - var msgLine = formatter.string(from: Date()) + message - if msgLine.last! != "\n" { - msgLine.append("\n") - } - let data = msgLine.data(using: .utf8) - if let data = data, let logFileHandle = logFileHandle { - logFileHandle.write(data) - logFileHandle.synchronizeFile() - } -} diff --git a/WireGuard/WireGuardNetworkExtension/WireGuardNetworkExtension-Bridging-Header.h b/WireGuard/WireGuardNetworkExtension/WireGuardNetworkExtension-Bridging-Header.h index 95d3f4b..2c6a2d0 100644 --- a/WireGuard/WireGuardNetworkExtension/WireGuardNetworkExtension-Bridging-Header.h +++ b/WireGuard/WireGuardNetworkExtension/WireGuardNetworkExtension-Bridging-Header.h @@ -1,2 +1,3 @@ #include "../../wireguard-go-bridge/wireguard.h" #include "wireguard-go-version.h" +#include "ringlogger.h"