Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Term9// File : Packages/SPTermKit/Sources/PTYProcess/PTYProcess.swift10// Module : PTYProcess11// Repository : https://git.spboucher.ai/sp-term12// Created : 2026-11-1713// Last Modified : 2026-11-1714//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Darwin88import Foundation8990/// How a child process attached to a pseudo-terminal ended.91public enum PTYExitStatus: Sendable, Equatable {92 /// Normal exit with the given status code.93 case exited(code: Int32)94 /// Killed by a signal.95 case signaled(signal: Int32)9697 /// Shell-style numeric code (128 + signal for signaled processes).98 public var shellCode: Int32 {99 switch self {100 case .exited(let code): return code101 case .signaled(let signal): return 128 + signal102 }103 }104}105106public enum PTYError: Error, Equatable, CustomStringConvertible {107 case openptyFailed(errno: Int32)108 case spawnFailed(errno: Int32, executable: String)109 case invalidConfiguration(String)110111 public var description: String {112 switch self {113 case .openptyFailed(let e): return "openpty failed: \(String(cString: strerror(e)))"114 case .spawnFailed(let e, let exe): return "cannot launch \(exe): \(String(cString: strerror(e)))"115 case .invalidConfiguration(let why): return "invalid launch configuration: \(why)"116 }117 }118}119120/// Everything needed to start a program on a new pseudo-terminal.121public struct PTYLaunchConfiguration: Sendable, Equatable {122 /// Absolute path of the executable.123 public var executable: String124 /// Full argv, including argv[0] (a leading "-" marks a login shell).125 public var arguments: [String]126 /// Complete environment of the child (nothing is inherited implicitly).127 public var environment: [String: String]128 /// Initial working directory; `nil` keeps the parent's.129 public var workingDirectory: String?130 public var columns: UInt16131 public var rows: UInt16132133 public init(executable: String, arguments: [String], environment: [String: String],134 workingDirectory: String? = nil, columns: UInt16 = 80, rows: UInt16 = 24) {135 self.executable = executable136 self.arguments = arguments137 self.environment = environment138 self.workingDirectory = workingDirectory139 self.columns = columns140 self.rows = rows141 }142}143144/// A child process running on its own pseudo-terminal.145///146/// The child is created with `forkpty` (new session, slave side as controlling terminal on147/// fds 0/1/2) and immediately replaced with `posix_spawn(POSIX_SPAWN_SETEXEC)`, which resets148/// signal dispositions and closes every other descriptor (`POSIX_SPAWN_CLOEXEC_DEFAULT`).149/// Job control, `SIGWINCH`, `Ctrl+C`/`Ctrl+Z` therefore behave exactly as in any terminal.150///151/// Output and exit callbacks are delivered on a private serial queue, output always before exit.152public final class PTYProcess: @unchecked Sendable {153 public let pid: pid_t154 /// Path of the slave device (e.g. `/dev/ttys012`).155 public let ttyName: String156157 private let masterFD: Int32158 private let queue: DispatchQueue159 private var readSource: DispatchSourceRead?160 private var writeSource: DispatchSourceWrite?161 private var processSource: DispatchSourceProcess?162 private var pendingWrites: [UInt8] = []163 private var finished = false164 private var masterClosed = false165 private let onOutput: @Sendable (ArraySlice<UInt8>) -> Void166 private let onExit: @Sendable (PTYExitStatus) -> Void167 private let stateLock = NSLock()168 private var _exitStatus: PTYExitStatus?169170 /// Exit status once the child has been reaped, `nil` while it runs.171 public var exitStatus: PTYExitStatus? { stateLock.withLock { _exitStatus } }172 public var isRunning: Bool { exitStatus == nil }173174 /// Spawns the program. Throws if the PTY cannot be created or the executable cannot be launched.175 public init(_ configuration: PTYLaunchConfiguration,176 onOutput: @escaping @Sendable (ArraySlice<UInt8>) -> Void,177 onExit: @escaping @Sendable (PTYExitStatus) -> Void) throws {178 guard configuration.executable.hasPrefix("/") else {179 throw PTYError.invalidConfiguration("executable must be an absolute path")180 }181 guard !configuration.arguments.isEmpty else {182 throw PTYError.invalidConfiguration("argv must contain at least argv[0]")183 }184 self.onOutput = onOutput185 self.onExit = onExit186 self.queue = DispatchQueue(label: "ai.spboucher.spterm.pty", qos: .userInteractive)187188 var master: Int32 = -1189 var size = winsize(ws_row: max(1, configuration.rows), ws_col: max(1, configuration.columns),190 ws_xpixel: 0, ws_ypixel: 0)191 var term = PTYProcess.defaultTermios()192193 // Everything the child needs is prepared before forking: between fork and exec only194 // async-signal-safe calls on these pre-built C values are made.195 var attr: posix_spawnattr_t?196 posix_spawnattr_init(&attr)197 defer { posix_spawnattr_destroy(&attr) }198 var allSignals = sigset_t()199 sigfillset(&allSignals)200 var noSignals = sigset_t()201 sigemptyset(&noSignals)202 posix_spawnattr_setsigdefault(&attr, &allSignals)203 posix_spawnattr_setsigmask(&attr, &noSignals)204 // SETEXEC turns posix_spawn into an exec of the current (forked) process, which gives us205 // CLOEXEC_DEFAULT: the program inherits no descriptor of the app except its terminal.206 let flags = POSIX_SPAWN_SETEXEC | POSIX_SPAWN_CLOEXEC_DEFAULT | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK207 posix_spawnattr_setflags(&attr, Int16(flags))208209 var actions: posix_spawn_file_actions_t?210 posix_spawn_file_actions_init(&actions)211 defer { posix_spawn_file_actions_destroy(&actions) }212 for fd in Int32(0)...2 { posix_spawn_file_actions_addinherit_np(&actions, fd) }213 if let cwd = configuration.workingDirectory, !cwd.isEmpty {214 posix_spawn_file_actions_addchdir_np(&actions, cwd)215 }216217 let argv: [UnsafeMutablePointer<CChar>?] = configuration.arguments.map { strdup($0) } + [nil]218 let envp: [UnsafeMutablePointer<CChar>?] = configuration.environment219 .map { strdup("\($0.key)=\($0.value)") } + [nil]220 let executable = strdup(configuration.executable)221 defer {222 argv.forEach { free($0) }223 envp.forEach { free($0) }224 free(executable)225 }226 // Close-on-exec pipe: stays silent when exec succeeds, carries errno when it fails.227 var statusPipe: [Int32] = [-1, -1]228 guard pipe(&statusPipe) == 0 else { throw PTYError.openptyFailed(errno: errno) }229 _ = fcntl(statusPipe[0], F_SETFD, FD_CLOEXEC)230 _ = fcntl(statusPipe[1], F_SETFD, FD_CLOEXEC)231 let statusWrite = statusPipe[1]232233 // forkpty: new session, the slave becomes the controlling terminal (TIOCSCTTY) on 0/1/2.234 let child = argv.withUnsafeBufferPointer { argvPtr in235 envp.withUnsafeBufferPointer { envpPtr -> pid_t in236 let pid = forkpty(&master, nil, &term, &size)237 if pid == 0 {238 var code = posix_spawn(nil, executable, &actions, &attr, argvPtr.baseAddress, envpPtr.baseAddress)239 _ = Darwin.write(statusWrite, &code, MemoryLayout<Int32>.size)240 _exit(127)241 }242 return pid243 }244 }245 let forkError = errno246 close(statusPipe[1])247 guard child > 0 else {248 close(statusPipe[0])249 throw PTYError.openptyFailed(errno: forkError)250 }251 var execError: Int32 = 0252 var got: Int253 repeat {254 got = withUnsafeMutableBytes(of: &execError) { read(statusPipe[0], $0.baseAddress, $0.count) }255 } while got < 0 && errno == EINTR256 close(statusPipe[0])257 if got == MemoryLayout<Int32>.size {258 var status: Int32 = 0259 waitpid(child, &status, 0)260 close(master)261 throw PTYError.spawnFailed(errno: execError, executable: configuration.executable)262 }263 self.ttyName = String(cString: ptsname(master))264 self.pid = child265 self.masterFD = master266 _ = fcntl(master, F_SETFL, fcntl(master, F_GETFL) | O_NONBLOCK)267 _ = fcntl(master, F_SETFD, FD_CLOEXEC)268 startSources()269 }270271 deinit {272 // Never leave a zombie or a leaked descriptor behind.273 readSource?.cancel()274 writeSource?.cancel()275 processSource?.cancel()276 if !masterClosed { close(masterFD) }277 if _exitStatus == nil {278 kill(pid, SIGHUP)279 let reaper = pid280 DispatchQueue.global().async { var s: Int32 = 0; waitpid(reaper, &s, 0) }281 }282 }283284 private func startSources() {285 let read = DispatchSource.makeReadSource(fileDescriptor: masterFD, queue: queue)286 read.setEventHandler { [weak self] in287 guard let self, !self.drainOutput() else { return }288 // Every descriptor of the slave side is closed: nothing more will ever arrive.289 // Stop watching (an EOF descriptor is permanently "readable") and wait for the exit.290 self.readSource?.cancel()291 self.readSource = nil292 self.pollForExit(attempt: 0)293 }294 readSource = read295 read.resume()296297 let proc = DispatchSource.makeProcessSource(identifier: pid, eventMask: .exit, queue: queue)298 proc.setEventHandler { [weak self] in self?.handleExit() }299 // The child may exit before the kernel event is registered (tiny programs): an exit that300 // happened earlier produces no event, so look once more right after registration.301 proc.setRegistrationHandler { [weak self] in self?.handleExit() }302 processSource = proc303 proc.resume()304 }305306 /// Reads everything currently available. Returns `false` once the slave side is closed.307 @discardableResult308 private func drainOutput() -> Bool {309 var buffer = [UInt8](repeating: 0, count: 65_536)310 while true {311 let n = buffer.withUnsafeMutableBytes { read(masterFD, $0.baseAddress, $0.count) }312 if n > 0 {313 onOutput(buffer[0..<n])314 if n < buffer.count { return true }315 } else if n == 0 {316 return false317 } else {318 if errno == EINTR { continue }319 return errno == EAGAIN320 }321 }322 }323324 /// After end-of-file the child is normally about to exit; poll briefly in case the exit event325 /// is delayed or the child only closed its terminal.326 private func pollForExit(attempt: Int) {327 guard !finished else { return }328 handleExit()329 guard !finished, attempt < 200 else { return }330 queue.asyncAfter(deadline: .now() + .milliseconds(attempt < 20 ? 5 : 50)) { [weak self] in331 self?.pollForExit(attempt: attempt + 1)332 }333 }334335 private func handleExit() {336 guard !finished else { return }337 var status: Int32 = 0338 let r = waitpid(pid, &status, WNOHANG)339 if r == pid { finish(status: status) }340 }341342 private func finish(status: Int32) {343 guard !finished else { return }344 finished = true345 drainOutput()346 readSource?.cancel(); readSource = nil347 writeSource?.cancel(); writeSource = nil348 processSource?.cancel(); processSource = nil349 if !masterClosed { close(masterFD); masterClosed = true }350 let low = status & 0x7f351 let result: PTYExitStatus = low == 0 ? .exited(code: (status >> 8) & 0xff) : .signaled(signal: low)352 stateLock.withLock { _exitStatus = result }353 onExit(result)354 }355356 /// Sane cooked-mode settings (the values of <sys/ttydefaults.h>) with UTF-8 aware erase.357 static func defaultTermios() -> termios {358 var term = termios()359 term.c_iflag = tcflag_t(BRKINT | ICRNL | IMAXBEL | IXON | IXANY | IUTF8)360 term.c_oflag = tcflag_t(OPOST | ONLCR)361 term.c_cflag = tcflag_t(CREAD | CS8 | HUPCL)362 term.c_lflag = tcflag_t(ECHO | ICANON | ISIG | IEXTEN | ECHOE | ECHOKE | ECHOCTL)363 cfsetspeed(&term, speed_t(B38400))364 withUnsafeMutableBytes(of: &term.c_cc) { cc in365 for index in 0..<cc.count { cc[index] = 0xff } // _POSIX_VDISABLE366 cc[Int(VEOF)] = 0x04; cc[Int(VERASE)] = 0x7f; cc[Int(VWERASE)] = 0x17; cc[Int(VKILL)] = 0x15367 cc[Int(VREPRINT)] = 0x12; cc[Int(VINTR)] = 0x03; cc[Int(VQUIT)] = 0x1c; cc[Int(VSUSP)] = 0x1a368 cc[Int(VDSUSP)] = 0x19; cc[Int(VSTART)] = 0x11; cc[Int(VSTOP)] = 0x13; cc[Int(VLNEXT)] = 0x16369 cc[Int(VDISCARD)] = 0x0f; cc[Int(VSTATUS)] = 0x14; cc[Int(VMIN)] = 1; cc[Int(VTIME)] = 0370 }371 return term372 }373374 // MARK: Input375376 /// Queues bytes for the child. Never blocks the caller; ordering is preserved.377 public func write(_ bytes: some Sequence<UInt8>) {378 let data = Array(bytes)379 guard !data.isEmpty else { return }380 queue.async { [weak self] in381 guard let self, !self.finished else { return }382 self.pendingWrites.append(contentsOf: data)383 self.flushWrites()384 }385 }386387 public func write(_ text: String) { write(Array(text.utf8)) }388389 private func flushWrites() {390 while !pendingWrites.isEmpty {391 let n = pendingWrites.withUnsafeBytes { Darwin.write(masterFD, $0.baseAddress, $0.count) }392 if n > 0 {393 pendingWrites.removeFirst(n)394 } else if n < 0 && errno == EINTR {395 continue396 } else if n < 0 && errno == EAGAIN {397 armWriteSource()398 return399 } else {400 pendingWrites.removeAll()401 return402 }403 }404 // Drop the source instead of suspending it: releasing a suspended source is a fatal error.405 writeSource?.cancel()406 writeSource = nil407 }408409 private func armWriteSource() {410 guard writeSource == nil else { return }411 let source = DispatchSource.makeWriteSource(fileDescriptor: masterFD, queue: queue)412 source.setEventHandler { [weak self] in self?.flushWrites() }413 writeSource = source414 source.resume()415 }416417 // MARK: Terminal control418419 /// Updates the window size; the kernel sends `SIGWINCH` to the foreground process group.420 public func resize(columns: UInt16, rows: UInt16, pixelWidth: UInt16 = 0, pixelHeight: UInt16 = 0) {421 queue.async { [weak self] in422 guard let self, !self.finished else { return }423 var size = winsize(ws_row: max(1, rows), ws_col: max(1, columns),424 ws_xpixel: pixelWidth, ws_ypixel: pixelHeight)425 _ = ioctl(self.masterFD, TIOCSWINSZ, &size)426 }427 }428429 /// Current window size as stored in the kernel, or `nil` after exit.430 public func windowSize() -> (columns: UInt16, rows: UInt16)? {431 queue.sync {432 guard !finished else { return nil }433 var size = winsize()434 guard ioctl(masterFD, TIOCGWINSZ, &size) == 0 else { return nil }435 return (size.ws_col, size.ws_row)436 }437 }438439 /// Process group currently in the foreground of the terminal (the shell when idle).440 public func foregroundProcessGroup() -> pid_t? {441 queue.sync {442 guard !finished else { return nil }443 let group = tcgetpgrp(masterFD)444 return group > 0 ? group : nil445 }446 }447448 /// `true` when something other than the shell itself owns the terminal (a command is running).449 public var hasForegroundJob: Bool {450 guard let group = foregroundProcessGroup() else { return false }451 return group != pid452 }453454 public func send(signal: Int32) {455 guard isRunning else { return }456 kill(pid, signal)457 }458459 /// Asks the session to end the way closing a terminal window does (`SIGHUP` to the session),460 /// then forces termination if it is still alive after `grace` seconds.461 public func terminate(grace: TimeInterval = 1.5) {462 guard isRunning else { return }463 let target = pid464 kill(-target, SIGHUP)465 kill(target, SIGHUP)466 queue.asyncAfter(deadline: .now() + grace) { [weak self] in467 guard let self, !self.finished else { return }468 kill(-target, SIGKILL)469 kill(target, SIGKILL)470 }471 }472}473