Skip to content

Commit

Permalink
Add more checks for EOF, short lines, etc.
Browse files Browse the repository at this point in the history
Signed-off-by: Geoff Hutchison <[email protected]>
  • Loading branch information
ghutchis committed Jan 21, 2025
1 parent 7f90837 commit eed3018
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions avogadro/io/mdlformat.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,28 @@ bool MdlFormat::read(std::istream& in, Core::Molecule& mol)
if (!buffer.empty())
mol.setData("name", buffer);

if (!in.good()) {
appendError("Error reading molecule name.");
return false;
}

// Skip the next two lines (generator, and comment).
getline(in, buffer);
getline(in, buffer);
if (!in.good()) {
appendError("Error reading generator and comment lines.");
return false;
}

// The counts line, and version identifier.
getline(in, buffer);
// should be long enough, e.g.
// 5 4 0 0 0 0 0 0 0 0999 V2000
if (buffer.size() < 39) {
appendError("Error reading counts line.");
return false;
}

bool ok(false);
int numAtoms(lexicalCast<int>(buffer.substr(0, 3), ok));
if (!ok) {
Expand All @@ -105,6 +121,12 @@ bool MdlFormat::read(std::istream& in, Core::Molecule& mol)
for (int i = 0; i < numAtoms; ++i) {
Vector3 pos;
getline(in, buffer);
// 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
if (!in.good() || buffer.size() < 40) {
appendError("Error reading atom block.");
return false;
}

pos.x() = lexicalCast<Real>(buffer.substr(0, 10), ok);
if (!ok) {
appendError("Failed to parse x coordinate: " + buffer.substr(0, 10));
Expand Down Expand Up @@ -146,6 +168,12 @@ bool MdlFormat::read(std::istream& in, Core::Molecule& mol)
for (int i = 0; i < numBonds; ++i) {
// Bond atom indices start at 1, -1 for C++.
getline(in, buffer);
// 1 2 1 0 0 0 0
if (!in.good() || buffer.size() < 10) {
appendError("Error reading bond block.");
return false;
}

int begin(lexicalCast<int>(buffer.substr(0, 3), ok) - 1);
if (!ok) {
appendError("Error parsing beginning bond index:" + buffer.substr(0, 3));
Expand Down Expand Up @@ -174,6 +202,9 @@ bool MdlFormat::read(std::istream& in, Core::Molecule& mol)
bool foundEnd(false);
bool foundChgProperty(false);
while (getline(in, buffer)) {
if (!in.good() || buffer.size() < 6) {
break;
}
string prefix = buffer.substr(0, 6);
if (prefix == "M END") {
foundEnd = true;
Expand Down

0 comments on commit eed3018

Please sign in to comment.