tethering-hider/TetheringHider/Services/SystemCommandService.swift

63 lines
2.1 KiB
Swift

//
// TetheringHiderApp.swift
//
//
// Created by Jesús David Chapman Vélez on 12/08/26.
//
import Foundation
enum SystemCommandError: LocalizedError {
case executionFailed(String)
case userCancelledAuth
case scriptError(String)
var errorDescription: String? {
switch self {
case .executionFailed(let reason):
return "Command failed: \(reason)"
case .userCancelledAuth:
return "Administrator authentication was cancelled."
case .scriptError(let detail):
return "Script error: \(detail)"
}
}
}
struct SystemCommandService: Sendable {
/// Sets IPv4 TTL, IPv6 Hop Limit, and flushes system DNS cache with administrator privileges.
func setTTL(_ value: Int) async throws {
let command = "sysctl -w net.inet.ip.ttl=\(value) && sysctl -w net.inet6.ip6.hlim=\(value) && dscacheutil -flushcache && killall -HUP mDNSResponder"
try await executeWithAdminPrivileges(command)
}
/// Resets IPv4 TTL and IPv6 Hop Limit to default (64) and flushes DNS cache.
func resetTTL() async throws {
try await setTTL(64)
}
/// Executes a shell command with administrator privileges via NSAppleScript
@MainActor
private func executeWithAdminPrivileges(_ command: String) async throws {
let scriptSource = "do shell script \"\(command)\" with administrator privileges"
guard let script = NSAppleScript(source: scriptSource) else {
throw SystemCommandError.scriptError("Failed to create AppleScript.")
}
var errorDict: NSDictionary?
script.executeAndReturnError(&errorDict)
if let error = errorDict {
let errorNumber = error[NSAppleScript.errorNumber] as? Int ?? -1
let errorMessage = error[NSAppleScript.errorMessage] as? String ?? "Unknown error"
if errorNumber == -128 {
throw SystemCommandError.userCancelledAuth
}
throw SystemCommandError.executionFailed(errorMessage)
}
}
}