Skip to content

Commit

Permalink
improved logging
Browse files Browse the repository at this point in the history
  • Loading branch information
twocanoes committed May 15, 2023
1 parent 4c887fb commit e92ffe9
Show file tree
Hide file tree
Showing 21 changed files with 185 additions and 122 deletions.
8 changes: 4 additions & 4 deletions LicenseChecker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,17 @@ class LicenseChecker: NSObject {
TCSLogWithMark("valid license")
return .valid
case .expired:
TCSLogWithMark("expired license")
TCSLogErrorWithMark("expired license")
return trialState

case .invalid:
TCSLogWithMark("license invalid")
TCSLogErrorWithMark("license invalid")
return trialState
case .unset:
TCSLogWithMark("No License")
TCSLogErrorWithMark("No License")
return trialState
default:
TCSLogWithMark("invalid license")
TCSLogErrorWithMark("invalid license")
return trialState
}

Expand Down
4 changes: 2 additions & 2 deletions XCreds/Helper+JWTDecode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ func jwtDecode(value: String) -> Dictionary<String, Any>? {
let array = value.components(separatedBy: ".")

if array.count != 3 {
TCSLogWithMark("idToken is invalid")
TCSLogErrorWithMark("idToken is invalid")
return nil
}
let body = array[1]
guard let data = base64UrlDecode(value:body ) else {
TCSLogWithMark("error decoding id token base64")
TCSLogErrorWithMark("error decoding id token base64")
return nil
}

Expand Down
6 changes: 3 additions & 3 deletions XCreds/KeychainUtil.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class KeychainUtil {
}
return password as? String ?? ""
} else {
TCSLogWithMark("Password not found in keychain")
TCSLogErrorWithMark("Password not found in keychain")
throw KeychainError.noStoredPassword
}
}
Expand All @@ -82,7 +82,7 @@ class KeychainUtil {

myErr = setPassword(name, pass: pass)
if myErr != OSStatus(errSecSuccess) {
TCSLogWithMark("setting new password FAILURE")
TCSLogErrorWithMark("setting new password FAILURE")
return false
}
TCSLogWithMark("setting new password success")
Expand All @@ -94,7 +94,7 @@ class KeychainUtil {
updateACL(password:keychainPassword)
}
else {
TCSLogWithMark("ERROR Updating ACL")
TCSLogErrorWithMark("ERROR Updating ACL")

return false
}
Expand Down
26 changes: 24 additions & 2 deletions XCreds/Logger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,37 @@ import Foundation
func TCSLogWithMark(_ message: String = "",
file: String = #file, line: Int = #line, function: String = #function ) {

// let date = Date()


let comp = file.components(separatedBy: "/")
if let lastPart = comp.last{
TCSLog("\(lastPart):\(line) \(function) \(message)")

}

}
func TCSLogInfoWithMark(_ message: String = "",
file: String = #file, line: Int = #line, function: String = #function ) {


let comp = file.components(separatedBy: "/")
if let lastPart = comp.last{
TCSLogInfo("\(lastPart):\(line) \(function) \(message)")

}

}
func TCSLogErrorWithMark(_ message: String = "",
file: String = #file, line: Int = #line, function: String = #function ) {


let comp = file.components(separatedBy: "/")
if let lastPart = comp.last{
TCSLogError("\(lastPart):\(line) \(function) \(message)")

}

}

//
//func Mark(
// file: String = #file, line: Int = #line, function: String = #function ) {
Expand Down
4 changes: 2 additions & 2 deletions XCreds/MainController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class MainController: NSObject {
}
if updatePassword {
guard let localPassword = self.localPassword() else {
TCSLogWithMark("error getting local password")
TCSLogErrorWithMark("error getting local password")
return
}
try? PasswordUtils.changeLocalUserAndKeychainPassword(localPassword, newPassword1: tokens.password, newPassword2: tokens.password)
Expand All @@ -98,7 +98,7 @@ class MainController: NSObject {
}
}
if TokenManager.shared.saveTokensToKeychain(creds: tokens, setACL: true, password:tokens.password ) == false {
TCSLogWithMark("error saving tokens to keychain")
TCSLogErrorWithMark("error saving tokens to keychain")
}
ScheduleManager.shared.startCredentialCheck()

Expand Down
8 changes: 4 additions & 4 deletions XCreds/PasswordUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ class PasswordUtils: NSObject {
isValid = ((try records.first?.verifyPassword(auth)) != nil)
} catch {
let errorText = error.localizedDescription
TCSLogWithMark("ODError while trying to check for local user: \(errorText)")
TCSLogErrorWithMark("ODError while trying to check for local user: \(errorText)")
return false
}
return isValid
Expand Down Expand Up @@ -388,17 +388,17 @@ class PasswordUtils: NSObject {
let records = try query.resultsAllowingPartial(false) as! [ODRecord]

if records.count > 1 {
TCSLogWithMark("More than one local user found for name.")
TCSLogErrorWithMark("More than one local user found for name.")
throw DSQueryableErrors.multipleUsersFound
}
guard let record = records.first else {
TCSLogWithMark("No local user found. Passing on demobilizing allow login.")
TCSLogErrorWithMark("No local user found. Passing on demobilizing allow login.")
throw DSQueryableErrors.notLocalUser
}
TCSLogWithMark("Found local user: \(record)")
return record
} catch {
TCSLogWithMark("ODError while trying to check for local user: \(error.localizedDescription)")
TCSLogErrorWithMark("ODError while trying to check for local user: \(error.localizedDescription)")
throw error
}
}
Expand Down
4 changes: 3 additions & 1 deletion XCreds/TCSUnifiedLogger.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,12 @@ typedef enum : NSUInteger {
NS_ASSUME_NONNULL_BEGIN
#undef TCSLog
void TCSLog(NSString *str);

void TCSLogInfo(NSString *str);
void TCSLogError(NSString *string);

@interface TCSUnifiedLogger : NSObject
+ (TCSUnifiedLogger *)sharedLogger;
//-(void)setLogFilePath:(NSString *)logFilePath;
@property (strong, readwrite) NSURL *logFileURL;
@property (strong, readwrite) NSString *logFolderName;
@property (strong, readwrite) NSString *logFileName;
Expand Down
62 changes: 42 additions & 20 deletions XCreds/TCSUnifiedLogger.m
Original file line number Diff line number Diff line change
Expand Up @@ -22,48 +22,63 @@ @implementation TCSUnifiedLogger

void TCSLog(NSString *string)
{
[[TCSUnifiedLogger sharedLogger] logString:string level:LOGLEVELINFO];
[[TCSUnifiedLogger sharedLogger] logString:string level:LOGLEVELDEBUG];
}


void TCSLogInfo(NSString *string)
{
[[TCSUnifiedLogger sharedLogger] logString:string level:LOGLEVELINFO];
}
void TCSLogError(NSString *string)
{
[[TCSUnifiedLogger sharedLogger] logString:string level:LOGLEVELERROR];
}
+ (TCSUnifiedLogger *)sharedLogger
{
static TCSUnifiedLogger *sharedLogger;


if (sharedLogger !=nil){
return sharedLogger;
}
NSFileManager *fm = [NSFileManager defaultManager];


NSFileManager *fm = [NSFileManager defaultManager];
NSString *logFolderPath = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LogFolderPath"] stringByExpandingTildeInPath];
NSURL *logFolderURL;

//log file not defined.
if (!logFolderPath || logFolderPath.length == 0 || [fm fileExistsAtPath:logFolderPath] == NO) {
if (getuid() == 0) {
logFolderURL = [NSURL fileURLWithPath:@"/Library/Logs"];
//root
if (getuid() == 0 || getuid() == 92) { //root or security agent

if ([fm isWritableFileAtPath:logFolderURL.path] == NO || [fm fileExistsAtPath:logFolderURL.path]) {
logFolderURL = [NSURL fileURLWithPath:@"/var/log"];
if (![fm fileExistsAtPath:logFolderURL.path] || [fm isWritableFileAtPath:logFolderURL.path] == NO) {
logFolderURL = [NSURL fileURLWithPath:@"/tmp"];
}
}
logFolderURL = [NSURL fileURLWithPath:@"/tmp/xcreds"];


//not root
} else {
NSString *homePath = [[NSFileManager defaultManager] realHomeFolder];
logFolderURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Library/Logs", homePath]];
if (![fm fileExistsAtPath:logFolderURL.path]) {
logFolderURL = [NSURL fileURLWithPath:@"/tmp"];
char template[]="/tmp/xcreds-XXXXXX";

char *dirPath=mkdtemp(template);
if (dirPath) {
logFolderURL = [NSURL fileURLWithPath:[NSString stringWithUTF8String:dirPath]];
}

}
}
}

//define based on prefs.
else {
logFolderURL = [NSURL fileURLWithPath:[logFolderPath stringByExpandingTildeInPath]];
}

//get name from prefs. if not set, use generic.log
NSString *logFileName = [[NSUserDefaults standardUserDefaults] objectForKey:@"LogFileName"];
if (!logFileName || logFileName.length == 0) {
logFileName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"LogFileName"];

logFileName = [[[NSBundle bundleForClass:[self class]] infoDictionary] objectForKey:@"LogFileName"];
if (!logFileName || logFileName.length == 0) {
logFileName = @"generic.log";
}
Expand All @@ -72,12 +87,12 @@ + (TCSUnifiedLogger *)sharedLogger

if (sharedLogger == nil) {
sharedLogger = [[TCSUnifiedLogger alloc] init];
sharedLogger.lastLoggedDate = [NSDate distantPast];
}
sharedLogger.lastLoggedDate = [NSDate distantPast];

sharedLogger.logFileURL = [logFolderURL URLByAppendingPathComponent:logFileName];
if (![fm fileExistsAtPath:[sharedLogger.logFileURL.path stringByDeletingLastPathComponent]]) {
if ([fm createDirectoryAtPath:[sharedLogger.logFileURL.path stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil] == NO) {
}
sharedLogger.logFileURL = [logFolderURL URLByAppendingPathComponent:logFileName];
if (![fm fileExistsAtPath:[sharedLogger.logFileURL.path stringByDeletingLastPathComponent]]) {
if ([fm createDirectoryAtPath:[sharedLogger.logFileURL.path stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil] == NO) {
}
}
return sharedLogger;
Expand All @@ -90,6 +105,11 @@ - (void)os_log:(NSString *)inStr log:(NSString *)level type:(id)type{

- (void)logString:(NSString *)inStr level:(LogLevel)level
{

if (level==LOGLEVELDEBUG && [[NSUserDefaults standardUserDefaults] boolForKey:@"showDebug"]==NO){

return;
}
NSProcessInfo *processInfo = [NSProcessInfo processInfo];

NSString *processName = [processInfo processName];
Expand Down Expand Up @@ -129,4 +149,6 @@ - (void)logString:(NSString *)inStr level:(LogLevel)level
self.lastLine = inStr;
}



@end
10 changes: 5 additions & 5 deletions XCreds/TokenManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class TokenManager {
if let accessToken = creds.accessToken, accessToken.count>0{
TCSLogWithMark("Saving Access Token")
if keychainUtil.updatePassword(PrefKeys.accessToken.rawValue, pass: accessToken,shouldUpdateACL: setACL, keychainPassword:password) == false {
TCSLogWithMark("Error Updating Access Token")
TCSLogErrorWithMark("Error Updating Access Token")

return false
}
Expand All @@ -84,7 +84,7 @@ class TokenManager {
if let idToken = creds.idToken, idToken.count>0{
TCSLogWithMark("Saving idToken Token")
if keychainUtil.updatePassword(PrefKeys.idToken.rawValue, pass: idToken, shouldUpdateACL: setACL, keychainPassword:password) == false {
TCSLogWithMark("Error Updating idToken Token")
TCSLogErrorWithMark("Error Updating idToken Token")

return false
}
Expand All @@ -95,7 +95,7 @@ class TokenManager {
TCSLogWithMark("Saving refresh Token")

if keychainUtil.updatePassword(PrefKeys.refreshToken.rawValue, pass: refreshToken,shouldUpdateACL: setACL, keychainPassword:password) == false {
TCSLogWithMark("Error Updating refreshToken Token")
TCSLogErrorWithMark("Error Updating refreshToken Token")

return false
}
Expand All @@ -107,7 +107,7 @@ class TokenManager {
TCSLogWithMark("Saving cloud password")

if keychainUtil.updatePassword(PrefKeys.password.rawValue, pass: creds.password,shouldUpdateACL: setACL, keychainPassword:password) == false {
TCSLogWithMark("Error Updating password")
TCSLogErrorWithMark("Error Updating password")

return false
}
Expand Down Expand Up @@ -186,7 +186,7 @@ class TokenManager {

}
else {
TCSLogWithMark("got status code of \(response.statusCode):\(response)")
TCSLogErrorWithMark("got status code of \(response.statusCode):\(response)")
completion(false,false)

}
Expand Down
8 changes: 4 additions & 4 deletions XCreds/WebView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ extension WebViewController: WKNavigationDelegate {
self.password=passwords[0]
}
else {
TCSLogWithMark("password not set. Found: \(ids)")
TCSLogErrorWithMark("password not set. Found: \(ids)")
return

}
Expand Down Expand Up @@ -196,7 +196,7 @@ extension WebViewController: WKNavigationDelegate {
}

guard let pathURL = pathURL else {
TCSLogWithMark("get_pw.js not found")
TCSLogErrorWithMark("get_pw.js not found")
return
}

Expand All @@ -222,7 +222,7 @@ extension WebViewController: WKNavigationDelegate {
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
TCSLogWithMark(error.localizedDescription)
TCSLogErrorWithMark(error.localizedDescription)


}
Expand Down Expand Up @@ -280,7 +280,7 @@ extension WebViewController: WKNavigationDelegate {
extension WebViewController: OIDCLiteDelegate {

func authFailure(message: String) {
TCSLogWithMark("authFailure: \(message)")
TCSLogErrorWithMark("authFailure: \(message)")
NotificationCenter.default.post(name: Notification.Name("TCSTokensUpdated"), object: self, userInfo:[:])

}
Expand Down

0 comments on commit e92ffe9

Please sign in to comment.