From eed3018bd0cffc18cc0e53bcfcd99df8c269be9b Mon Sep 17 00:00:00 2001 From: Geoff Hutchison Date: Mon, 20 Jan 2025 23:20:32 -0500 Subject: [PATCH] Add more checks for EOF, short lines, etc. Signed-off-by: Geoff Hutchison --- avogadro/io/mdlformat.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/avogadro/io/mdlformat.cpp b/avogadro/io/mdlformat.cpp index adb34e26de..d94f162d08 100644 --- a/avogadro/io/mdlformat.cpp +++ b/avogadro/io/mdlformat.cpp @@ -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(buffer.substr(0, 3), ok)); if (!ok) { @@ -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(buffer.substr(0, 10), ok); if (!ok) { appendError("Failed to parse x coordinate: " + buffer.substr(0, 10)); @@ -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(buffer.substr(0, 3), ok) - 1); if (!ok) { appendError("Error parsing beginning bond index:" + buffer.substr(0, 3)); @@ -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;