Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions GhosttyTabs.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
734F49D37E543DD01C2F4FEF /* NotificationAndMenuBarTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2C075029771815DD5DA1332 /* NotificationAndMenuBarTests.swift */; };
84E00D47E4584162AE53BC8D /* xterm-ghostty in Resources */ = {isa = PBXBuildFile; fileRef = B2E7294509CC42FE9191870E /* xterm-ghostty */; };
8C4BBF2DEF6DF93F395A9EE7 /* TerminalControllerSocketSecurityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 491751CE2321474474F27DCF /* TerminalControllerSocketSecurityTests.swift */; };
9C1BEA3D2E6F49709A71C020 /* TerminalControllerSocketWriteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C1BEA3D2E6F49709A71C021 /* TerminalControllerSocketWriteTests.swift */; };
A5001001 /* cmuxApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001011 /* cmuxApp.swift */; };
A50019A0 /* SettingsNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50019A1 /* SettingsNavigation.swift */; };
A50019B0 /* SettingsSearchAliases.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50019B1 /* SettingsSearchAliases.swift */; };
Expand Down Expand Up @@ -326,6 +327,7 @@
42092CDB2109E250F7F2A76E /* TabManagerUnitTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TabManagerUnitTests.swift; sourceTree = "<group>"; };
43430FA5929121E2EAAB3091 /* AuthEnvironment.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AuthEnvironment.swift; sourceTree = "<group>"; };
491751CE2321474474F27DCF /* TerminalControllerSocketSecurityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalControllerSocketSecurityTests.swift; sourceTree = "<group>"; };
9C1BEA3D2E6F49709A71C021 /* TerminalControllerSocketWriteTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TerminalControllerSocketWriteTests.swift; sourceTree = "<group>"; };
58C7B1B978620BE162CC057E /* BrowserPanelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserPanelTests.swift; sourceTree = "<group>"; };
5B1EA8948C5F126FE63CFB4E /* AuthSettingsStore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AuthSettingsStore.swift; sourceTree = "<group>"; };
6083A7DAD962E287FC2FFE94 /* ShortcutAndCommandPaletteTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutAndCommandPaletteTests.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -862,6 +864,7 @@
1D301919B10F22B8708E8883 /* WorkspaceManualUnreadTests.swift */,
EE0171AF1F49F7547191CEE5 /* SidebarWidthPolicyTests.swift */,
491751CE2321474474F27DCF /* TerminalControllerSocketSecurityTests.swift */,
9C1BEA3D2E6F49709A71C021 /* TerminalControllerSocketWriteTests.swift */,
A5A5A504A1B2C3D4E5F60718 /* TerminalNotificationQueueTests.swift */,
A5C41104A1B2C3D4E5F60718 /* TerminalNotificationCallerTests.swift */,
A5D41204A1B2C3D4E5F60718 /* CLINotifyProcessIntegrationRegressionTests.swift */,
Expand Down Expand Up @@ -1330,6 +1333,7 @@
0F2C25F9170130F8DC09DD1B /* WorkspaceManualUnreadTests.swift in Sources */,
CA39C0304FE351A21C372429 /* SidebarWidthPolicyTests.swift in Sources */,
8C4BBF2DEF6DF93F395A9EE7 /* TerminalControllerSocketSecurityTests.swift in Sources */,
9C1BEA3D2E6F49709A71C020 /* TerminalControllerSocketWriteTests.swift in Sources */,
A5A5A503A1B2C3D4E5F60718 /* TerminalNotificationQueueTests.swift in Sources */,
A5C41103A1B2C3D4E5F60718 /* TerminalNotificationCallerTests.swift in Sources */,
A5D41203A1B2C3D4E5F60718 /* CLINotifyProcessIntegrationRegressionTests.swift in Sources */,
Expand Down
113 changes: 89 additions & 24 deletions Sources/TerminalController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ class TerminalController {
private nonisolated static let socketProbePollTimeoutMs: Int32 = 100
private nonisolated static let socketProbePollAttempts = 3
private nonisolated static let socketProbePollRetryBackoffUs: useconds_t = 50_000
private nonisolated static let socketClientWriteTimeout: TimeInterval = 5
private nonisolated static let socketListenerFailureCaptureCooldown: TimeInterval = 60
private nonisolated static let socketListenerFailureCaptureLock = NSLock()
private nonisolated(unsafe) static var socketListenerFailureLastCapturedAt: [String: Date] = [:]
Expand Down Expand Up @@ -866,6 +867,52 @@ class TerminalController {
}
}

