Skip to content

Commit

Permalink
Fix uncaught exception caused by invalid UTF-8 data
Browse files Browse the repository at this point in the history
The json serializer will throw for invalid UTF-8 (e.g.
if long PS has undetected errors). Fix by catching serializer
exceptions before anything gets printed.
  • Loading branch information
windytan committed Jul 15, 2024
1 parent 3330480 commit 58ea59f
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 deletions.
7 changes: 7 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# redsea changelog

## 1.0.1

* Fixes:
* Fix a crash (uncaught json exception) when attempting to serialize a string that's
invalid UTF-8, e.g. if long PS gets corrupted
* Fix build when the installed version of nlohmann-json is too old (#113)

## 1.0 (2024-06-27)

* New features:
Expand Down
2 changes: 1 addition & 1 deletion meson.build
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
project('redsea', 'cpp', default_options : ['warning_level=3', 'buildtype=release', 'optimization=3'],
version: '1.0')
version: '1.0.1')

# Store version number to be compiled in
conf = configuration_data()
Expand Down
13 changes: 12 additions & 1 deletion src/groups.cc
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,18 @@ void Station::updateAndPrint(const Group& group, std::ostream& stream) {
}
}

stream << json_ << std::endl << std::flush;
try {
// nlohmann::operator<< throws if a string contains non-UTF8 data.
// It's better to throw while writing to a stringstream; otherwise
// incomplete JSON objects could get printed.
std::stringstream output_proxy_stream;
output_proxy_stream << json_;
stream << output_proxy_stream.str() << std::endl << std::flush;
} catch (const std::exception& e) {
nlohmann::ordered_json json_from_exception;
json_from_exception["debug"] = std::string(e.what());
stream << json_from_exception << std::endl << std::flush;
}
}

uint16_t Station::getPI() const {
Expand Down
12 changes: 12 additions & 0 deletions test/unit.cc
Original file line number Diff line number Diff line change
Expand Up @@ -449,3 +449,15 @@ TEST_CASE("Error detection and correction") {
CHECK(groups.back().get(redsea::BLOCK1) == 0x0000); // "----"
}
}

TEST_CASE("Invalid data") {
redsea::Options options;

SECTION("Invalid UTF-8 is handled cleanly") {
REQUIRE_NOTHROW(hex2json({
0xE24D'4401'D02F'1942,
0xE24D'E400'E24D'0000,
0xE24D'F400'E20D'FC20
}, options, 0xE24D));
}
}

0 comments on commit 58ea59f

Please sign in to comment.