From 5117edfcb2094749b660e80c11f87f65965eb9b0 Mon Sep 17 00:00:00 2001 From: Emil Juhl Date: Wed, 1 May 2024 17:03:06 +0200 Subject: [PATCH] read: clear buffer when full and invalid If for some reason the read buffer got filled with data, but no complete hdlc frame was present, the library would get stuck. This is because the buffer is only ever erased from in the good case scenario. As a very simple workaround, albeit not a great one, just drop the entire buffer if it is not possible to deframe the data it contains _and_ it doesn't have room left for more data. Ideally, the recovery mechanism would only drop bytes until a start byte is spotted to make it more graceful on a buffer containing a partial frame. This is, however, already an edge case (otherwise users of the library should be experiencing these lockups at the moment), and thus it seems reasonable to just go for a harsh but simple workaround. --- include/Hdlcpp.hpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/include/Hdlcpp.hpp b/include/Hdlcpp.hpp index 8a7a12f..1890f1f 100644 --- a/include/Hdlcpp.hpp +++ b/include/Hdlcpp.hpp @@ -89,6 +89,12 @@ class Buffer { return m_tail; } + void clear() + { + m_head = m_buffer.begin(); + m_tail = m_head; + } + private: Container m_buffer {}; typename Container::iterator m_head { m_buffer.begin() }; @@ -161,6 +167,12 @@ class Hdlcpp { result = decode(address, readFrame, readSequenceNumber, readBuffer.dataSpan(), buffer, discardBytes); if (result >= 0) { doTransportRead = false; + } else if (readBuffer.unusedSpan().size() == 0) { + // Drop the buffer in an attempt to recover from getting + // filled with an invalid message. + // FIXME: really start/stop codes should be tracked to + // implement this in a more fail-safe way + readBuffer.clear(); } }