Skip to content

set_socket_timeout + ignore receive timeout - #1000

Open
hs2bws wants to merge 5 commits into
gijzelaerr:masterfrom
hs2bws:socket-timeout
Open

hs2bws wants to merge 5 commits into
gijzelaerr:masterfrom
hs2bws:socket-timeout

Conversation

@hs2bws

@hs2bws hs2bws commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

In the event of a connection interruption, _connection.connected is set to false. This is checked within the get_status() function.

The issue is that, inside _recv_listener(), a socket timeout causes _connection.connected to be set to false and then immediately back to true. If get_status() happens to be called at that exact moment, it will return a status of 1 (running).

By setting connection.ignore_rcv_tout = True, it is now possible to prevent _connection.connected from being set to false when a receive timeout occurs.

When self.ignore_rcv_tout == True: self.connected is not set to False opon receicve timeout
New helper: set_socket_timeout()
pre-commit fix
pre-commit fix
@hs2bws

hs2bws commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Alternative solution: We could pass an argument from _recv_listener() through _b_recv_loop(), connection.receive_data(), and finally to _recv_exact().

connection.receive_data(self, ignore_rcv_tout = False)
connection._recv_exact(self, size: int, ignore_rcv_tout = False)
This shouldn't have any negative impact on backward compatibility, right?

It might also be a cleaner approach than using a variable.

@gijzelaerr gijzelaerr left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, @hs2bws. A get_status() that notices a lost connection is worth having. I ran this branch against a socket pair (two Partner objects wired as in tests/test_partner.py), and a few things need to change before it can go in.

Your question: flag or argument

The argument, please. A keyword on receive_data() and _recv_exact() (for example ignore_timeout: bool = False) carries no state. The flag can be left set: conn.ignore_rcv_tout = True runs before the inner try, so if gettimeout() or settimeout() raises, nothing resets it. A new keyword with a default does not break existing callers.

Problems

  1. set_socket_timeout() has no effect while the listener runs. It does not take _io_lock, so the finally in _recv_listener() puts the old timeout back over it. After as_b_recv() and then set_socket_timeout(3.0), the socket's timeout was still None. It also leaves conn.timeout at 5.0, so the two disagree.

  2. set_socket_timeout(0) is accepted. That makes the socket non-blocking. The next b_recv() returned -1 and the status dropped to 1. Please reject timeout <= 0.

  3. An ordinary receive timeout now reads as a lost connection. A synchronous b_recv() on an idle link times out, receive_data() sets conn.connected = False, and with the new check get_status() returns 1 although the TCP connection is fine. On master it returns 2, but the connection object is already unusable there (the next b_recv() returns -1 with "Not connected"), so this is an existing bug that the new check makes visible. The same applies to a timeout while b_send() waits for its acknowledgement. If get_status() is going to read conn.connected, a timeout outside the listener must not clear it either, or it needs handling in b_recv() and b_send().

  4. A peer that closes is still not detected. When the other partner called stop(), the listener ended with "Invalid COTP DT header length" and get_status() still returned 2: that path does not clear conn.connected. I ran this before #987 was merged, which changes what disconnect() sends, so it is worth re-checking on current master.

Smaller points

  • The race in the description is not on master: get_status() there never reads conn.connected. The race only exists once this PR adds that check, so the description should say that the PR makes get_status() follow the connection's state and avoids a false "running" while the listener times out.
  • get_status() sets self.connected = False as a side effect and without a lock. I would rather it stayed a pure read, for example by reporting connected only when both self.connected and self._connection.connected are true, or have the code that detects the loss clear the flag.
  • There are no tests. Please add at least: the status after the listener has timed out a few times (still 2), the status after the connection is lost, and set_socket_timeout() with and without a running listener and with an invalid value.
  • set_socket_timeout() is a second concern. What is it for? recv_timeout and the connection's timeout already exist. If it is needed, a separate PR would be easier to review. It also counts a call on an unconnected partner as a send error, which it is not.
  • Typos: "opon receicve" in connection.py, "timetout" in the docstring.
  • CHANGES.md: the entry leaves out the get_status() change, which is the part users will notice, and has no PR number. It now conflicts with master after #987.

