diff --git a/Packages/OpenScreensKit/Sources/OpenScreensCore/Tailscale/TailscaleCommandLine.swift b/Packages/OpenScreensKit/Sources/OpenScreensCore/Tailscale/TailscaleCommandLine.swift index 9f6e659..eff95c9 100644 --- a/Packages/OpenScreensKit/Sources/OpenScreensCore/Tailscale/TailscaleCommandLine.swift +++ b/Packages/OpenScreensKit/Sources/OpenScreensCore/Tailscale/TailscaleCommandLine.swift @@ -23,8 +23,16 @@ enum TailscaleCommandLine { case couldNotStart(String) /// The tool was still running when its time was up, and was stopped. case timedOut + /// The tool printed more than it is allowed to, and was stopped. + case tooMuchOutput } + /// How much a tool may print, both streams together, before it is + /// stopped. Everything it prints is held in memory, so there has to be + /// an end to it; the status of a tailnet of ten thousand devices is + /// well within this. + static let outputLimit = 16 * 1024 * 1024 + /// How long the output streams may stay open after the tool has exited /// before what has been read is taken as everything. static let streamGracePeriod: DispatchTimeInterval = .seconds(2) @@ -39,17 +47,21 @@ enum TailscaleCommandLine { ["PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": NSHomeDirectory()] } - /// - Parameter environment: Everything the tool finds in its - /// environment. This process's own is never passed on. + /// - Parameters: + /// - environment: Everything the tool finds in its environment. This + /// process's own is never passed on. + /// - outputLimit: How many bytes the tool may print before it is + /// stopped and the run fails with ``Failure/tooMuchOutput``. static func run( _ executable: URL, arguments: [String] = [], environment: [String: String] = minimalEnvironment, + outputLimit: Int = TailscaleCommandLine.outputLimit, timeout: Duration ) async throws -> Output { let run = Run( executable: executable, arguments: arguments, environment: environment, - timeout: timeout) + outputLimit: outputLimit, timeout: timeout) return try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in run.start(continuation) @@ -69,6 +81,7 @@ extension TailscaleCommandLine { private let outputPipe = Pipe() private let errorPipe = Pipe() private let timeout: Duration + private let outputLimit: Int private var continuation: CheckedContinuation? private var timer: (any DispatchSourceTimer)? @@ -83,9 +96,11 @@ extension TailscaleCommandLine { executable: URL, arguments: [String], environment: [String: String], + outputLimit: Int, timeout: Duration ) { self.timeout = timeout + self.outputLimit = outputLimit process.executableURL = executable process.arguments = arguments process.environment = environment @@ -142,14 +157,14 @@ extension TailscaleCommandLine { /// either way the read returns at once. private func read(from handle: FileHandle, isErrorStream: Bool) { let chunk = (try? handle.read(upToCount: 1 << 16)) ?? Data() - lock.withLock { + let isTooMuch = lock.withLock { if !chunk.isEmpty { if isErrorStream { errorOutput.append(chunk) } else { output.append(chunk) } - return + return output.count + errorOutput.count > outputLimit } handle.readabilityHandler = nil if isErrorStream { @@ -158,6 +173,10 @@ extension TailscaleCommandLine { outputEnded = true } finishIfComplete() + return false + } + if isTooMuch { + stop(reportingFailure: Failure.tooMuchOutput) } } @@ -180,7 +199,8 @@ extension TailscaleCommandLine { } } - /// Ends the run early, for a timeout or a cancellation. + /// Ends the run early: it took too long, printed too much, or was + /// cancelled. private func stop(reportingFailure failure: any Error) { lock.withLock { guard continuation != nil else { return } diff --git a/Packages/OpenScreensKit/Sources/OpenScreensCore/Tailscale/TailscaleLocalSource.swift b/Packages/OpenScreensKit/Sources/OpenScreensCore/Tailscale/TailscaleLocalSource.swift index 93d1208..ca45f7a 100644 --- a/Packages/OpenScreensKit/Sources/OpenScreensCore/Tailscale/TailscaleLocalSource.swift +++ b/Packages/OpenScreensKit/Sources/OpenScreensCore/Tailscale/TailscaleLocalSource.swift @@ -98,14 +98,39 @@ struct TailscaleLocalStatus: Decodable { if let status = try? JSONDecoder().decode(TailscaleLocalStatus.self, from: output) { return try status.devices() } - // No status: the tool explained itself in words instead. - let errorText = String(decoding: errorOutput, as: UTF8.self) - let outputText = String(decoding: output, as: UTF8.self) + // No status: the tool explained itself in words instead. An + // explanation is a line or two, so only the beginning of what was + // printed is read as one — whatever it is and however much there is. + let errorText = explanation(in: errorOutput) + let outputText = explanation(in: output) let said = errorText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? outputText : errorText throw failure(exitCode: exitCode, message: said) } + /// How many bytes of what the tool printed are read as words when there + /// is no status in it. + static let explanationLimit = 4096 + + private static func explanation(in output: Data) -> String { + String(decoding: output.prefix(explanationLimit), as: UTF8.self) + } + + /// Text fit to be shown: without the characters that are not text at + /// all — bells and escapes, or the NULs of something that was never + /// words to begin with. + private static func shown(_ text: some StringProtocol) -> String { + var shown = String.UnicodeScalarView() + for scalar in text.unicodeScalars { + if scalar == "\t" { + shown.append(" ") + } else if scalar.properties.generalCategory != .control { + shown.append(scalar) + } + } + return String(shown) + } + /// The devices in the status, this device included and marked as such. func devices() throws -> [TailscaleDevice] { switch backendState { @@ -176,6 +201,7 @@ struct TailscaleLocalStatus: Decodable { /// Reads the plain-text complaint the tool prints when it cannot produce /// a status at all. static func failure(exitCode: Int32, message: String) -> TailscaleError { + let message = String(message.prefix(explanationLimit)) let lowered = message.lowercased() let saysLoggedOut = ["logged out", "not logged in", "needslogin"] if saysLoggedOut.contains(where: lowered.contains) { @@ -196,7 +222,7 @@ struct TailscaleLocalStatus: Decodable { let firstLine = message .split(whereSeparator: \.isNewline) - .map { $0.trimmingCharacters(in: .whitespaces) } + .map { shown($0).trimmingCharacters(in: .whitespaces) } .first { !$0.isEmpty } if let firstLine { return .commandFailed(String(firstLine.prefix(200))) @@ -334,6 +360,8 @@ public struct TailscaleLocalSource: TailscaleSource { timeout: timeout) } catch TailscaleCommandLine.Failure.timedOut { throw TailscaleError.timedOut + } catch TailscaleCommandLine.Failure.tooMuchOutput { + throw TailscaleError.commandFailed("The status it printed was too large to read.") } catch TailscaleCommandLine.Failure.couldNotStart(let reason) { throw TailscaleError.commandFailed(reason) } diff --git a/Packages/OpenScreensKit/Tests/OpenScreensCoreTests/TailscaleLocalSourceTests.swift b/Packages/OpenScreensKit/Tests/OpenScreensCoreTests/TailscaleLocalSourceTests.swift index 558b959..4f6f914 100644 --- a/Packages/OpenScreensKit/Tests/OpenScreensCoreTests/TailscaleLocalSourceTests.swift +++ b/Packages/OpenScreensKit/Tests/OpenScreensCoreTests/TailscaleLocalSourceTests.swift @@ -369,6 +369,54 @@ private func tailscaleListedDevices( exitCode: 1, message: String(repeating: "x", count: 5000)) #expect(failure == .commandFailed(String(repeating: "x", count: 200))) } + + /// What the tool printed is shown to the user as it is. Whatever stood + /// in for the tool may have printed anything. + @Test func charactersThatAreNotTextAreLeftOutOfAComplaint() { + let escape = "\u{1B}", bell = "\u{7}", null = "\u{0}" + let complaint = "\(escape)[31mfatal\(bell): tail\(null)scaled\tis b\u{8}roken\(escape)[0m\r\nsecond line" + #expect(throws: TailscaleError.commandFailed("[31mfatal: tailscaled is broken[0m")) { + try TailscaleLocalStatus.devices(exitCode: 1, output: Data(), errorOutput: Data(complaint.utf8)) + } + // Nothing but such characters is nothing said at all. + #expect(throws: TailscaleError.commandFailed("The status it printed could not be read.")) { + try TailscaleLocalStatus.devices(exitCode: 0, output: Data(count: 5000), errorOutput: Data()) + } + #expect(throws: TailscaleError.commandFailed("The command exited with code 9.")) { + try TailscaleLocalStatus.devices( + exitCode: 9, output: Data(), errorOutput: Data("\(escape)\(bell)\n\(null)\(null)\n".utf8)) + } + } + + /// An explanation is a line or two. However much was printed, only its + /// beginning is read as one. + @Test func onlyTheBeginningOfWhatWasPrintedIsReadAsAnExplanation() { + let limit = TailscaleLocalStatus.explanationLimit + #expect(limit >= 1024 && limit <= 65536) + + // Megabytes of something that is not a status. + var flood = Data(repeating: UInt8(ascii: "x"), count: 8 * 1024 * 1024) + #expect(throws: TailscaleError.commandFailed(String(repeating: "x", count: 200))) { + try TailscaleLocalStatus.devices(exitCode: 0, output: flood, errorOutput: Data()) + } + + // What decides is at the beginning. A phrase far into the output is + // not what the tool led with. + flood.append(Data("\nfailed to connect to local Tailscale service; is Tailscale running?\n".utf8)) + #expect(throws: TailscaleError.commandFailed(String(repeating: "x", count: 200))) { + try TailscaleLocalStatus.devices(exitCode: 1, output: Data(), errorOutput: flood) + } + let early = Data("is Tailscale running?\n".utf8) + flood + #expect(throws: TailscaleError.notRunning) { + try TailscaleLocalStatus.devices(exitCode: 1, output: Data(), errorOutput: early) + } + + // Cut where it may, the text is still text. + let multibyte = Data(String(repeating: "é", count: limit).utf8) + #expect(throws: TailscaleError.commandFailed(String(repeating: "é", count: 200))) { + try TailscaleLocalStatus.devices(exitCode: 1, output: Data(), errorOutput: multibyte) + } + } } #if os(macOS) @@ -561,6 +609,19 @@ private final class FakeTailscale { #expect(try await source(running: tool.executable).devices().count == 5) } + @Test func aToolThatPrintsWithoutEndIsStoppedAndReported() async throws { + // Gigabytes, if it were let. + let tool = try FakeTailscale( + output: Data(), + preamble: "exec /bin/dd if=/dev/zero bs=1048576 count=8192 2>/dev/null") + let clock = ContinuousClock() + let started = clock.now + await #expect(throws: TailscaleError.commandFailed("The status it printed was too large to read.")) { + try await source(running: tool.executable, timeout: .seconds(120)).devices() + } + #expect(clock.now - started < .seconds(30)) + } + @Test func theToolIsLookedForWhereTailscaleInstallsIt() { #expect(TailscaleLocalSource.commandLineToolPaths == [ "/Applications/Tailscale.app/Contents/MacOS/Tailscale", @@ -705,6 +766,41 @@ private final class FakeHangingTailscale { #expect(chosen == ["ONLY": "this"]) } + @Test func outputIsCollectedUpToALimitAndTheToolStoppedBeyondIt() async throws { + let megabyte = 1 << 20 + let printZeros = URL(fileURLWithPath: "/usr/bin/head") + + // Exactly what is allowed is collected whole. + let allowed = try await TailscaleCommandLine.run( + printZeros, arguments: ["-c", "\(megabyte)", "/dev/zero"], + outputLimit: megabyte, timeout: .seconds(30)) + #expect(allowed.standardOutput.count == megabyte) + #expect(allowed.exitCode == 0) + + // One byte more is too much. + await #expect(throws: TailscaleCommandLine.Failure.tooMuchOutput) { + try await TailscaleCommandLine.run( + printZeros, arguments: ["-c", "\(megabyte + 1)", "/dev/zero"], + outputLimit: megabyte, timeout: .seconds(30)) + } + + // A tool that never stops printing is stopped, long before its time + // is up — and it counts whichever of the two streams it prints to. + let clock = ContinuousClock() + let started = clock.now + for redirection in ["", " >&2"] { + await #expect(throws: TailscaleCommandLine.Failure.tooMuchOutput) { + try await TailscaleCommandLine.run( + URL(fileURLWithPath: "/bin/sh"), + arguments: ["-c", "exec /bin/cat /dev/zero\(redirection)"], + outputLimit: megabyte, timeout: .seconds(120)) + } + } + #expect(clock.now - started < .seconds(30)) + #expect(TailscaleCommandLine.outputLimit >= 4 * megabyte) + #expect(TailscaleCommandLine.outputLimit <= 64 * megabyte) + } + @Test func outputAndExitCodeAreCollected() async throws { let result = try await TailscaleCommandLine.run( URL(fileURLWithPath: "/bin/echo"), arguments: ["hello", "world"], timeout: .seconds(10))