-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSpeaker.swift
340 lines (303 loc) · 10.9 KB
/
Speaker.swift
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import Foundation
import os
import SwiftProtobuf
let newLine = 0x0A
let headerPreamble = "codervpn"
/// A message that has the `rpc` property for recording participation in a unary RPC.
protocol RPCMessage: Sendable {
var rpc: Vpn_RPC { get set }
/// Returns true if `rpc` has been explicitly set.
var hasRpc: Bool { get }
}
extension Vpn_TunnelMessage: RPCMessage {}
extension Vpn_ManagerMessage: RPCMessage {}
/// A role within the VPN protocol. Determines what message types are allowed to be sent and recieved.
enum ProtoRole: String {
case manager
case tunnel
}
/// A version of the VPN protocol that can be negotiated.
struct ProtoVersion: CustomStringConvertible, Equatable, Codable {
let major: Int
let minor: Int
var description: String { "\(major).\(minor)" }
init(_ major: Int, _ minor: Int) {
self.major = major
self.minor = minor
}
init(parse str: String) throws {
let parts = str.split(separator: ".").map { Int($0) }
if parts.count != 2 {
throw HandshakeError.invalidVersion(str)
}
guard let major = parts[0] else {
throw HandshakeError.invalidVersion(str)
}
guard let minor = parts[1] else {
throw HandshakeError.invalidVersion(str)
}
self.major = major
self.minor = minor
}
}
/// An actor that communicates using the VPN protocol
actor Speaker<SendMsg: RPCMessage & Message, RecvMsg: RPCMessage & Message> {
private let logger = Logger(subsystem: "com.coder.Coder-Desktop", category: "proto")
private let writeFD: FileHandle
private let readFD: FileHandle
private let dispatch: DispatchIO
private let queue: DispatchQueue = .global(qos: .utility)
private let sender: Sender<SendMsg>
private let receiver: Receiver<RecvMsg>
private let secretary = RPCSecretary<RecvMsg>()
let role: ProtoRole
/// Creates an instance that communicates over the provided file handles.
init(writeFD: FileHandle, readFD: FileHandle) {
self.writeFD = writeFD
self.readFD = readFD
sender = Sender(writeFD: writeFD)
dispatch = DispatchIO(
type: .stream,
fileDescriptor: readFD.fileDescriptor,
queue: queue,
cleanupHandler: { _ in
do {
try readFD.close()
} catch {
// TODO:
}
}
)
receiver = Receiver(dispatch: dispatch, queue: queue)
if SendMsg.self == Vpn_TunnelMessage.self {
role = .tunnel
} else {
role = .manager
}
}
/// Does the VPN Protocol handshake and validates the result
func handshake() async throws {
let hndsh = Handshaker(writeFD: writeFD, dispatch: dispatch, queue: queue, role: role)
// ignore the version for now because we know it can only be 1.0
try _ = await hndsh.handshake()
}
/// Send a unary RPC message and handle the response
func unaryRPC(_ req: SendMsg) async throws -> RecvMsg {
return try await withCheckedThrowingContinuation { continuation in
Task { [sender, secretary, logger] in
let msgID = await secretary.record(continuation: continuation)
var req = req
req.rpc = Vpn_RPC()
req.rpc.msgID = msgID
do {
logger.debug("sending RPC with msgID: \(msgID)")
try await sender.send(req)
} catch {
logger.warning("failed to send RPC with msgID: \(msgID): \(error)")
await secretary.erase(id: req.rpc.msgID)
continuation.resume(throwing: error)
}
logger.debug("sent RPC with msgID: \(msgID)")
}
}
}
func closeWrite() {
do {
try writeFD.close()
} catch {
logger.error("failed to close write file handle: \(error)")
}
}
func closeRead() {
do {
try readFD.close()
} catch {
logger.error("failed to close read file handle: \(error)")
}
}
enum IncomingMessage {
case message(RecvMsg)
case RPC(RPCRequest<SendMsg, RecvMsg>)
}
}
extension Speaker: AsyncSequence, AsyncIteratorProtocol {
typealias Element = IncomingMessage
public nonisolated func makeAsyncIterator() -> Speaker<SendMsg, RecvMsg> {
self
}
func next() async throws -> IncomingMessage? {
for try await msg in try await receiver.messages() {
guard msg.hasRpc else {
return .message(msg)
}
guard msg.rpc.msgID == 0 else {
return .RPC(RPCRequest<SendMsg, RecvMsg>(req: msg, sender: sender))
}
guard msg.rpc.responseTo == 0 else {
logger.debug("got RPC reply for msgID \(msg.rpc.responseTo)")
do throws(RPCError) {
try await self.secretary.route(reply: msg)
} catch {
logger.error(
"couldn't route RPC reply for \(msg.rpc.responseTo): \(error)")
}
continue
}
}
return nil
}
}
/// An actor performs the initial VPN protocol handshake and version negotiation.
actor Handshaker {
private let writeFD: FileHandle
private let dispatch: DispatchIO
private var theirData: Data = .init()
private let versions: [ProtoVersion]
private let role: ProtoRole
private var continuation: CheckedContinuation<Data, any Error>?
private let queue: DispatchQueue
init(writeFD: FileHandle, dispatch: DispatchIO, queue: DispatchQueue,
role: ProtoRole,
versions: [ProtoVersion] = [.init(1, 0)])
{
self.writeFD = writeFD
self.dispatch = dispatch
self.role = role
self.queue = queue
self.versions = versions
}
/// Performs the initial VPN protocol handshake, returning the negotiated `ProtoVersion` that we should use.
func handshake() async throws -> ProtoVersion {
// kick off the read async before we try to write, synchronously, so we don't deadlock, both
// waiting to write with nobody reading.
let readTask = Task {
try await withCheckedThrowingContinuation { cont in
self.continuation = cont
// send in a nil read to kick us off
self.handleRead(false, nil, 0)
}
}
let vStr = versions.map { $0.description }.joined(separator: ",")
let ours = String(format: "\(headerPreamble) \(role) \(vStr)\n")
try writeFD.write(contentsOf: ours.data(using: .utf8)!)
let theirData = try await readTask.value
guard let theirsString = String(bytes: theirData, encoding: .utf8) else {
throw HandshakeError.invalidHeader("<unparsable: \(theirData)")
}
do {
return try validateHeader(theirsString)
} catch {
writeFD.closeFile()
dispatch.close()
throw error
}
}
private func handleRead(_: Bool, _ data: DispatchData?, _ error: Int32) {
guard error == 0 else {
let errStrPtr = strerror(error)
let errStr = String(validatingCString: errStrPtr!)!
continuation?.resume(throwing: HandshakeError.readError(errStr))
return
}
if let d = data, !d.isEmpty {
guard d[0] != newLine else {
continuation?.resume(returning: theirData)
return
}
theirData.append(contentsOf: d)
}
// read another byte, one at a time, so we don't read beyond the header.
dispatch.read(offset: 0, length: 1, queue: queue, ioHandler: handleRead)
}
private func validateHeader(_ header: String) throws -> ProtoVersion {
let parts = header.split(separator: " ")
guard parts.count == 3 else {
throw HandshakeError.invalidHeader("expected 3 parts: \(header)")
}
guard parts[0] == headerPreamble else {
throw HandshakeError.invalidHeader("expected \(headerPreamble) but got \(parts[0])")
}
var expectedRole = ProtoRole.manager
if role == .manager {
expectedRole = .tunnel
}
guard parts[1] == expectedRole.rawValue else {
throw HandshakeError.wrongRole("expected \(expectedRole) but got \(parts[1])")
}
let theirVersions = try parts[2]
.split(separator: ",")
.map { try ProtoVersion(parse: String($0)) }
return try pickVersion(ours: versions, theirs: theirVersions)
}
}
func pickVersion(ours: [ProtoVersion], theirs: [ProtoVersion]) throws -> ProtoVersion {
for our in ours.reversed() {
for their in theirs.reversed() where our.major == their.major {
if our.minor < their.minor {
return our
}
return their
}
}
throw HandshakeError.unsupportedVersion(theirs)
}
enum HandshakeError: Error {
case readError(String)
case invalidHeader(String)
case wrongRole(String)
case invalidVersion(String)
case unsupportedVersion([ProtoVersion])
}
struct RPCRequest<SendMsg: RPCMessage & Message, RecvMsg: RPCMessage & Sendable>: Sendable {
let msg: RecvMsg
private let sender: Sender<SendMsg>
public init(req: RecvMsg, sender: Sender<SendMsg>) {
msg = req
self.sender = sender
}
func sendReply(_ reply: SendMsg) async throws {
var reply = reply
reply.rpc.responseTo = msg.rpc.msgID
try await sender.send(reply)
}
}
enum RPCError: Error {
case missingRPC
case notARequest
case notAResponse
case unknownResponseID(UInt64)
case shutdown
}
/// An actor to record outgoing RPCs and route their replies to the original sender
actor RPCSecretary<RecvMsg: RPCMessage & Sendable> {
private var continuations: [UInt64: CheckedContinuation<RecvMsg, Error>] = [:]
private var nextMsgID: UInt64 = 1
func record(continuation: CheckedContinuation<RecvMsg, Error>) -> UInt64 {
let id = nextMsgID
nextMsgID += 1
continuations[id] = continuation
return id
}
func erase(id: UInt64) {
continuations[id] = nil
}
func shutdown() {
for cont in continuations.values {
cont.resume(throwing: RPCError.shutdown)
}
continuations = [:]
}
func route(reply: RecvMsg) throws(RPCError) {
guard reply.hasRpc else {
throw RPCError.missingRPC
}
guard reply.rpc.responseTo != 0 else {
throw RPCError.notAResponse
}
guard let cont = continuations[reply.rpc.responseTo] else {
throw RPCError.unknownResponseID(reply.rpc.responseTo)
}
continuations[reply.rpc.responseTo] = nil
cont.resume(returning: reply)
}
}