Skip to content

Commit

Permalink
fix: unsafe read fix and added comments regarding smaller fd frames
Browse files Browse the repository at this point in the history
Signed-off-by: Kenzo Lobos-Tsunekawa <[email protected]>
  • Loading branch information
knzo25 committed Sep 19, 2024
1 parent 2bbdba4 commit 73bae2f
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions ros2_socketcan/src/socket_can_receiver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,19 @@ CanId SocketCanReceiver::receive_fd(void * const data, const std::chrono::nanose
// Read
struct canfd_frame frame;
const auto nbytes = read(m_file_descriptor, &frame, sizeof(frame));
const auto data_length = static_cast<CanId::LengthT>(frame.len);
const auto expected_length = sizeof(frame) - sizeof(frame.data) + data_length;

// Checks
if (nbytes < 0) {
throw std::runtime_error{strerror(errno)};
}

if (static_cast<std::size_t>(nbytes) < sizeof(frame.can_id) + sizeof(frame.len)) {
throw std::runtime_error{"read: corrupted CAN frame"};
}

const auto data_length = static_cast<CanId::LengthT>(frame.len);
const auto expected_length = sizeof(frame) - sizeof(frame.data) + data_length; // some CAN FD frames are shorter than 64 bytes

if (static_cast<std::size_t>(nbytes) < expected_length) {
throw std::runtime_error{"read: incomplete CAN FD frame"};
}
Expand Down

0 comments on commit 73bae2f

Please sign in to comment.