Skip to content

Commit 6aa80af

Browse files
committed
FlyingSocks: fix partial reads
Fixes: #10
1 parent ef6087e commit 6aa80af

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

Sources/SwiftOCA/OCP.1/Backend/Ocp1FlyingSocksConnection.swift

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ public class Ocp1FlyingSocksConnection: Ocp1Connection {
151151
try self.init(socketAddress: sockaddr_un.unix(path: path), options: options)
152152
}
153153

154-
private func withMappedError<T: Sendable>(
154+
fileprivate func withMappedError<T: Sendable>(
155155
_ block: (_ asyncSocket: AsyncSocket) async throws
156156
-> T
157157
) async throws -> T {
@@ -166,12 +166,6 @@ public class Ocp1FlyingSocksConnection: Ocp1Connection {
166166
}
167167
}
168168

169-
override public func read(_ length: Int) async throws -> Data {
170-
try await withMappedError { socket in
171-
try await Data(socket.read(atMost: length))
172-
}
173-
}
174-
175169
override public func write(_ data: Data) async throws -> Int {
176170
try await withMappedError { socket in
177171
try await socket.write(data)
@@ -195,6 +189,19 @@ public final class Ocp1FlyingSocksStreamConnection: Ocp1FlyingSocksConnection {
195189

196190
override var socketType: SocketType { .stream }
197191

192+
override public func read(_ length: Int) async throws -> Data {
193+
var data = Data()
194+
195+
try await withMappedError { socket in
196+
while data.count < length {
197+
let receivedData = try await Data(socket.read(atMost: length - data.count))
198+
data += receivedData
199+
}
200+
}
201+
202+
return data
203+
}
204+
198205
override func setSocketOptions(_ socket: Socket) throws {
199206
if deviceAddress.family == AF_INET {
200207
try socket.setValue(true, for: BoolSocketOption(name: TCP_NODELAY), level: CInt(IPPROTO_TCP))
@@ -213,11 +220,13 @@ public final class Ocp1FlyingSocksDatagramConnection: Ocp1FlyingSocksConnection
213220

214221
override public var isDatagram: Bool { true }
215222

223+
override var socketType: SocketType { .datagram }
224+
216225
override public func read(_ length: Int) async throws -> Data {
217-
try await super.read(Ocp1MaximumDatagramPduSize)
226+
try await withMappedError { socket in
227+
try await Data(socket.read(atMost: Ocp1MaximumDatagramPduSize))
228+
}
218229
}
219-
220-
override var socketType: SocketType { .datagram }
221230
}
222231

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

0 commit comments

Comments
 (0)