From c6dfdf8d4b51504e1ff8e3d7c1772b80cb16fff3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 8 Mar 2018 18:09:28 +0100 Subject: [PATCH] comm: custom readline implementation w/ buffer We always read everything from the serial that is currently available in our rx buffer but only return the first line in that. While that increases our memory consumption slightly, it should hopefully not cause issues and should greatly reduce the risk of buffer overflows making us lose or receive corrupt data. Possible solution for #2370 and #2454 --- src/octoprint/util/comm.py | 43 +++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 229524196..dccd65189 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -20,6 +20,7 @@ from past.builtins import basestring import logging import serial +import wrapt import octoprint.plugin @@ -2240,7 +2241,7 @@ class MachineCom(object): serial_obj.parity = serial.PARITY_NONE serial_obj.open() - return serial_obj + return BufferedReadlineWrapper(serial_obj) serial_factories = self._serial_factory_hooks.items() + [("default", default)] for name, factory in serial_factories: @@ -4174,6 +4175,46 @@ class SendQueueMarker(QueueMarker): pass +class BufferedReadlineWrapper(wrapt.ObjectProxy): + def __init__(self, obj): + wrapt.ObjectProxy.__init__(self, obj) + self._buffered = bytearray() + + def readline(self, terminator=serial.LF): + termlen = len(terminator) + data = self._buffered + timeout = serial.Timeout(self._timeout) + + while True: + # make sure we always read everything that is waiting + data += bytearray(self.read(self.in_waiting)) + + # check for terminator, if it's there we have found our line + termpos = data.find(terminator) + if termpos >= 0: + # line: everything up to and incl. the terminator + line = data[:termpos + termlen] + # buffered: everything after the terminator + self._buffered = data[termpos + termlen:] + return bytes(line) + + # check if timeout expired + if timeout.expired(): + break + + # if we arrive here we so far couldn't read a full line, wait for more data + c = self.read(1) + if not c: + # EOF + break + + # add to data and loop + data += c + + self._buffered = data + return bytes("") + + # --- Test code for speed testing the comm layer via command line follows