private nonisolated static func configureSocketSendTimeout(_ fd: Int32, timeout: TimeInterval) -> Int32? {
var socketTimeout = makeSocketTimeout(timeout)
let result = withUnsafePointer(to: &socketTimeout) { ptr in
setsockopt(
fd,
SOL_SOCKET,
SO_SNDTIMEO,
ptr,
socklen_t(MemoryLayout<timeval>.size)
)
}
return result == 0 ? nil : errno
}

private nonisolated static func configureNoSigPipe(_ fd: Int32) -> Int32? {
#if os(macOS)
var noSigPipe: Int32 = 1
let result = withUnsafePointer(to: &noSigPipe) { ptr in
setsockopt(
fd,
SOL_SOCKET,
SO_NOSIGPIPE,
ptr,
socklen_t(MemoryLayout<Int32>.size)
)
}
return result == 0 ? nil : errno
#else
_ = fd
return nil
#endif
}

private nonisolated static func configureAcceptedClientSocket(_ fd: Int32) -> (stage: String, errnoCode: Int32)? {
if let errnoCode = configureBlocking(fd) {
return ("accept_client_configure_blocking", errnoCode)
}
if let errnoCode = configureSocketSendTimeout(fd, timeout: socketClientWriteTimeout) {
return ("accept_client_configure_send_timeout", errnoCode)
}
if let errnoCode = configureNoSigPipe(fd) {
return ("accept_client_configure_no_sigpipe", errnoCode)
}
return nil
}
Comment on lines +903 to +914

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Missing receive timeout on accepted client sockets

configureAcceptedClientSocket now applies SO_SNDTIMEO to guard against slow-reading clients, but it doesn't apply SO_RCVTIMEO. The read() call in handleClient (line 1882) will block indefinitely if a client connects and then goes silent without closing the socket — stalling that handler thread for the connection's lifetime. The code comment at line 1864 acknowledges connect-only probes, but a client that sends a partial command and then stalls would hold the thread forever. Consider adding SO_RCVTIMEO alongside SO_SNDTIMEO to fully bound the accepted-socket lifecycle.


