macOS 用户态进程间的通信实现

孙康

macOS 内核与用户态进程的通信前面已经讲解过了,用户态进程间通信较为简单,Apple 官方推荐使用 XPC 机制。XPC 有底层的 C API,也有封装后的上层的 objc 和 swift API,可以实现像调用自身进程的接口一样调用对端的暴露接口。这里以 swift 为例说明 XPC 的代码实现。开源项目 NuwaStone 用户态进程间通信均基于 XPC 实现,更多代码细节可参考该项目。

对外接口及类定义

使用 XPC 需新建两个协议,作为自身进程和对端进程的通信接口,然后新建一个处理 XPC 连接请求的类,注意需继承 NSObject,以便实现 XPC 系统调用所需的代理接口。注意,为了方便 XPCConnection 类是自身进程与对端进程共用的,但部分方法是不能共用的,详细见注释。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 客户端进程协议
@objc protocol ClientXPCProtocol {
}

// 服务端进程协议
@objc protocol ServerXPCProtocol {
func connectResponse(_ handler: @escaping (Bool) -> Void)
}

// 连接请求处理类
class XPCConnection: NSObject {
static let shared = XPCConnection()
var listener: NSXPCListener?
// 连接处理对象
var connection: NSXPCConnection?

private func getMachServiceName(from bundle: Bundle) -> String {
let clientKeys = bundle.object(forInfoDictionaryKey: ClientName) as? [String: Any]
let machServiceName = clientKeys?[MachServiceKey] as? String
return machServiceName ?? ""
}

// 仅服务端进程调用
func startListener() {
let newListener = NSXPCListener(machServiceName: "your service name")
newListener.delegate = self
newListener.resume()
listener = newListener
Logger(.Info, "Start XPC listener successfully.")
}

// 仅客户端进程调用
func connectToServer(bundle: Bundle, delegate: ClientXPCProtocol, handler: @escaping (Bool) -> Void) {
guard connection == nil else {
Logger(.Info, "Client already connected.")
handler(true)
return
}
guard getMachServiceName(from: bundle) == ClientBundle else {
handler(false)
return
}

let newConnection = NSXPCConnection(machServiceName: DaemonBundle)
newConnection.exportedObject = delegate
newConnection.exportedInterface = NSXPCInterface(with: ClientXPCProtocol.self)
newConnection.remoteObjectInterface = NSXPCInterface(with: DaemonXPCProtocol.self)
connection = newConnection
newConnection.resume()

let proxy = newConnection.remoteObjectProxyWithErrorHandler { error in
Logger(.Error, "Failed to connect with error [\(error)]")
self.connection?.invalidate()
self.connection = nil
handler(false)
} as? DaemonXPCProtocol

proxy?.connectResponse(handler)
}
}

XPC 的代码实现是较为简单的,startListener函数首先需创建连接所用的 Mach 端口,网络资源在 Mac 内核抽象为了 Mach 端口资源,然后设置处理连接请求的代理为自身类,后面需编写请求处理代码以校验对端并建立连接。connectToServer函数首先判断是否连接已建立,然后简单校验了一下 APP 包名。创建连接对象时需设置自身暴露接口和远程调用接口,设置完成后所调用的connectResponse为连接测试函数。在调用远程接口前均需获取remoteObjectProxy远程对象代理,这里需进行错误处理,如果出错则表示连接断开。

XPC 连接请求系统调用代理接口

startListener函数中设置处理连接请求的代理为自身类,所以类需要实现代理方法,代理方法的实现很简单,仅需实现下面一种方法。函数内的实现看起来与connectToServer差不多,不过多了错误处理机制。建立连接前可以进行签名校验以增强安全性。这里的invalidationHandler被系统调用时表明连接正常断开,interruptionHandler被系统调用时表明连接意外断开,如果有断开重连要求可以加在这里。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
extension XPCConnection: NSXPCListenerDelegate {
func listener(_ listener: NSXPCListener, shouldAcceptNewConnection newConnection: NSXPCConnection) -> Bool {
newConnection.exportedObject = self
newConnection.exportedInterface = NSXPCInterface(with: DaemonXPCProtocol.self)
newConnection.remoteObjectInterface = NSXPCInterface(with: ClientXPCProtocol.self)
newConnection.invalidationHandler = {
self.connection = nil
Logger(.Info, "Client disconnected.")
}
newConnection.interruptionHandler = {
self.connection = nil
Logger(.Info, "Client interrupted.")
}

connection = newConnection
newConnection.resume()
return true
}

服务端对外暴露接口

暴露接口根据自己的项目需要自行设计实现就好,但要注意这些接口是无返回值的,毕竟是远程调用,基本也不会需要返回值。这里使用@escaping修饰代码块,表示代码块的调用可能在函数返回后。

1
2
3
4
5
6
extension XPCConnection: DaemonXPCProtocol {
func connectResponse(_ handler: @escaping (Bool) -> Void) {
Logger(.Info, "Client connected.")
handler(true)
}
}
  • Title: macOS 用户态进程间的通信实现
  • Author: 孙康
  • Created at : 2023-06-23 13:12:57
  • Updated at : 2023-08-31 19:56:20
  • Link: https://conradsun.github.io/2023/06b3e3d734.html
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments