Skip to content

Commit

Permalink
feat: complete debug menu, log to file
Browse files Browse the repository at this point in the history
  • Loading branch information
khcrysalis committed Oct 1, 2024
1 parent 5a45709 commit da35995
Show file tree
Hide file tree
Showing 13 changed files with 403 additions and 34 deletions.
40 changes: 39 additions & 1 deletion Shared/Logging/Logger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,32 +35,70 @@ final class Debug {
static let shared = Debug()
private let subsystem = Bundle.main.bundleIdentifier!

private var logFilePath: URL {
return getDocumentsDirectory().appendingPathComponent("logs.txt")
}

private func appendLogToFile(_ message: String) {
do {
if FileManager.default.fileExists(atPath: logFilePath.path) {
let fileHandle = try FileHandle(forUpdating: logFilePath)
fileHandle.seekToEndOfFile()
if let data = message.data(using: .utf8) {
fileHandle.write(data)
}
fileHandle.closeFile()
}
} catch {
Debug.shared.log(message: "Error writing to logs.txt: \(error)")
}
}

func log(message: String, type: LogType? = nil, function: String = #function, file: String = #file, line: Int = #line) {
lazy var logger = Logger(subsystem: subsystem, category: file+"->"+function)
lazy var logger = Logger(subsystem: subsystem, category: file + "->" + function)

// Prepare the emoji based on the log type
var emoji: String
switch type {
case .success:
emoji = ""
logger.info("\(message)")
showSuccessAlert(with: String.localized("ALERT_SUCCESS"), subtitle: message)
case .info:
emoji = "ℹ️"
logger.info("\(message)")
case .debug:
emoji = "🐛"
logger.debug("\(message)")
case .trace:
emoji = "🔍"
logger.trace("\(message)")
showErrorUIAlert(with: String.localized("ALERT_TRACE"), subtitle: message)
case .warning:
emoji = "⚠️"
logger.warning("\(message)")
showErrorAlert(with: String.localized("ALERT_ERROR"), subtitle: message)
case .error:
emoji = ""
logger.error("\(message)")
showErrorAlert(with: String.localized("ALERT_ERROR"), subtitle: message)
case .critical:
emoji = "🔥"
logger.critical("\(message)")
showErrorUIAlert(with: String.localized("ALERT_CRITICAL"), subtitle: message)
default:
emoji = "📝"
logger.log("\(message)")
}

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let timeString = dateFormatter.string(from: Date())

let logMessage = "[\(timeString)] \(emoji) \(message)\n"
appendLogToFile(logMessage)
}


func showSuccessAlert(with title: String, subtitle: String) {
DispatchQueue.main.async {
Expand Down
3 changes: 1 addition & 2 deletions Shared/Server/Server.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,6 @@ class Installer: Identifiable, ObservableObject {
return Response(status: .ok, headers: headers, body: .init(string: html))
}


try app.server.start()
needsShutdown = true
Debug.shared.log(message: "Server started: Port \(port) for \(Self.sni)")
Expand Down Expand Up @@ -135,7 +134,7 @@ extension Installer {
app.http.server.configuration.tlsConfiguration = try Self.setupTLS()
}
app.http.server.configuration.hostname = Self.sni
print(self.sni)
Debug.shared.log(message: self.sni)
app.http.server.configuration.tcpNoDelay = true

app.http.server.configuration.address = .hostname("0.0.0.0", port: port)
Expand Down
29 changes: 24 additions & 5 deletions Shared/Signing/AppSigner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ func signInitialApp(options: AppSigningOptions, appPath: URL, completion: @escap
var iconURL = ""

do {
Debug.shared.log(message: "============================================")
Debug.shared.log(message: "\(options)")
Debug.shared.log(message: "============================================")
try fileManager.createDirectory(at: tmpDir, withIntermediateDirectories: true)
try fileManager.copyItem(at: appPath, to: tmpDirApp)

Expand Down Expand Up @@ -77,8 +80,12 @@ func signInitialApp(options: AppSigningOptions, appPath: URL, completion: @escap
let provisionPath = certPath.appendingPathComponent("\(options.certificate?.provisionPath ?? "")").path
let p12Path = certPath.appendingPathComponent("\(options.certificate?.p12Path ?? "")").path

Debug.shared.log(message: "🦋 Start Signing 🦋")

try signAppWithZSign(tmpDirApp: tmpDirApp, certPaths: (provisionPath, p12Path), password: options.certificate?.password ?? "", options: options)

Debug.shared.log(message: "🦋 End Signing 🦋")

let signedUUID = UUID().uuidString
try fileManager.createDirectory(at: getDocumentsDirectory().appendingPathComponent("Apps/Signed"), withIntermediateDirectories: true)
let path = getDocumentsDirectory().appendingPathComponent("Apps/Signed").appendingPathComponent(signedUUID)
Expand All @@ -101,6 +108,7 @@ func signInitialApp(options: AppSigningOptions, appPath: URL, completion: @escap
}

Debug.shared.log(message: String.localized("SUCCESS_SIGNED", arguments: "\(options.name ?? String.localized("UNKNOWN"))"), type: .success)
Debug.shared.log(message: "============================================")

UIApplication.shared.isIdleTimerDisabled = false
completion(true)
Expand All @@ -123,11 +131,17 @@ func resignApp(certificate: Certificate, appPath: URL, completion: @escaping (Bo
let provisionPath = certPath.appendingPathComponent("\(certificate.provisionPath ?? "")").path
let p12Path = certPath.appendingPathComponent("\(certificate.p12Path ?? "")").path

Debug.shared.log(message: "============================================")
Debug.shared.log(message: "🦋 Start Resigning 🦋")

try signAppWithZSign(tmpDirApp: appPath, certPaths: (provisionPath, p12Path), password: certificate.password ?? "", options: nil)

Debug.shared.log(message: "🦋 End Resigning 🦋")
DispatchQueue.main.async {
UIApplication.shared.isIdleTimerDisabled = false
Debug.shared.log(message: String.localized("SUCCESS_RESIGN"), type: .success)
}
Debug.shared.log(message: "============================================")
completion(true)
} catch {
Debug.shared.log(message: "\(error)", type: .warning)
Expand Down Expand Up @@ -166,13 +180,12 @@ func updateMobileProvision(app: URL) throws {
if FileManager.default.fileExists(atPath: provisioningFilePath.path) {
do {
try FileManager.default.removeItem(at: provisioningFilePath)
Debug.shared.log(message: "embedded.mobileprovision file removed successfully.")
Debug.shared.log(message: "Embedded.mobileprovision file removed successfully!")
} catch {
Debug.shared.log(message: "Failed to remove embedded.mobileprovision file: \(error)")
throw error
}
} else {
Debug.shared.log(message: "No embedded.mobileprovision file found.")
Debug.shared.log(message: "Could not find any mobileprovision to remove. ")
}
}

Expand All @@ -185,7 +198,7 @@ func listDylibs(filePath: String) -> [String]? {
let dylibPaths = dylibPathsArray as! [String]
return dylibPaths
} else {
print("Failed to list dylibs.")
Debug.shared.log(message: "Failed to list dylibs.")
return nil
}
}
Expand All @@ -202,9 +215,12 @@ func updatePlugIns(options: AppSigningOptions, app: URL) throws {
if filemanager.fileExists(atPath: path.path) {
do {
try filemanager.removeItem(at: path)
Debug.shared.log(message: "Removed PlugIns!")
} catch {
throw error
}
} else {
Debug.shared.log(message: "Could not find any PlugIns to remove.")
}
}
}
Expand All @@ -216,9 +232,12 @@ func removeDumbAssPlaceHolderExtension(options: AppSigningOptions, app: URL) thr
if filemanager.fileExists(atPath: path.path) {
do {
try filemanager.removeItem(at: path)
Debug.shared.log(message: "Removed placeholder watch app!")
} catch {
throw error
}
} else {
Debug.shared.log(message: "Placeholder watch app not found.")
}
}
}
Expand Down Expand Up @@ -263,7 +282,7 @@ func updateInfoPlist(infoDict: NSMutableDictionary, options: AppSigningOptions,
infoDict["CFBundleIcons~ipad"] = cfBundleIconsIpad

} else {
Debug.shared.log(message: "updateInfoPlist.updateicon: Does not include an icon! Will not this.")
Debug.shared.log(message: "updateInfoPlist.updateicon: Does not include an icon! Will not do this.")
}

if options.forceFileSharing! { infoDict.setObject(true, forKey: "UISupportsDocumentBrowser" as NSCopying) }
Expand Down
25 changes: 25 additions & 0 deletions Shared/Signing/zsign/Utils.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//
// Utils.hpp
// feather
//
// Created by samara on 30.09.2024.
//

#ifndef Utils_hpp
#define Utils_hpp

#include <stdio.h>


#ifdef __cplusplus
extern "C" {
#endif

const char* getDocumentsDirectory();


#ifdef __cplusplus
}
#endif

#endif /* zsign_hpp */
19 changes: 19 additions & 0 deletions Shared/Signing/zsign/Utils.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//
// Utils.cpp
// feather
//
// Created by samara on 30.09.2024.
//

#include "Utils.hpp"
#import <Foundation/Foundation.h>

extern "C" {

const char* getDocumentsDirectory() {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
const char *documentsPath = [documentsDirectory UTF8String];
return documentsPath;
}
}
33 changes: 29 additions & 4 deletions Shared/Signing/zsign/common/common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#include <sys/stat.h>
#include <inttypes.h>
#include <openssl/sha.h>
#include "Utils.hpp"
#include <fstream>

#define PARSEVALIST(szFormatArgs, szArgs) \
ZBuffer buffer; \
Expand Down Expand Up @@ -701,20 +703,33 @@ void ZLog::SetLogLever(int nLogLevel)
g_nLogLevel = nLogLevel;
}

void ZLog::writeToLogFile(const std::string& message) {
const char* documentsPath = getDocumentsDirectory();
std::string logFilePath = std::string(documentsPath) + "/logs.txt";

std::ofstream logFile(logFilePath, std::ios_base::app);
if (logFile.is_open()) {
logFile << message;
logFile.close();
} else {
std::cerr << "Failed to open log file: " << logFilePath << std::endl;
}
}

void ZLog::Print(int nLevel, const char *szLog)
{
if (g_nLogLevel >= nLevel)
{
write(STDOUT_FILENO, szLog, strlen(szLog));
writeToLogFile(szLog);
}
}

void ZLog::PrintV(int nLevel, const char *szFormatArgs, ...)
{
if (g_nLogLevel >= nLevel)
{
void ZLog::PrintV(int nLevel, const char *szFormatArgs, ...) {
if (g_nLogLevel >= nLevel) {
PARSEVALIST(szFormatArgs, szLog)
write(STDOUT_FILENO, szLog, strlen(szLog));
writeToLogFile(szLog);
}
}

Expand All @@ -723,6 +738,7 @@ bool ZLog::Error(const char *szLog)
write(STDOUT_FILENO, "\033[31m", 5);
write(STDOUT_FILENO, szLog, strlen(szLog));
write(STDOUT_FILENO, "\033[0m", 4);
writeToLogFile(szLog);
return false;
}

Expand All @@ -732,6 +748,7 @@ bool ZLog::ErrorV(const char *szFormatArgs, ...)
write(STDOUT_FILENO, "\033[31m", 5);
write(STDOUT_FILENO, szLog, strlen(szLog));
write(STDOUT_FILENO, "\033[0m", 4);
writeToLogFile(szLog);
return false;
}

Expand All @@ -740,6 +757,7 @@ bool ZLog::Success(const char *szLog)
write(STDOUT_FILENO, "\033[32m", 5);
write(STDOUT_FILENO, szLog, strlen(szLog));
write(STDOUT_FILENO, "\033[0m", 4);
writeToLogFile(szLog);
return true;
}

Expand All @@ -749,6 +767,7 @@ bool ZLog::SuccessV(const char *szFormatArgs, ...)
write(STDOUT_FILENO, "\033[32m", 5);
write(STDOUT_FILENO, szLog, strlen(szLog));
write(STDOUT_FILENO, "\033[0m", 4);
writeToLogFile(szLog);
return true;
}

Expand All @@ -768,6 +787,7 @@ bool ZLog::Warn(const char *szLog)
write(STDOUT_FILENO, "\033[33m", 5);
write(STDOUT_FILENO, szLog, strlen(szLog));
write(STDOUT_FILENO, "\033[0m", 4);
writeToLogFile(szLog);
return false;
}

