-
Notifications
You must be signed in to change notification settings - Fork 1
/
AuxiliaryExecute+Spawn.txt
378 lines (326 loc) · 11.8 KB
/
AuxiliaryExecute+Spawn.txt
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//
// AuxiliaryExecute+Spawn.swift
//
// Created by Speedyfriend67 on 22.07.24
//
//
// AuxiliaryExecute+Spawn.swift
// AuxiliaryExecute
//
// Created by Lakr Aream on 2021/12/6.
//
import Foundation
import Darwin
@discardableResult
@_silgen_name("posix_spawn_file_actions_addchdir_np")
private func posix_spawn_file_actions_addchdir_np(
_ attr: UnsafeMutablePointer<posix_spawn_file_actions_t?>,
_ dir: UnsafePointer<Int8>
) -> Int32
@discardableResult
@_silgen_name("posix_spawnattr_set_persona_np")
private func posix_spawnattr_set_persona_np(
_ attr: UnsafeMutablePointer<posix_spawnattr_t?>,
_ persona_id: uid_t,
_ flags: UInt32
) -> Int32
@discardableResult
@_silgen_name("posix_spawnattr_set_persona_uid_np")
private func posix_spawnattr_set_persona_uid_np(
_ attr: UnsafeMutablePointer<posix_spawnattr_t?>,
_ persona_id: uid_t
) -> Int32
@discardableResult
@_silgen_name("posix_spawnattr_set_persona_gid_np")
private func posix_spawnattr_set_persona_gid_np(
_ attr: UnsafeMutablePointer<posix_spawnattr_t?>,
_ persona_id: gid_t
) -> Int32
private func WIFEXITED(_ status: Int32) -> Bool {
_WSTATUS(status) == 0
}
private func _WSTATUS(_ status: Int32) -> Int32 {
status & 0x7f
}
private func WIFSIGNALED(_ status: Int32) -> Bool {
(_WSTATUS(status) != 0) && (_WSTATUS(status) != 0x7f)
}
private func WEXITSTATUS(_ status: Int32) -> Int32 {
(status >> 8) & 0xff
}
private func WTERMSIG(_ status: Int32) -> Int32 {
status & 0x7f
}
private let POSIX_SPAWN_PERSONA_FLAGS_OVERRIDE = UInt32(1)
public struct PersonaOptions {
let uid: uid_t
let gid: gid_t
}
public struct ExecuteReceipt {
let terminationReason: TerminationReason
let pid: Int
let wait: Int
let error: ExecuteError?
let stdout: String
let stderr: String
enum TerminationReason {
case exit(Int32)
case uncaughtSignal(Int32)
}
enum ExecuteError: Error {
case openFilePipeFailed
case posixSpawnFailed
case timeout
}
static func failure(error: ExecuteError) -> ExecuteReceipt {
return ExecuteReceipt(
terminationReason: .exit(-1),
pid: -1,
wait: -1,
error: error,
stdout: "",
stderr: ""
)
}
}
public class AuxiliaryExecute {
private static let pipeControlQueue = DispatchQueue(label: "pipeControlQueue")
private static let processControlQueue = DispatchQueue(label: "processControlQueue")
private static let maxTimeoutValue: TimeInterval = 60.0
@discardableResult
static func spawn(
command: String,
args: [String] = [],
environment: [String: String] = [:],
workingDirectory: String? = nil,
personaOptions: PersonaOptions? = nil,
timeout: Double = 0,
setPid: ((pid_t) -> Void)? = nil,
output: ((String) -> Void)? = nil
) -> ExecuteReceipt {
let outputLock = NSLock()
let result = spawn(
command: command,
args: args,
environment: environment,
workingDirectory: workingDirectory,
personaOptions: personaOptions,
timeout: timeout,
setPid: setPid
) { str in
outputLock.lock()
output?(str)
outputLock.unlock()
} stderrBlock: { str in
outputLock.lock()
output?(str)
outputLock.unlock()
}
return result
}
@discardableResult
static func spawn(
command: String,
args: [String] = [],
environment: [String: String] = [:],
workingDirectory: String? = nil,
personaOptions: PersonaOptions? = nil,
timeout: Double = 0,
setPid: ((pid_t) -> Void)? = nil,
stdoutBlock: ((String) -> Void)? = nil,
stderrBlock: ((String) -> Void)? = nil
) -> ExecuteReceipt {
let sema = DispatchSemaphore(value: 0)
var receipt: ExecuteReceipt!
spawn(
command: command,
args: args,
environment: environment,
workingDirectory: workingDirectory,
personaOptions: personaOptions,
timeout: timeout,
setPid: setPid,
stdoutBlock: stdoutBlock,
stderrBlock: stderrBlock
) {
receipt = $0
sema.signal()
}
sema.wait()
return receipt
}
static func spawn(
command: String,
args: [String] = [],
environment: [String: String] = [:],
workingDirectory: String? = nil,
personaOptions: PersonaOptions? = nil,
timeout: Double = 0,
setPid: ((pid_t) -> Void)? = nil,
stdoutBlock: ((String) -> Void)? = nil,
stderrBlock: ((String) -> Void)? = nil,
completionBlock: ((ExecuteReceipt) -> Void)? = nil
) {
var attrs: posix_spawnattr_t?
posix_spawnattr_init(&attrs)
defer { posix_spawnattr_destroy(&attrs) }
if let personaOptions {
posix_spawnattr_set_persona_np(&attrs, 99, POSIX_SPAWN_PERSONA_FLAGS_OVERRIDE)
posix_spawnattr_set_persona_uid_np(&attrs, personaOptions.uid)
posix_spawnattr_set_persona_gid_np(&attrs, personaOptions.gid)
}
var pipestdout: [Int32] = [0, 0]
var pipestderr: [Int32] = [0, 0]
let bufsiz = Int(exactly: BUFSIZ) ?? 65535
pipe(&pipestdout)
pipe(&pipestderr)
guard fcntl(pipestdout[0], F_SETFL, O_NONBLOCK) != -1 else {
let receipt = ExecuteReceipt.failure(error: .openFilePipeFailed)
completionBlock?(receipt)
return
}
guard fcntl(pipestderr[0], F_SETFL, O_NONBLOCK) != -1 else {
let receipt = ExecuteReceipt.failure(error: .openFilePipeFailed)
completionBlock?(receipt)
return
}
var fileActions: posix_spawn_file_actions_t?
posix_spawn_file_actions_init(&fileActions)
posix_spawn_file_actions_addclose(&fileActions, pipestdout[0])
posix_spawn_file_actions_addclose(&fileActions, pipestderr[0])
posix_spawn_file_actions_adddup2(&fileActions, pipestdout[1], STDOUT_FILENO)
posix_spawn_file_actions_adddup2(&fileActions, pipestderr[1], STDERR_FILENO)
posix_spawn_file_actions_addclose(&fileActions, pipestdout[1])
posix_spawn_file_actions_addclose(&fileActions, pipestderr[1])
if let workingDirectory = workingDirectory {
workingDirectory.withCString { dir in
posix_spawn_file_actions_addchdir_np(&fileActions, dir)
}
}
defer { posix_spawn_file_actions_destroy(&fileActions) }
var realEnvironmentBuilder: [String] = []
var envBuilder = environment
var currentEnv = environ
while let rawStr = currentEnv.pointee {
defer { currentEnv += 1 }
let str = String(cString: rawStr)
let components = str.split(separator: "=", maxSplits: 1)
if components.count == 2 {
let key = String(components[0])
let value = String(components[1])
envBuilder[key] = value
}
}
for (key, value) in envBuilder {
realEnvironmentBuilder.append("\(key)=\(value)")
}
let realEnv: [UnsafeMutablePointer<CChar>?] = realEnvironmentBuilder.map { $0.withCString(strdup) }
defer { for case let env? in realEnv { free(env) } }
let args = [command] + args
let argv: [UnsafeMutablePointer<CChar>?] = args.map { $0.withCString(strdup) }
defer { for case let arg? in argv { free(arg) } }
var pid: pid_t = 0
let spawnStatus = posix_spawn(&pid, command, &fileActions, &attrs, argv + [nil], realEnv + [nil])
if spawnStatus != 0 {
let receipt = ExecuteReceipt.failure(error: .posixSpawnFailed)
completionBlock?(receipt)
return
}
setPid?(pid)
close(pipestdout[1])
close(pipestderr[1])
var stdoutStr = ""
var stderrStr = ""
let stdoutSource = DispatchSource.makeReadSource(fileDescriptor: pipestdout[0], queue: pipeControlQueue)
let stderrSource = DispatchSource.makeReadSource(fileDescriptor: pipestderr[0], queue: pipeControlQueue)
let stdoutSem = DispatchSemaphore(value: 0)
let stderrSem = DispatchSemaphore(value: 0)
stdoutSource.setCancelHandler {
close(pipestdout[0])
stdoutSem.signal()
}
stderrSource.setCancelHandler {
close(pipestderr[0])
stderrSem.signal()
}
stdoutSource.setEventHandler {
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufsiz)
defer { buffer.deallocate() }
let bytesRead = read(pipestdout[0], buffer, bufsiz)
guard bytesRead > 0 else {
if bytesRead == -1, errno == EAGAIN {
return
}
stdoutSource.cancel()
return
}
let array = Array(UnsafeBufferPointer(start: buffer, count: bytesRead)) + [UInt8(0)]
array.withUnsafeBufferPointer { ptr in
let str = String(cString: unsafeBitCast(ptr.baseAddress, to: UnsafePointer<CChar>.self))
stdoutStr += str
stdoutBlock?(str)
}
}
stderrSource.setEventHandler {
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufsiz)
defer { buffer.deallocate() }
let bytesRead = read(pipestderr[0], buffer, bufsiz)
guard bytesRead > 0 else {
if bytesRead == -1, errno == EAGAIN {
return
}
stderrSource.cancel()
return
}
let array = Array(UnsafeBufferPointer(start: buffer, count: bytesRead)) + [UInt8(0)]
array.withUnsafeBufferPointer { ptr in
let str = String(cString: unsafeBitCast(ptr.baseAddress, to: UnsafePointer<CChar>.self))
stderrStr += str
stderrBlock?(str)
}
}
stdoutSource.resume()
stderrSource.resume()
let realTimeout = timeout > 0 ? timeout : maxTimeoutValue
let wallTimeout = DispatchTime.now() + (
TimeInterval(exactly: realTimeout) ?? maxTimeoutValue
)
var status: Int32 = 0
var wait: pid_t = 0
var isTimeout = false
let timerSource = DispatchSource.makeTimerSource(flags: [], queue: processControlQueue)
timerSource.setEventHandler {
isTimeout = true
kill(pid, SIGKILL)
}
let processSource = DispatchSource.makeProcessSource(identifier: pid, eventMask: .exit, queue: processControlQueue)
processSource.setEventHandler {
wait = waitpid(pid, &status, 0)
processSource.cancel()
timerSource.cancel()
stdoutSem.wait()
stderrSem.wait()
let terminationReason: ExecuteReceipt.TerminationReason
if WIFSIGNALED(status) {
let signal = WTERMSIG(status)
terminationReason = .uncaughtSignal(signal)
} else {
assert(WIFEXITED(status))
let exitCode = WEXITSTATUS(status)
terminationReason = .exit(exitCode)
}
let receipt = ExecuteReceipt(
terminationReason: terminationReason,
pid: Int(exactly: pid) ?? -1,
wait: Int(exactly: wait) ?? -1,
error: isTimeout ? .timeout : nil,
stdout: stdoutStr,
stderr: stderrStr
)
completionBlock?(receipt)
}
processSource.resume()
timerSource.schedule(deadline: wallTimeout)
timerSource.resume()
}
}