Skip to content

Commit db57f32

Browse files
authored
Correctly resize ByteBuffers (#150)
Motivation: In two different places in this module we "reserve" space by moving the writer index forward. This isn't the correct way to do that, and it's a bit of a needless performance optimization. Instead, just write a zero in that location and come back to it. Modifications: - Replace unmotivated writer index move with a write. - Add tests. Result: Fewer crashes
1 parent dcc089f commit db57f32

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

Sources/NIOSSH/ByteBuffer+SSH.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ extension ByteBuffer {
205205
mutating func writeCompositeSSHString(_ compositeFunction: (inout ByteBuffer) throws -> Int) rethrows -> Int {
206206
// Reserve 4 bytes for the length.
207207
let originalWriterIndex = self.writerIndex
208-
self.moveWriterIndex(forwardBy: 4)
208+
self.writeInteger(UInt32(0))
209209

210210
var writtenLength: Int
211211
do {

Sources/NIOSSH/SSHPacketSerializer.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ extension ByteBuffer {
7373
/// byte[m] mac (Message Authentication Code - MAC); m = mac_length
7474

7575
/// payload
76-
self.moveWriterIndex(forwardBy: 5)
76+
self.writeMultipleIntegers(UInt32(0), UInt8(0))
7777
let messageLength = self.writeSSHMessage(message)
7878

7979
// Depending on on whether packet length is encrypted, padding should reflect that

Tests/NIOSSHTests/ByteBuffer+SSHTests.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,33 @@ final class ByteBufferSSHTests: XCTestCase {
361361

362362
XCTAssertNoThrow(XCTAssertNotNil(try buffer.readSSHHostKey()))
363363
}
364+
365+
func testCompositeStringDoesTheRightThingWithBB() throws {
366+
var buffer = ByteBuffer()
367+
XCTAssertEqual(buffer.capacity, 0)
368+
369+
buffer.writeCompositeSSHString {
370+
$0.writeInteger(UInt64(9))
371+
}
372+
let writtenBytes = buffer.readBytes(length: buffer.readableBytes)
373+
XCTAssertEqual(
374+
writtenBytes,
375+
[0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 9]
376+
)
377+
}
378+
379+
func testWriteSSHPacketDoesTheRightThingWithBB() throws {
380+
var buffer = ByteBuffer()
381+
XCTAssertEqual(buffer.capacity, 0)
382+
383+
buffer.writeSSHPacket(message: .version("Tests_v1.0"), lengthEncrypted: false, blockSize: 8)
384+
385+
let writtenBytes = buffer.readBytes(length: 5)
386+
XCTAssertEqual(
387+
writtenBytes,
388+
[0, 0, 0, 24, 11]
389+
)
390+
}
364391
}
365392

366393
extension ByteBuffer {

0 commit comments

Comments
 (0)