Skip to content

Commit e281cc8

Browse files
committed
Added functions to determine whether or not a .dbc file is valid or not.
The file extension is not a definitive answer to anything. Shoving a JPEG image with a modified extension would falsely identify that file as a valid DBC.
1 parent 32f2dbd commit e281cc8

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

include/libdbc/dbc.hpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@
88
#include <string>
99
#include <vector>
1010

11+
#if __cplusplus >= 201703L
12+
#include <filesystem>
13+
#endif // __cplusplus >= 201703L
14+
1115
namespace Libdbc {
1216

1317
class Parser {
@@ -35,6 +39,13 @@ class DbcParser : public Parser {
3539

3640
const std::vector<std::string>& unused_lines() const;
3741

42+
#if __cplusplus >= 201703L
43+
static bool is_valid_dbc_file(const std::filesystem::path&);
44+
#else
45+
static bool is_valid_dbc_file(const std::string&);
46+
#endif // __cplusplus >= 201703L
47+
static bool is_valid_dbc_file(std::istream& stream);
48+
3849
private:
3950
std::string version{};
4051
std::vector<std::string> nodes{};

src/dbc.cpp

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,32 @@ DbcParser::DbcParser()
7070
+ whiteSpace + receiverPattern) {
7171
}
7272

73+
#if __cplusplus >= 201703L
74+
bool DbcParser::is_valid_dbc_file(const std::filesystem::path& file_path) {
75+
#else
76+
bool DbcParser::is_valid_dbc_file(const std::string& file_path) {
77+
#endif // __cplusplus >= 201703L
78+
79+
std::ifstream testStream{file_path};
80+
if (!testStream.is_open()) { return false; }
81+
82+
return is_valid_dbc_file(testStream);
83+
}
84+
85+
bool DbcParser::is_valid_dbc_file(std::istream& stream) {
86+
stream.seekg(0, std::ios::beg);
87+
88+
try {
89+
DbcParser parser{};
90+
parser.parse_dbc_header(stream);
91+
} catch (const Exception& e) {
92+
// If the file is missing the version, it is not a valid DBC file
93+
return false;
94+
}
95+
96+
return true;
97+
}
98+
7399
void DbcParser::parse_file(std::istream& stream) {
74100
std::string line;
75101
std::vector<std::string> lines;
@@ -88,9 +114,8 @@ void DbcParser::parse_file(std::istream& stream) {
88114
}
89115

90116
void DbcParser::parse_file(const std::string& file_name) {
91-
auto extension = get_extension(file_name);
92-
if (extension != ".dbc") {
93-
throw NonDbcFileFormatError(file_name, extension);
117+
if (!is_valid_dbc_file(file_name)) {
118+
throw NonDbcFileFormatError(file_name, get_extension(file_name));
94119
}
95120

96121
std::ifstream stream(file_name);

0 commit comments

Comments
 (0)