Skip to content

chore: run coder connect networking from launchdaemon #203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: ethan/mandatory-helper
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions Coder-Desktop/Coder-Desktop/HelperService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,8 @@ extension CoderVPNService {
func setupHelper() async {
refreshHelperState()
switch helperState {
case .uninstalled, .failed:
await installHelper()
case .installed:
uninstallHelper()
case .uninstalled, .failed, .installed:
await uninstallHelper()
await installHelper()
case .requiresApproval, .installing:
break
Expand Down Expand Up @@ -63,10 +61,10 @@ extension CoderVPNService {
helperState = .failed(.unknown(lastUnknownError?.localizedDescription ?? "Unknown"))
}

private func uninstallHelper() {
private func uninstallHelper() async {
let daemon = SMAppService.daemon(plistName: plistName)
do {
try daemon.unregister()
try await daemon.unregister()
} catch let error as NSError {
helperState = .failed(.init(error: error))
} catch {
Expand Down
16 changes: 9 additions & 7 deletions Coder-Desktop/Coder-Desktop/VPN/VPNService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ enum VPNServiceError: Error, Equatable {
@MainActor
final class CoderVPNService: NSObject, VPNService {
var logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "vpn")
lazy var xpc: VPNXPCInterface = .init(vpn: self)
lazy var xpc: AppXPCListener = .init(vpn: self)

@Published var tunnelState: VPNServiceState = .disabled {
didSet {
Expand Down Expand Up @@ -158,10 +158,10 @@ final class CoderVPNService: NSObject, VPNService {
}
}

func onExtensionPeerUpdate(_ data: Data) {
func onExtensionPeerUpdate(_ diff: Data) {
logger.info("network extension peer update")
do {
let msg = try Vpn_PeerUpdate(serializedBytes: data)
let msg = try Vpn_PeerUpdate(serializedBytes: diff)
debugPrint(msg)
applyPeerUpdate(with: msg)
} catch {
Expand Down Expand Up @@ -219,16 +219,18 @@ extension CoderVPNService {
break
// Non-connecting -> Connecting: Establish XPC
case (_, .connecting):
xpc.connect()
xpc.ping()
// Detached to run ASAP
// TODO: Switch to `Task.immediate` once stable
Task.detached { try? await self.xpc.ping() }
tunnelState = .connecting
// Non-connected -> Connected:
// - Retrieve Peers
// - Run `onStart` closure
case (_, .connected):
onStart?()
xpc.connect()
xpc.getPeerState()
// Detached to run ASAP
// TODO: Switch to `Task.immediate` once stable
Task.detached { try? await self.xpc.getPeerState() }
tunnelState = .connected
// Any -> Reasserting
case (_, .reasserting):
Expand Down
6 changes: 3 additions & 3 deletions Coder-Desktop/Coder-Desktop/Views/LoginForm.swift
Original file line number Diff line number Diff line change
Expand Up @@ -190,13 +190,13 @@ struct LoginForm: View {
@discardableResult
func validateURL(_ url: String) throws(LoginError) -> URL {
guard let url = URL(string: url) else {
throw LoginError.invalidURL
throw .invalidURL
}
guard url.scheme == "https" else {
throw LoginError.httpsRequired
throw .httpsRequired
}
guard url.host != nil else {
throw LoginError.noHost
throw .noHost
}
return url
}
Expand Down
148 changes: 67 additions & 81 deletions Coder-Desktop/Coder-Desktop/XPCInterface.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,112 +3,98 @@ import NetworkExtension
import os
import VPNLib

@objc final class VPNXPCInterface: NSObject, VPNXPCClientCallbackProtocol, @unchecked Sendable {
@objc final class AppXPCListener: NSObject, AppXPCInterface, @unchecked Sendable {
private var svc: CoderVPNService
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "VPNXPCInterface")
private var xpc: VPNXPCProtocol?
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AppXPCListener")
private var connection: NSXPCConnection?

init(vpn: CoderVPNService) {
svc = vpn
super.init()
}

func connect() {
logger.debug("VPN xpc connect called")
guard xpc == nil else {
logger.debug("VPN xpc already exists")
return
func connect() -> NSXPCConnection {
if let connection {
return connection
}
let networkExtDict = Bundle.main.object(forInfoDictionaryKey: "NetworkExtension") as? [String: Any]
let machServiceName = networkExtDict?["NEMachServiceName"] as? String
let xpcConn = NSXPCConnection(machServiceName: machServiceName!)
xpcConn.remoteObjectInterface = NSXPCInterface(with: VPNXPCProtocol.self)
xpcConn.exportedInterface = NSXPCInterface(with: VPNXPCClientCallbackProtocol.self)
guard let proxy = xpcConn.remoteObjectProxy as? VPNXPCProtocol else {
fatalError("invalid xpc cast")
}
xpc = proxy

logger.debug("connecting to machServiceName: \(machServiceName!)")

xpcConn.exportedObject = self
xpcConn.invalidationHandler = { [logger] in
Task { @MainActor in
logger.error("VPN XPC connection invalidated.")
self.xpc = nil
self.connect()
}
}
xpcConn.interruptionHandler = { [logger] in
Task { @MainActor in
logger.error("VPN XPC connection interrupted.")
self.xpc = nil
self.connect()
}
let connection = NSXPCConnection(
machServiceName: helperAppMachServiceName,
options: .privileged
)
connection.remoteObjectInterface = NSXPCInterface(with: HelperAppXPCInterface.self)
connection.exportedInterface = NSXPCInterface(with: AppXPCInterface.self)
connection.exportedObject = self
connection.invalidationHandler = {
self.logger.error("XPC connection invalidated")
self.connection = nil
_ = self.connect()
}
xpcConn.resume()
}

func ping() {
xpc?.ping {
Task { @MainActor in
self.logger.info("Connected to NE over XPC")
}
connection.interruptionHandler = {
self.logger.error("XPC connection interrupted")
self.connection = nil
_ = self.connect()
}
logger.info("connecting to \(helperAppMachServiceName)")
connection.resume()
self.connection = connection
return connection
}

func getPeerState() {
xpc?.getPeerState { data in
Task { @MainActor in
self.svc.onExtensionPeerState(data)
}
func onPeerUpdate(_ diff: Data, reply: @escaping () -> Void) {
let reply = CompletionWrapper(reply)
Task { @MainActor in
svc.onExtensionPeerUpdate(diff)
reply()
}
}

func onPeerUpdate(_ data: Data) {
func onProgress(stage: ProgressStage, downloadProgress: DownloadProgress?, reply: @escaping () -> Void) {
let reply = CompletionWrapper(reply)
Task { @MainActor in
svc.onExtensionPeerUpdate(data)
svc.onProgress(stage: stage, downloadProgress: downloadProgress)
reply()
}
}
}

func onProgress(stage: ProgressStage, downloadProgress: DownloadProgress?) {
Task { @MainActor in
svc.onProgress(stage: stage, downloadProgress: downloadProgress)
// These methods are called to request updatess from the Helper.
extension AppXPCListener {
func ping() async throws {
let conn = connect()
return try await withCheckedThrowingContinuation { continuation in
guard let proxy = conn.remoteObjectProxyWithErrorHandler({ err in
self.logger.error("failed to connect to HelperXPC \(err.localizedDescription, privacy: .public)")
continuation.resume(throwing: err)
}) as? HelperAppXPCInterface else {
self.logger.error("failed to get proxy for HelperXPC")
continuation.resume(throwing: XPCError.wrongProxyType)
return
}
proxy.ping {
self.logger.info("Connected to Helper over XPC")
continuation.resume()
}
}
}

// The NE has verified the dylib and knows better than Gatekeeper
func removeQuarantine(path: String, reply: @escaping (Bool) -> Void) {
let reply = CallbackWrapper(reply)
Task { @MainActor in
let prompt = """
Coder Desktop wants to execute code downloaded from \
\(svc.serverAddress ?? "the Coder deployment"). The code has been \
verified to be signed by Coder.
"""
let source = """
do shell script "xattr -d com.apple.quarantine \(path)" \
with prompt "\(prompt)" \
with administrator privileges
"""
let success = await withCheckedContinuation { continuation in
guard let script = NSAppleScript(source: source) else {
continuation.resume(returning: false)
return
}
// Run on a background thread
Task.detached {
var error: NSDictionary?
script.executeAndReturnError(&error)
if let error {
self.logger.error("AppleScript error: \(error)")
continuation.resume(returning: false)
} else {
continuation.resume(returning: true)
}
func getPeerState() async throws {
let conn = connect()
return try await withCheckedThrowingContinuation { continuation in
guard let proxy = conn.remoteObjectProxyWithErrorHandler({ err in
self.logger.error("failed to connect to HelperXPC \(err.localizedDescription, privacy: .public)")
continuation.resume(throwing: err)
}) as? HelperAppXPCInterface else {
self.logger.error("failed to get proxy for HelperXPC")
continuation.resume(throwing: XPCError.wrongProxyType)
return
}
proxy.getPeerState { data in
Task { @MainActor in
self.svc.onExtensionPeerState(data)
}
continuation.resume()
}
reply(success)
}
}
}
Loading
Loading