Skip to content

Commit

Permalink
FlyingSocks: fix partial reads
Browse files Browse the repository at this point in the history
Fixes: #10
  • Loading branch information
lhoward committed Nov 28, 2024
1 parent ef6087e commit 6aa80af
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions Sources/SwiftOCA/OCP.1/Backend/Ocp1FlyingSocksConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public class Ocp1FlyingSocksConnection: Ocp1Connection {
try self.init(socketAddress: sockaddr_un.unix(path: path), options: options)
}

private func withMappedError<T: Sendable>(
fileprivate func withMappedError<T: Sendable>(
_ block: (_ asyncSocket: AsyncSocket) async throws
-> T
) async throws -> T {
Expand All @@ -166,12 +166,6 @@ public class Ocp1FlyingSocksConnection: Ocp1Connection {
}
}

override public func read(_ length: Int) async throws -> Data {
try await withMappedError { socket in
try await Data(socket.read(atMost: length))
}
}

override public func write(_ data: Data) async throws -> Int {
try await withMappedError { socket in
try await socket.write(data)
Expand All @@ -195,6 +189,19 @@ public final class Ocp1FlyingSocksStreamConnection: Ocp1FlyingSocksConnection {

override var socketType: SocketType { .stream }

override public func read(_ length: Int) async throws -> Data {
var data = Data()

try await withMappedError { socket in
while data.count < length {
let receivedData = try await Data(socket.read(atMost: length - data.count))
data += receivedData
}
}

return data
}

override func setSocketOptions(_ socket: Socket) throws {
if deviceAddress.family == AF_INET {
try socket.setValue(true, for: BoolSocketOption(name: TCP_NODELAY), level: CInt(IPPROTO_TCP))
Expand All @@ -213,11 +220,13 @@ public final class Ocp1FlyingSocksDatagramConnection: Ocp1FlyingSocksConnection

override public var isDatagram: Bool { true }

override var socketType: SocketType { .datagram }

override public func read(_ length: Int) async throws -> Data {
try await super.read(Ocp1MaximumDatagramPduSize)
try await withMappedError { socket in
try await Data(socket.read(atMost: Ocp1MaximumDatagramPduSize))
}
}

override var socketType: SocketType { .datagram }
}

func deviceAddressToString(_ deviceAddress: any SocketAddress) -> String {
Expand Down

0 comments on commit 6aa80af

Please sign in to comment.