Expand All @@ -777,6 +797,7 @@ bool ZLog::WarnV(const char *szFormatArgs, ...)
write(STDOUT_FILENO, "\033[33m", 5);
write(STDOUT_FILENO, szLog, strlen(szLog));
write(STDOUT_FILENO, "\033[0m", 4);
writeToLogFile(szLog);
return false;
}

Expand All @@ -785,6 +806,7 @@ void ZLog::Print(const char *szLog)
if (g_nLogLevel >= E_INFO)
{
write(STDOUT_FILENO, szLog, strlen(szLog));
writeToLogFile(szLog);
}
}

Expand All @@ -794,6 +816,7 @@ void ZLog::PrintV(const char *szFormatArgs, ...)
{
PARSEVALIST(szFormatArgs, szLog)
write(STDOUT_FILENO, szLog, strlen(szLog));
writeToLogFile(szLog);
}
}

Expand All @@ -802,6 +825,7 @@ void ZLog::Debug(const char *szLog)
if (g_nLogLevel >= E_DEBUG)
{
write(STDOUT_FILENO, szLog, strlen(szLog));
writeToLogFile(szLog);
}
}

Expand All @@ -811,6 +835,7 @@ void ZLog::DebugV(const char *szFormatArgs, ...)
{
PARSEVALIST(szFormatArgs, szLog)
write(STDOUT_FILENO, szLog, strlen(szLog));
writeToLogFile(szLog);
}
}

Expand Down
4 changes: 3 additions & 1 deletion Shared/Signing/zsign/common/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,6 @@ class ZLog

private:
static int g_nLogLevel;
};
static void writeToLogFile(const std::string& message);

};
1 change: 0 additions & 1 deletion Shared/Signing/zsign/zsign.mm
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
return [[[paths objectAtIndex:0] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"tmp"];
}


extern "C" {

bool InjectDyLib(NSString *filePath, NSString *dylibPath, bool weakInject, bool bCreate) {
Expand Down
Loading

0 comments on commit da35995

Please sign in to comment.