Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 60 additions & 38 deletions can/interfaces/socketcand/socketcand.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,41 +296,7 @@ def _recv_internal(self, timeout):
self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1)
self.__receive_buffer += ascii_msg
log.debug(f"Received Ascii Message: {ascii_msg}")
buffer_view = self.__receive_buffer
chars_processed_successfully = 0
while True:
if len(buffer_view) == 0:
break

start = buffer_view.find("<")
if start == -1:
log.warning(
f"Bad data: No opening < found => discarding entire buffer '{buffer_view}'"
)
chars_processed_successfully = len(self.__receive_buffer)
break
end = buffer_view.find(">")
if end == -1:
log.warning("Got incomplete message => waiting for more data")
if len(buffer_view) > 200:
log.warning(
"Incomplete message exceeds 200 chars => Discarding"
)
chars_processed_successfully = len(self.__receive_buffer)
break
chars_processed_successfully += end + 1
single_message = buffer_view[start : end + 1]
parsed_can_message = convert_ascii_message_to_can_message(
single_message
)
if parsed_can_message is None:
log.warning(f"Invalid Frame: {single_message}")
else:
parsed_can_message.channel = self.channel
self.__message_buffer.append(parsed_can_message)
buffer_view = buffer_view[end + 1 :]

self.__receive_buffer = self.__receive_buffer[chars_processed_successfully:]
self._parse_receive_buffer()
can_message = (
None
if len(self.__message_buffer) == 0
Expand All @@ -350,12 +316,68 @@ def _tcp_send(self, msg: str):
if self.__tcp_tune:
self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1)

def _parse_receive_buffer(self) -> None:
"""Move every complete message in the receive buffer to the message buffer."""
buffer_view = self.__receive_buffer
chars_processed_successfully = 0
while True:
if len(buffer_view) == 0:
break

start = buffer_view.find("<")
if start == -1:
log.warning(
f"Bad data: No opening < found => discarding entire buffer '{buffer_view}'"
)
chars_processed_successfully = len(self.__receive_buffer)
break
end = buffer_view.find(">")
if end == -1:
log.warning("Got incomplete message => waiting for more data")
if len(buffer_view) > 200:
log.warning("Incomplete message exceeds 200 chars => Discarding")
chars_processed_successfully = len(self.__receive_buffer)
break
chars_processed_successfully += end + 1
single_message = buffer_view[start : end + 1]
parsed_can_message = convert_ascii_message_to_can_message(single_message)
if parsed_can_message is None:
log.warning(f"Invalid Frame: {single_message}")
else:
parsed_can_message.channel = self.channel
self.__message_buffer.append(parsed_can_message)
buffer_view = buffer_view[end + 1 :]

self.__receive_buffer = self.__receive_buffer[chars_processed_successfully:]

def _expect_msg(self, msg):
ascii_msg = self.__socket.recv(256).decode("ascii")
if self.__tcp_tune:
self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1)
# TCP is a stream: the reply can arrive in several pieces, and after
# "< rawmode >" the first frames can follow the "< ok >" in the same read.
while ">" not in self.__receive_buffer:
# a reply always starts with "<", so fail early instead of waiting
# forever when the server is not socketcand
buffer = self.__receive_buffer.lstrip()
if (buffer and not buffer.startswith("<")) or len(buffer) > 200:
raise can.CanInitializationError(
f"Expected '{msg}' got: '{self.__receive_buffer}'"
)
data = self.__socket.recv(256)
if not data:
raise can.CanInitializationError(
f"Expected '{msg}' got: '{self.__receive_buffer}' "
"(connection closed)"
)
if self.__tcp_tune:
self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1)
self.__receive_buffer += data.decode("ascii")

end = self.__receive_buffer.index(">") + 1
ascii_msg = self.__receive_buffer[:end]
if not ascii_msg == msg:
raise can.CanError(f"Expected '{msg}' got: '{ascii_msg}'")
self.__receive_buffer = self.__receive_buffer[end:]
# keep frames that arrived together with the reply
self._parse_receive_buffer()

def send(self, msg, timeout=None):
"""Transmit a message to the CAN bus.
Expand Down
1 change: 1 addition & 0 deletions doc/changelog.d/2150.fixed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed the ``socketcand`` handshake failing when a server reply arrived split over several reads or together with the first CAN frames.
81 changes: 81 additions & 0 deletions test/test_socketcand.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#!/usr/bin/env python

import socket
import threading
import unittest

import can
from can.interfaces.socketcand import socketcand

Expand Down Expand Up @@ -69,5 +72,83 @@ def test_remote_frame_is_refused(self):
socketcand.convert_can_message_to_ascii_message(msg)


class TestHandshake(unittest.TestCase):
"""The server replies arrive on a TCP stream, so a read can hold part
of a reply or a reply followed by frames."""

def _serve(self, chunks):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 0))
server.listen(1)
self.addCleanup(server.close)

def run():
conn, _ = server.accept()
with conn:
for expected_cmd, reply_chunks in chunks:
if expected_cmd:
received = b""
while not received.endswith(b">"):
received += conn.recv(256)
self.assertEqual(received.decode("ascii"), expected_cmd)
for chunk in reply_chunks:
conn.sendall(chunk.encode("ascii"))
threading.Event().wait(0.05)
# wait for the client to close the connection
while conn.recv(256):
pass

thread = threading.Thread(target=run, daemon=True)
thread.start()
self.addCleanup(thread.join, 2)
return server.getsockname()[1]

def test_frames_in_same_read_as_rawmode_ok(self):
port = self._serve(
[
(None, ["< hi >"]),
("< open can0 >", ["< ok >"]),
("< rawmode >", ["< ok >< frame 123 1680000000.0 0102 >"]),
]
)
with can.Bus(
interface="socketcand", channel="can0", host="127.0.0.1", port=port
) as bus:
msg = bus.recv(timeout=1)
self.assertIsNotNone(msg)
self.assertEqual(msg.arbitration_id, 0x123)
self.assertEqual(msg.data, bytearray([1, 2]))
self.assertEqual(msg.channel, "can0")

def test_reply_split_over_reads(self):
port = self._serve(
[
(None, ["< h", "i >"]),
("< open can0 >", ["< o", "k >"]),
("< rawmode >", ["< ok >"]),
]
)
with can.Bus(
interface="socketcand", channel="can0", host="127.0.0.1", port=port
) as bus:
self.assertIsNone(bus.recv(timeout=0.1))

def test_unexpected_reply_raises(self):
port = self._serve(
[
(None, ["< hi >"]),
("< open can0 >", ["< error could not open bus >"]),
]
)
with self.assertRaises(can.CanError):
can.Bus(interface="socketcand", channel="can0", host="127.0.0.1", port=port)

def test_non_socketcand_server_raises(self):
# e.g. the port belongs to another service that keeps the connection open
port = self._serve([(None, ["SSH-2.0-OpenSSH_9.6\r\n"])])
with self.assertRaises(can.CanInitializationError):
can.Bus(interface="socketcand", channel="can0", host="127.0.0.1", port=port)


if __name__ == "__main__":
unittest.main()
Loading