]> git.ipfire.org Git - thirdparty/wireguard-apple.git/commitdiff
Logging: Use ringlogger for logging from the extension
authorRoopesh Chander <roop@roopc.net>
Thu, 13 Dec 2018 10:08:10 +0000 (15:38 +0530)
committerRoopesh Chander <roop@roopc.net>
Thu, 13 Dec 2018 12:07:14 +0000 (17:37 +0530)
Signed-off-by: Roopesh Chander <roop@roopc.net>
WireGuard/Shared/FileManager+Extension.swift
WireGuard/Shared/Logging/Logger.swift [new file with mode: 0644]
WireGuard/Shared/Logging/ringlogger.c [moved from WireGuard/Shared/RingLogger/ringlogger.c with 90% similarity]
WireGuard/Shared/Logging/ringlogger.h [moved from WireGuard/Shared/RingLogger/ringlogger.h with 54% similarity]
WireGuard/WireGuard.xcodeproj/project.pbxproj
WireGuard/WireGuard/UI/iOS/AppDelegate.swift
WireGuard/WireGuard/UI/iOS/SettingsTableViewController.swift
WireGuard/WireGuard/WireGuard-Bridging-Header.h
WireGuard/WireGuardNetworkExtension/PacketTunnelProvider.swift
WireGuard/WireGuardNetworkExtension/WireGuardNetworkExtension-Bridging-Header.h

index 535b999611dc16b993df808a74672eba9e4a96e5..06f9e4477fb3aa15db12b488a02ebb4d098e8566 100644 (file)
@@ -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 (file)
index 0000000..bc0ffd4
--- /dev/null
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: MIT
+// Copyright © 2018 WireGuard LLC. All Rights Reserved.
+
+import os.log
+
+class Logger {
+    static var logPtr: UnsafeMutablePointer<log>?
+
+    static func configure(withFilePath filePath: String) -> Bool {
+        let logPtr = filePath.withCString { filePathCStr -> UnsafeMutablePointer<log>? 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<log>? 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<UInt8>) -> 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)
+        }
+    }
+}
similarity index 90%
rename from WireGuard/Shared/RingLogger/ringlogger.c
rename to WireGuard/Shared/Logging/ringlogger.c
index d39b9d7f79d1d930b693f61a015b74e9482a8872..ea862de9060e592d6bcbc1d95bd3ea970b469c77 100644 (file)
 #include <sys/mman.h>
 #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];
similarity index 54%
rename from WireGuard/Shared/RingLogger/ringlogger.h
rename to WireGuard/Shared/Logging/ringlogger.h
index d90e0c5ab35b48ac0de9656cd9efcb17d3c17054..a8d07c03eea50e11f0a5322669128d8dae050f88 100644 (file)
@@ -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);
index 93ed1b063fe39cda6e661fe6812742e0e23cf165..049071b4170fd7399321ac0837b8a55355619ba9 100644 (file)
                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 */; };
                6FDEF8072187442100D8FBF6 /* WgQuickConfigFileWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WgQuickConfigFileWriter.swift; sourceTree = "<group>"; };
                6FE254FA219C10800028284D /* ZipImporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZipImporter.swift; sourceTree = "<group>"; };
                6FE254FE219C60290028284D /* ZipExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZipExporter.swift; sourceTree = "<group>"; };
+               6FF3526B21C23F960008484E /* ringlogger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ringlogger.h; sourceTree = "<group>"; };
+               6FF3526C21C23F960008484E /* ringlogger.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ringlogger.c; sourceTree = "<group>"; };
+               6FF3526E21C23FA10008484E /* Logger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = "<group>"; };
                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 = "<group>"; };
                6FF4AC21211EC472002C96EB /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
                6F5D0C432183B4A4000F85AD /* Shared */ = {
                        isa = PBXGroup;
                        children = (
+                               6FF3526A21C23F720008484E /* Logging */,
                                6F7774E6217201E0006A79B3 /* Model */,
                                6FFA5D942194454A0001E2F7 /* NETunnelProviderProtocol+Extension.swift */,
                                6F5A2B4421AFDE020081EDD8 /* FileManager+Extension.swift */,
                        path = minizip;
                        sourceTree = "<group>";
                };
+               6FF3526A21C23F720008484E /* Logging */ = {
+                       isa = PBXGroup;
+                       children = (
+                               6FF3526C21C23F960008484E /* ringlogger.c */,
+                               6FF3526B21C23F960008484E /* ringlogger.h */,
+                               6FF3526E21C23FA10008484E /* Logger.swift */,
+                       );
+                       path = Logging;
+                       sourceTree = "<group>";
+               };
                6FF4AC0B211EC46F002C96EB = {
                        isa = PBXGroup;
                        children = (
                        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 */,
                        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 */,
index 1a4f15cbe263c61a1bd0df4ca38396bb8c7c4876..56258147f9bec8e50ab7d593826863c864d4f2da 100644 (file)
@@ -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
index fe276b1ceee06931cc98e6305fca2cc934acdf7a..43e277e82bf3103af427cafe38d338a845a93a34 100644 (file)
@@ -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
             }
 
index 4fe53a77cd27fad833780e86d79660974e7ce3d5..21cd2a2d129113c6deae55e33b865a7abd95c957 100644 (file)
@@ -2,3 +2,4 @@
 #include "unzip.h"
 #include "zip.h"
 #include "wireguard-go-version.h"
+#include "ringlogger.h"
index 5cac33312b8fc00457ce1d065e0f0eaa4e5e7ef7..04e3893e6f297af4fcb3b87064ea9dcb2e4bcaa5 100644 (file)
@@ -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<R>(_ 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<UInt8>) -> 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()
-    }
-}
index 95d3f4be14b8106df34985797483b20bdb01e02b..2c6a2d015287e49f2f9e3df57642063a6c50c19a 100644 (file)
@@ -1,2 +1,3 @@
 #include "../../wireguard-go-bridge/wireguard.h"
 #include "wireguard-go-version.h"
+#include "ringlogger.h"