Skip to content

Commit

Permalink
Enforce the 2GB message size limit when serializing to binary form.
Browse files Browse the repository at this point in the history
  • Loading branch information
thomasvl committed Feb 22, 2023
1 parent dcd23ba commit 8d19c09
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Sources/SwiftProtobufCore/BinaryEncodingError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,7 @@ public enum BinaryEncodingError: Error {
/// must pass `partial: true` during encoding if you wish to explicitly ignore
/// missing required fields.
case missingRequiredFields

/// Messages are limited to a maximum of 2GB in encoded size.
case tooLarge
}
12 changes: 12 additions & 0 deletions Sources/SwiftProtobufCore/Message+BinaryAdditions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ extension Message {
throw BinaryEncodingError.missingRequiredFields
}
let requiredSize = try serializedDataSize()

// Messages have a 2GB limit in encoded size, the upstread C++ code
// (message_lite, etc.) does this enforcement also.
// https://protobuf.dev/programming-guides/encoding/#cheat-sheet
//
// Testing here enables the limit without adding extra conditionals to all
// the places that encode message fields (or strings/bytes fields), keeping
// the overhead of the check to a minimum.
guard requiredSize < 0x7fffffff else {
throw BinaryEncodingError.tooLarge
}

var data = Data(count: requiredSize)
try data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) in
if let baseAddress = body.baseAddress, body.count > 0 {
Expand Down

0 comments on commit 8d19c09

Please sign in to comment.