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

Open
wants to merge 2 commits into
base: ethan/mandatory-helper
Choose a base branch
from
Open
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
102 changes: 102 additions & 0 deletions Coder-Desktop/Coder-Desktop/AppHelperXPCClient.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import Foundation
import NetworkExtension
import os
import VPNLib

// This is the client for the app to communicate with the privileged helper.
@objc final class HelperXPCClient: NSObject, @unchecked Sendable {
private var svc: CoderVPNService
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "HelperXPCClient")
private var connection: NSXPCConnection?

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

func connect() -> NSXPCConnection {
if let connection {
return connection
}

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()
}
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
}

// Establishes a connection to the Helper, so it can send messages back.
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()
}
}
}

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()
}
}
}
}

// These methods by the Helper over XPC
extension HelperXPCClient: AppXPCInterface {
func onPeerUpdate(_ diff: Data, reply: @escaping () -> Void) {
let reply = CompletionWrapper(reply)
Task { @MainActor in
svc.onExtensionPeerUpdate(diff)
reply()
}
}

func onProgress(stage: ProgressStage, downloadProgress: DownloadProgress?, reply: @escaping () -> Void) {
let reply = CompletionWrapper(reply)
Task { @MainActor in
svc.onProgress(stage: stage, downloadProgress: downloadProgress)
reply()
}
}
}
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: HelperXPCClient = .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
10 changes: 5 additions & 5 deletions Coder-Desktop/Coder-Desktop/Views/LoginForm.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ struct LoginForm: View {
return
}
// x.compare(y) is .orderedDescending if x > y
guard SignatureValidator.minimumCoderVersion.compare(semver, options: .numeric) != .orderedDescending else {
guard Validator.minimumCoderVersion.compare(semver, options: .numeric) != .orderedDescending else {
loginError = .outdatedCoderVersion
return
}
Expand Down Expand Up @@ -192,13 +192,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 All @@ -221,7 +221,7 @@ enum LoginError: Error {
"Invalid URL"
case .outdatedCoderVersion:
"""
The Coder deployment must be version \(SignatureValidator.minimumCoderVersion)
The Coder deployment must be version \(Validator.minimumCoderVersion)
or higher to use Coder Desktop.
"""
case let .failedAuth(err):
Expand Down
114 changes: 0 additions & 114 deletions Coder-Desktop/Coder-Desktop/XPCInterface.swift

This file was deleted.

Loading
Loading