private nonisolated static func bindListenerSocket(_ socket: Int32, path: String) -> SocketBindAttemptResult {
if let errnoCode = ensureSocketParentDirectoryExists(path: path) {
return .failure(path: path, stage: "create_directory", errnoCode: errnoCode)
Expand Down Expand Up @@ -1147,18 +1194,7 @@ class TerminalController {
defer { close(fd) }
Self.configureSocketTimeouts(fd, timeout: timeout)

#if os(macOS)
var noSigPipe: Int32 = 1
_ = withUnsafePointer(to: &noSigPipe) { ptr in
setsockopt(
fd,
SOL_SOCKET,
SO_NOSIGPIPE,
ptr,
socklen_t(MemoryLayout<Int32>.size)
)
}
#endif
_ = Self.configureNoSigPipe(fd)

var addr = sockaddr_un()
memset(&addr, 0, MemoryLayout<sockaddr_un>.size)
Expand Down Expand Up @@ -1298,13 +1334,36 @@ class TerminalController {
}
}

private nonisolated func writeSocketResponse(_ response: String, to socket: Int32) {
let payload = response + "\n"
payload.withCString { ptr in
_ = write(socket, ptr, strlen(ptr))
nonisolated static func writeAllToSocket(_ data: Data, to socket: Int32) -> Bool {
data.withUnsafeBytes { rawBuffer in
guard let baseAddress = rawBuffer.baseAddress else { return true }
var offset = 0

while offset < rawBuffer.count {
let written = write(
socket,
baseAddress.advanced(by: offset),
rawBuffer.count - offset
)
if written > 0 {
offset += written
continue
}
if written < 0, errno == EINTR {
continue
}
return false
}

return true
}
}

private nonisolated func writeSocketResponse(_ response: String, to socket: Int32) -> Bool {
let payload = response + "\n"
return Self.writeAllToSocket(Data(payload.utf8), to: socket)
}

private nonisolated func passwordAuthRequiredResponse(for command: String) -> String {
let message = "Authentication required. Send auth <password> first."
guard command.hasPrefix("{"),
Expand Down Expand Up @@ -1572,13 +1631,13 @@ class TerminalController {
acceptSourceConsecutiveFailures = 0
}

if let errnoCode = Self.configureBlocking(clientSocket) {
if let failure = Self.configureAcceptedClientSocket(clientSocket) {
sentryBreadcrumb(
"socket.listener.client_config.failed",
category: "socket",
data: socketListenerEventData(
stage: "accept_client_configure_blocking",
errnoCode: errnoCode,
stage: failure.stage,
errnoCode: failure.errnoCode,
extra: ["generation": generation]
)
)
Expand Down Expand Up @@ -1790,8 +1849,10 @@ class TerminalController {
let pid = peerPid ?? getPeerPid(socket)
if let pid {
guard isDescendant(pid) else {
let msg = "ERROR: Access denied — only processes started inside cmux can connect\n"
msg.withCString { ptr in _ = write(socket, ptr, strlen(ptr)) }
_ = writeSocketResponse(
"ERROR: Access denied — only processes started inside cmux can connect",
to: socket
)
return
}
}
Expand All @@ -1804,8 +1865,10 @@ class TerminalController {
// with no data is harmless.
if pid == nil {
guard peerHasSameUID(socket) else {
let msg = "ERROR: Unable to verify client process\n"
msg.withCString { ptr in _ = write(socket, ptr, strlen(ptr)) }
_ = writeSocketResponse(
"ERROR: Unable to verify client process",
to: socket
)
return
}
}
Expand All @@ -1830,7 +1893,9 @@ class TerminalController {

let result = processSocketLine(trimmed, authenticated: authenticated)
authenticated = result.authenticated
writeSocketResponse(result.response, to: socket)
guard writeSocketResponse(result.response, to: socket) else {
return
}
}
}
}
Expand Down
79 changes: 79 additions & 0 deletions cmuxTests/TerminalControllerSocketWriteTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import XCTest
import Darwin
import Foundation

#if canImport(cmux_DEV)
@testable import cmux_DEV
#elseif canImport(cmux)
@testable import cmux
#endif

@MainActor
final class TerminalControllerSocketWriteTests: XCTestCase {
func testSocketWriteAllWritesCompletePayload() throws {
let sockets = try makeSocketPair()
defer {
Darwin.close(sockets.reader)
Darwin.close(sockets.writer)
}

let payload = Data("PONG\n".utf8)
XCTAssertTrue(TerminalController.writeAllToSocket(payload, to: sockets.writer))

var buffer = [UInt8](repeating: 0, count: payload.count)
let count = Darwin.read(sockets.reader, &buffer, buffer.count)
XCTAssertEqual(count, payload.count)
XCTAssertEqual(count > 0 ? Data(buffer.prefix(count)) : Data(), payload)
}

func testSocketWriteAllReturnsWhenPeerDoesNotRead() throws {
let sockets = try makeSocketPair()
defer {
Darwin.close(sockets.reader)
Darwin.close(sockets.writer)
}
try configureSendTimeout(sockets.writer, timeout: 0.05)

let payload = Data(repeating: 0x78, count: 8 * 1024 * 1024)
let startedAt = Date()
XCTAssertFalse(TerminalController.writeAllToSocket(payload, to: sockets.writer))
XCTAssertLessThan(Date().timeIntervalSince(startedAt), 2.0)
}

private nonisolated func makeSocketPair() throws -> (reader: Int32, writer: Int32) {
var fds = [Int32](repeating: -1, count: 2)
let result = fds.withUnsafeMutableBufferPointer { buffer in
Darwin.socketpair(AF_UNIX, SOCK_STREAM, 0, buffer.baseAddress)
}
guard result == 0 else {
throw posixError("socketpair(AF_UNIX)")
}
return (reader: fds[0], writer: fds[1])
}

private nonisolated func configureSendTimeout(_ fd: Int32, timeout: TimeInterval) throws {
let seconds = floor(max(timeout, 0))
let microseconds = (max(timeout, 0) - seconds) * 1_000_000
var socketTimeout = timeval(tv_sec: Int(seconds), tv_usec: Int32(microseconds.rounded()))
let result = withUnsafePointer(to: &socketTimeout) { ptr in
Darwin.setsockopt(
fd,
SOL_SOCKET,
SO_SNDTIMEO,
ptr,
socklen_t(MemoryLayout<timeval>.size)
)
}
guard result == 0 else {
throw posixError("setsockopt(SO_SNDTIMEO)")
}
}

private nonisolated func posixError(_ operation: String) -> NSError {
NSError(
domain: NSPOSIXErrorDomain,
code: Int(errno),
userInfo: [NSLocalizedDescriptionKey: "\(operation) failed: \(String(cString: strerror(errno)))"]
)
}
}