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
7 changes: 4 additions & 3 deletions async_postgres/pg_protocol.nim
Original file line number Diff line number Diff line change
Expand Up @@ -329,17 +329,18 @@ proc decodeInt64*(buf: openArray[byte], offset: int): int64 =

proc decodeCString*(buf: openArray[byte], offset: int): (string, int) =
## Decode a null-terminated string at the given offset. Returns (string, bytes consumed).
if offset > buf.len:
if offset >= buf.len:
raise newException(ProtocolError, "decodeCString: offset past end of buffer")
var i = offset
while i < buf.len and buf[i] != 0:
inc i
if i >= buf.len:
raise newException(ProtocolError, "decodeCString: missing null terminator")
let slen = i - offset
var s = newString(slen)
if slen > 0:
copyMem(addr s[0], unsafeAddr buf[offset], slen)
if i < buf.len:
inc i # skip null terminator
inc i # skip null terminator
result = (s, i - offset)

# Frontend message encoding
Expand Down
7 changes: 5 additions & 2 deletions async_postgres/pg_replication.nim
Original file line number Diff line number Diff line change
Expand Up @@ -230,15 +230,18 @@ proc currentPgTimestamp*(): int64 =

proc decodeCStringAt(buf: openArray[byte], offset: int): (string, int) =
## Decode a null-terminated string at offset. Returns (string, next offset).
if offset >= buf.len:
raise newException(ProtocolError, "decodeCStringAt: offset past end of buffer")
var i = offset
while i < buf.len and buf[i] != 0:
inc i
if i >= buf.len:
raise newException(ProtocolError, "decodeCStringAt: missing null terminator")
let slen = i - offset
var s = newString(slen)
if slen > 0:
copyMem(addr s[0], unsafeAddr buf[offset], slen)
if i < buf.len:
inc i # skip null
inc i # skip null
(s, i)

proc decodeTuple(buf: openArray[byte], offset: int): (seq[TupleField], int) =
Expand Down
10 changes: 7 additions & 3 deletions tests/test_protocol.nim
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,8 @@ suite "Byte helpers":

test "decodeCString at end of buffer":
let buf = @[byte('a'), 0'u8]
let (s, consumed) = decodeCString(buf, 2)
check s == ""
check consumed == 0
expect(ProtocolError):
discard decodeCString(buf, 2)

test "decodeCString offset past end of buffer":
let buf = @[byte('a'), 0'u8]
Expand All @@ -62,6 +61,11 @@ suite "Byte helpers":
expect(ProtocolError):
discard decodeCString(buf, 1)

test "decodeCString missing null terminator":
let buf = @[byte('h'), byte('i')]
expect(ProtocolError):
discard decodeCString(buf, 0)

suite "Frontend encoding":
test "encodeStartup - no type byte, version 3.0":
let msg = encodeStartup("testuser", "testdb")
Expand Down
Loading