@hs2bws

hs2bws commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @gijzelaerr for the reply and your suggestions.

Regarding the socket timeout: I recognize the shortcomings and will revise it. The default value of 5 seconds is somewhat too long for certain time-critical PLC applications. If no response is received within 100 ms of a b_send() call, it is highly unlikely that one will arrive after 5 seconds...

get_status():
In the current solution, this function does not provide a reliable indication of the connection status. If I transmit data via u_send() within a loop while simultaneously waiting for data using as_b_recv(), and then disconnect the network cable, the loop continues to run for a full minute without any errors. Subsequently, "not connected" errors occur, yet get_status() still returns 2 ("connected"). Even when the connection is active again, "not connected" errors still occur (conn.connected is still False). It only starts working again after a stop() and start() sequence. Hence my suggested changes. get_status() can safely return 1 when conn.connected = False, since communication is no longer possible in that state anyway.

How can we reliably determine whether a connection to the peer is still active?

What about the other Snap7 packages (client, server, etc.): does it actually make sense to set conn.connected to False when a receive or send timeout occurs?

@gijzelaerr

Copy link
Copy Markdown
Owner

Thanks, @hs2bws, the cable-pull case is exactly the one this needs to handle.

Should a timeout set connected = False? Only when it leaves the stream unusable. If a timeout hits after part of a frame was read, the next read starts in the middle of a frame, so the connection cannot be trusted any more and marking it closed is right. If nothing at all arrived, nothing is lost and the connection is as good as before. The server already makes this distinction: _recv_exact() in snap7/server/__init__.py raises S7ConnectionError after a partial frame and a plain timeout otherwise. ISOTCPConnection._recv_exact() in connection.py, which the client and the partner use, does not: it clears connected on any timeout. I would rather fix it there, for every user of the class, than add a flag or an argument for the listener. The listener's workaround of setting conn.connected = True again after a timeout could then go.

For the client, a timeout waiting for a reply is less clear-cut: the reply can still arrive later and would then be read as the answer to the next request. The client checks PDU references for some requests, but not all, so I would leave its behaviour alone in this PR.

How to tell whether the peer is still there. TCP alone does not notice a pulled cable until it next tries to send and its retransmissions give up, which can take minutes. That is why your u_send() loop ran for a minute without errors: sendall() only fills the kernel's buffer. There are two ways to find out sooner:

  • The application's own traffic. b_send() waits for the partner's acknowledgement, so a short receive timeout there is a fast liveness check. That is where a configurable timeout helps, rather than a general setter on the socket.
  • TCP keepalive. The active side (ISOTCPConnection._tcp_connect()) sets keepalive with a 60 s idle time, 10 s interval and 3 probes, where the platform supports those options. The passive partner's accepted socket only enables SO_KEEPALIVE, so it uses the OS default of about two hours. Giving it the same settings would make a passive partner notice a dead link within about 90 s even when it is idle.

After the link comes back, the old TCP connection does not recover; a new one has to be set up, which is why only stop() and start() help. So I agree that get_status() should stop reporting 2 once the connection is gone. What it should not do is report a lost connection after a timeout that lost nothing, which is what the change in _recv_exact() would settle.

One more thing I found while looking at this: b_recv() catches socket.timeout and returns 1, but ISOTCPConnection turns a timeout into S7TimeoutError, which is not a socket.timeout. So b_recv() returns -1 on a timeout, and the documented return value 1 never happens. That is older than this PR, but it touches the same lines, so it could be fixed here.

Suggested shape, in this PR or split up as you prefer:

  1. ISOTCPConnection._recv_exact(): keep connected on a timeout before the first byte of a frame, and raise S7ConnectionError and clear it after a partial frame, as the server does. Remove the workaround in _recv_listener().
  2. get_status(): report connected only while self._connection.connected is true too, without changing state.
  3. b_recv(): catch S7TimeoutError so a timeout returns 1.
  4. If you still need it, a timeout for the acknowledgement in b_send(), as its own setting.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants