ser2netweb 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. ser2netweb/__init__.py +20 -0
  2. ser2netweb/__main__.py +6 -0
  3. ser2netweb/accounts.py +503 -0
  4. ser2netweb/cli.py +489 -0
  5. ser2netweb/clock.py +128 -0
  6. ser2netweb/config.py +4491 -0
  7. ser2netweb/console.py +181 -0
  8. ser2netweb/datalock.py +181 -0
  9. ser2netweb/engine/__init__.py +0 -0
  10. ser2netweb/engine/access.py +173 -0
  11. ser2netweb/engine/bindhint.py +115 -0
  12. ser2netweb/engine/bridge.py +1928 -0
  13. ser2netweb/engine/cluster.py +1140 -0
  14. ser2netweb/engine/modbus.py +530 -0
  15. ser2netweb/engine/modbus_gateway.py +1465 -0
  16. ser2netweb/engine/mqtt_pub.py +632 -0
  17. ser2netweb/engine/netguard.py +805 -0
  18. ser2netweb/engine/netinfo.py +199 -0
  19. ser2netweb/engine/portdiag.py +414 -0
  20. ser2netweb/engine/portlist.py +471 -0
  21. ser2netweb/engine/protocols/__init__.py +28 -0
  22. ser2netweb/engine/protocols/base.py +117 -0
  23. ser2netweb/engine/protocols/raw.py +12 -0
  24. ser2netweb/engine/protocols/rfc2217.py +586 -0
  25. ser2netweb/engine/protocols/telnet.py +172 -0
  26. ser2netweb/engine/serial_compat.py +598 -0
  27. ser2netweb/engine/serial_io.py +210 -0
  28. ser2netweb/engine/serial_link.py +414 -0
  29. ser2netweb/engine/sockopts.py +103 -0
  30. ser2netweb/engine/sparkplug.py +538 -0
  31. ser2netweb/engine/sparkplug_node.py +550 -0
  32. ser2netweb/engine/supervisor.py +533 -0
  33. ser2netweb/engine/tls.py +232 -0
  34. ser2netweb/envvars.py +57 -0
  35. ser2netweb/explain.py +117 -0
  36. ser2netweb/healthcheck.py +78 -0
  37. ser2netweb/i18n.py +110 -0
  38. ser2netweb/importer.py +550 -0
  39. ser2netweb/layout.py +118 -0
  40. ser2netweb/licences.py +86 -0
  41. ser2netweb/locale/tr.json +1569 -0
  42. ser2netweb/logsetup.py +253 -0
  43. ser2netweb/logtext.py +23 -0
  44. ser2netweb/notify.py +761 -0
  45. ser2netweb/optional.py +76 -0
  46. ser2netweb/reload.py +295 -0
  47. ser2netweb/runtime.py +762 -0
  48. ser2netweb/sdnotify.py +85 -0
  49. ser2netweb/ser2net_import.py +2001 -0
  50. ser2netweb/signins.py +98 -0
  51. ser2netweb/standalone.py +154 -0
  52. ser2netweb/state.py +1457 -0
  53. ser2netweb/storage.py +130 -0
  54. ser2netweb/textfold.py +51 -0
  55. ser2netweb/tlsreload.py +37 -0
  56. ser2netweb/watchdog.py +201 -0
  57. ser2netweb/web/__init__.py +0 -0
  58. ser2netweb/web/api.py +793 -0
  59. ser2netweb/web/auth.py +699 -0
  60. ser2netweb/web/certinfo.py +144 -0
  61. ser2netweb/web/httpguard.py +413 -0
  62. ser2netweb/web/ldap_auth.py +556 -0
  63. ser2netweb/web/oidc_auth.py +330 -0
  64. ser2netweb/web/proxy.py +398 -0
  65. ser2netweb/web/routes/__init__.py +78 -0
  66. ser2netweb/web/routes/cluster.py +669 -0
  67. ser2netweb/web/routes/common.py +359 -0
  68. ser2netweb/web/routes/console.py +451 -0
  69. ser2netweb/web/routes/forms.py +853 -0
  70. ser2netweb/web/routes/login.py +573 -0
  71. ser2netweb/web/routes/mappings.py +470 -0
  72. ser2netweb/web/routes/ops.py +374 -0
  73. ser2netweb/web/routes/settings.py +2135 -0
  74. ser2netweb/web/routes/system.py +308 -0
  75. ser2netweb/web/routes/totp.py +282 -0
  76. ser2netweb/web/selfsigned.py +129 -0
  77. ser2netweb/web/server.py +483 -0
  78. ser2netweb/web/static/app.css +327 -0
  79. ser2netweb/web/static/app.js +1102 -0
  80. ser2netweb/web/static/htmx.min.js +1 -0
  81. ser2netweb/web/static/points.js +218 -0
  82. ser2netweb/web/static/theme.js +7 -0
  83. ser2netweb/web/static/xterm-addon-fit.js +2 -0
  84. ser2netweb/web/static/xterm.css +218 -0
  85. ser2netweb/web/static/xterm.js +2 -0
  86. ser2netweb/web/templates/_cluster_body.html +109 -0
  87. ser2netweb/web/templates/_console.html +21 -0
  88. ser2netweb/web/templates/_footer.html +13 -0
  89. ser2netweb/web/templates/_login_notice.html +8 -0
  90. ser2netweb/web/templates/_macros.html +21 -0
  91. ser2netweb/web/templates/_mapping_form.html +477 -0
  92. ser2netweb/web/templates/_mapping_log.html +28 -0
  93. ser2netweb/web/templates/_mapping_traces.html +44 -0
  94. ser2netweb/web/templates/_mappings_body.html +149 -0
  95. ser2netweb/web/templates/_modbus_read.html +18 -0
  96. ser2netweb/web/templates/_ports_table.html +37 -0
  97. ser2netweb/web/templates/_serial_port_select.html +48 -0
  98. ser2netweb/web/templates/_shell.html +41 -0
  99. ser2netweb/web/templates/audit.html +55 -0
  100. ser2netweb/web/templates/base.html +77 -0
  101. ser2netweb/web/templates/dashboard.html +72 -0
  102. ser2netweb/web/templates/licenses.html +18 -0
  103. ser2netweb/web/templates/login.html +32 -0
  104. ser2netweb/web/templates/login_totp.html +23 -0
  105. ser2netweb/web/templates/settings.html +830 -0
  106. ser2netweb/web/templates/setup.html +43 -0
  107. ser2netweb/web/templates/totp.html +41 -0
  108. ser2netweb/web/totp.py +94 -0
  109. ser2netweb/winservice.py +1793 -0
  110. ser2netweb-3.0.0.dist-info/METADATA +120 -0
  111. ser2netweb-3.0.0.dist-info/RECORD +121 -0
  112. ser2netweb-3.0.0.dist-info/WHEEL +5 -0
  113. ser2netweb-3.0.0.dist-info/entry_points.txt +2 -0
  114. ser2netweb-3.0.0.dist-info/licenses/COMMERCIAL_LICENSE.md +94 -0
  115. ser2netweb-3.0.0.dist-info/licenses/LICENSE +662 -0
  116. ser2netweb-3.0.0.dist-info/licenses/NOTICE +20 -0
  117. ser2netweb-3.0.0.dist-info/licenses/THIRD-PARTY-NOTICES.md +105 -0
  118. ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/htmx.org.txt +13 -0
  119. ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/xterm-addon-fit.txt +19 -0
  120. ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/xterm.txt +21 -0
  121. ser2netweb-3.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,586 @@
1
+ """RFC 2217 mode: telnet + COM-PORT-CONTROL, via pyserial's PortManager.
2
+
3
+ We reuse ``serial.rfc2217.PortManager`` as the protocol engine — it parses the
4
+ telnet/RFC2217 subnegotiation stream and applies SET-BAUDRATE/DATASIZE/PARITY/
5
+ STOPSIZE/CONTROL directly onto the live serial.Serial, and emits NOTIFY-MODEMSTATE
6
+ deltas. We supply one PortManager PER client (it carries protocol state) and own
7
+ the networking ourselves.
8
+
9
+ PortManager writes its telnet replies/notifications by calling ``connection.write``;
10
+ we capture those into a buffer that the bridge drains to the socket.
11
+
12
+ The network stream is parsed by our own subclass (_PortManager.feed_parts): the same state
13
+ machine as PortManager.filter, which looks at every byte in Python and keeps whatever
14
+ follows IAC SB without a limit, but data between commands goes through in bulk (a regex
15
+ scan, bytes.replace) and a subnegotiation longer than MAX_SUBNEGOTIATION ends the session.
16
+ Serial data is escaped with bytes.replace, which gives exactly what PortManager.escape
17
+ yields byte by byte.
18
+
19
+ Commands and data keep their order: a command that acts on the port (SET-BAUDRATE,
20
+ SET-DATASIZE, SET-PARITY, SET-STOPSIZE, SET-CONTROL, PURGE-DATA) is not carried out while
21
+ the read is parsed, but returned at its place in the data (PortCommand), and so is every
22
+ command after it in that read; the bridge writes the data before it first and, for a
23
+ setting, waits until that data has left the port. IAC BRK becomes a serial BREAK there too
24
+ (BREAK), unless the mapping is read-only.
25
+
26
+ What pyserial's PortManager leaves out is answered here: SIGNATURE (an empty one asks for
27
+ ours: "ser2net", or the mapping's rfc2217_signature), the SET-CONTROL queries (BREAK, DTR
28
+ and RTS state, the inbound flow control) from the port's state, and SET-LINESTATE-MASK /
29
+ SET-MODEMSTATE-MASK with an acknowledgement. Flow control is one mode at a time (XON/XOFF
30
+ turns RTS/CTS off and the other way round, either one DSR/DTR) and a DSR/DTR port says so
31
+ when asked (DSR flow control outbound, DTR inbound); "no flow control" leaves DSR/DTR flow
32
+ control on, as before, since pyserial's rfc2217:// clients ask for it at every open. The
33
+ flow controls RFC 2217 has and pyserial can't set (inbound only, DCD, DTR, DSR) are refused
34
+ with the current setting.
35
+
36
+ Robustness: PortManager reads modem-status lines (CTS/DSR/RI/CD) and may toggle
37
+ RTS/DTR/BREAK. Virtual ports (PTYs) and some USB adapters don't support those
38
+ ioctls and raise OSError(ENOTTY), which would otherwise tear down the client. We
39
+ wrap the serial object so those specific operations degrade gracefully while every
40
+ other attribute (baudrate/parity/databits/stopbits/...) passes straight through.
41
+
42
+ A request is refused as RFC 2217 says, by answering with the current setting, and the
43
+ client stays connected: a malformed or reserved value (a short SET-BAUDRATE, parity 6,
44
+ stop size 4, ...) is handled as a request for the current setting, and a value the serial
45
+ port refuses (Windows SetCommState, a baud rate the OS can't take) is first taken back
46
+ off the serial object, where pyserial stores it before the driver sees it. What a client
47
+ sends that is refused or ignored is logged (rate-limited by the bridge).
48
+
49
+ The serial port can go away and be reopened while a client stays connected (the bridge
50
+ reopens it with a new pyserial object and calls serial_changed): the session then drives
51
+ the reopened port, which is given the settings the client has, so it goes on as before.
52
+ While the port is closed, the client's settings can still be read and changed (they take
53
+ effect when it is back), the modem lines read low and a purge has nothing to do.
54
+
55
+ Not done (documented, not fatal): server-side NOTIFY-LINESTATE is stubbed (always 0),
56
+ FLOWCONTROL-SUSPEND/RESUME are taken but don't hold the client's data, and PURGE-DATA
57
+ purges the operating system's buffers, not the data still waiting in the bridge.
58
+ """
59
+ from __future__ import annotations
60
+
61
+ import contextlib
62
+ from functools import partial
63
+ from typing import TYPE_CHECKING, Callable, Optional
64
+
65
+ from serial import rfc2217 as _rfc2217
66
+
67
+ from .base import (BREAK, MAX_SUBNEGOTIATION, PortCommand, ProtocolError, ProtocolSession,
68
+ data_run_end, subnegotiation_too_long)
69
+
70
+ _MODEM_READS = ("cts", "dsr", "ri", "cd")
71
+ _LINE_WRITES = ("rts", "dtr", "break_condition")
72
+ # Port-configuration writes RFC2217 SET-* commands perform on the live serial.
73
+ # Blocked on read-only mappings so a "read-only" client cannot reconfigure the
74
+ # physical port (baud/framing/flow-control) or toggle control lines.
75
+ _CONFIG_WRITES = ("baudrate", "bytesize", "parity", "stopbits", "xonxoff", "rtscts", "dsrdtr")
76
+ _RO_BLOCKED_WRITES = frozenset(_CONFIG_WRITES + _LINE_WRITES)
77
+ # Mutating method calls (buffer purge, writes) blocked on read-only mappings.
78
+ _RO_BLOCKED_CALLS = frozenset({
79
+ "write", "flush", "reset_input_buffer", "reset_output_buffer",
80
+ "flushInput", "flushOutput", "send_break", "setRTS", "setDTR", "setBreak",
81
+ })
82
+
83
+
84
+ def _noop(*_args, **_kwargs):
85
+ return None
86
+
87
+
88
+ def _settings_of(ser) -> dict:
89
+ """A port's settings, the ones an RFC 2217 client can change ({} without a port)."""
90
+ settings = {}
91
+ if ser is not None:
92
+ for name in _CONFIG_WRITES:
93
+ with contextlib.suppress(Exception):
94
+ settings[name] = getattr(ser, name)
95
+ return settings
96
+
97
+
98
+ class _ModemSafeSerial:
99
+ """Transparent proxy that prevents unsupported modem-line ioctls from raising.
100
+
101
+ Reads of CTS/DSR/RI/CD fall back to False; writes of RTS/DTR/BREAK are ignored
102
+ if the backend doesn't support them. All other attribute access (including
103
+ baudrate/parity/bytesize/stopbits changes that RFC2217 needs) is delegated
104
+ verbatim to the real serial instance.
105
+
106
+ When ``read_only`` is set the proxy additionally drops every port-mutating
107
+ operation (SET-BAUDRATE/DATASIZE/PARITY/STOPSIZE/CONTROL, RTS/DTR/BREAK,
108
+ buffer purges). Reads still pass through, so the client keeps getting
109
+ NOTIFY-MODEMSTATE and the queries answer the port's real state. A refused
110
+ SET-BAUDRATE/DATASIZE/PARITY/STOPSIZE is answered with the actual (unchanged)
111
+ setting, the correct RFC 2217 response for a request that took no effect; a
112
+ SET-CONTROL that would change flow control, RTS, DTR or BREAK is acknowledged
113
+ with the value asked for although nothing changed, since pyserial's rfc2217://
114
+ client fails its open() on any other answer.
115
+
116
+ A port setting the serial port refuses is put back to what it was and raised as
117
+ ValueError, which PortManager answers with the current setting (_set_config).
118
+
119
+ The proxy keeps the port settings as the client knows them, and the RTS/DTR/BREAK
120
+ state it set: rebind() moves it to a reopened port, which is given them, or to None
121
+ while the port is closed. Without a port, settings are read from and changed in what
122
+ the proxy keeps (the reopened port gets the changes), line changes wait for the port
123
+ too, modem lines read low and a purge does nothing.
124
+ """
125
+
126
+ def __init__(self, ser, read_only: bool = False,
127
+ log: Optional[Callable[[str], None]] = None) -> None:
128
+ object.__setattr__(self, "_ser", ser)
129
+ object.__setattr__(self, "_read_only", read_only)
130
+ object.__setattr__(self, "_log", log or _noop)
131
+ object.__setattr__(self, "_settings", _settings_of(ser)) # as the client knows them
132
+ object.__setattr__(self, "_lines", {}) # RTS/DTR/BREAK as the client set them
133
+
134
+ def __getattr__(self, name):
135
+ ser = self._ser
136
+ if name in _MODEM_READS:
137
+ if ser is None:
138
+ return False # no port: the lines are low
139
+ try:
140
+ return getattr(ser, name)
141
+ except Exception:
142
+ return False
143
+ if ser is None:
144
+ if name in self._settings:
145
+ return self._settings[name]
146
+ if name in _LINE_WRITES: # no port: as the client set them (applied at reopen)
147
+ return self._lines.get(name, False)
148
+ if name in _RO_BLOCKED_CALLS:
149
+ return _noop # no port: nothing to purge
150
+ elif self._read_only and name in _RO_BLOCKED_CALLS:
151
+ return _noop
152
+ return getattr(ser, name)
153
+
154
+ def __setattr__(self, name, value):
155
+ if self._read_only and name in _RO_BLOCKED_WRITES:
156
+ return # read-only: ignore baud/framing/flow-control/RTS/DTR/BREAK changes
157
+ ser = self._ser
158
+ if name in _LINE_WRITES:
159
+ if ser is not None:
160
+ try:
161
+ setattr(ser, name, value)
162
+ except Exception:
163
+ return # not supported by this port (PTYs, some USB adapters)
164
+ self._lines[name] = value
165
+ return
166
+ if name in _CONFIG_WRITES:
167
+ if ser is not None:
168
+ self._set_config(name, value)
169
+ self._settings[name] = value
170
+ return
171
+ setattr(ser, name, value)
172
+
173
+ def rebind(self, ser) -> list[str]:
174
+ """Drive ``ser`` from now on: the reopened port, or None while it is closed. A
175
+ reopened port (of a writable mapping) is given the client's settings and line
176
+ state; returns the settings it refused (it keeps its own for those)."""
177
+ object.__setattr__(self, "_ser", ser)
178
+ if ser is None:
179
+ return []
180
+ refused = []
181
+ if not self._read_only:
182
+ for name, value in self._settings.items(): # pyserial's order: baud rate first
183
+ try:
184
+ if getattr(ser, name) != value:
185
+ self._set_config(name, value)
186
+ except Exception:
187
+ refused.append(f"{name} {value!r}")
188
+ for name, value in self._lines.items():
189
+ with contextlib.suppress(Exception):
190
+ setattr(ser, name, value)
191
+ object.__setattr__(self, "_settings", _settings_of(ser))
192
+ return refused
193
+
194
+ def _set_config(self, name: str, value) -> None:
195
+ """Set a port setting; raises ValueError, with the old value back in place, when
196
+ the port refuses it. pyserial stores a new value before it reconfigures the port,
197
+ so a value the driver or the OS refused (SerialException, termios.error,
198
+ OverflowError, ...) would otherwise stay set: reported by every later query and
199
+ applied again with the next change."""
200
+ ser = self._ser
201
+ old = getattr(ser, name)
202
+ try:
203
+ setattr(ser, name, value)
204
+ except Exception as e:
205
+ with contextlib.suppress(Exception):
206
+ setattr(ser, name, old)
207
+ if value != old:
208
+ self._log(f"RFC 2217: the serial port refused {name} {value!r} "
209
+ f"({type(e).__name__}: {e}); it stays {old!r}")
210
+ raise ValueError(f"{name} {value!r} refused: {e}") from e
211
+
212
+
213
+ class _NetConnection:
214
+ """Minimal sink implementing the .write(bytes) that PortManager expects."""
215
+
216
+ def __init__(self) -> None:
217
+ self.buf = bytearray()
218
+
219
+ def write(self, data: bytes) -> None:
220
+ self.buf.extend(data)
221
+
222
+
223
+ _IAC, _SB, _SE, _BRK = _rfc2217.IAC, _rfc2217.SB, _rfc2217.SE, _rfc2217.BRK
224
+ _NEGOTIATION = (_rfc2217.DO, _rfc2217.DONT, _rfc2217.WILL, _rfc2217.WONT)
225
+ M_NORMAL, M_IAC_SEEN, M_NEGOTIATE = _rfc2217.M_NORMAL, _rfc2217.M_IAC_SEEN, _rfc2217.M_NEGOTIATE
226
+
227
+ # COM-PORT-OPTION commands a client sends (RFC 2217 section 3)
228
+ _COMMANDS = {
229
+ 0: "SIGNATURE", 1: "SET-BAUDRATE", 2: "SET-DATASIZE", 3: "SET-PARITY", 4: "SET-STOPSIZE",
230
+ 5: "SET-CONTROL", 6: "NOTIFY-LINESTATE", 7: "NOTIFY-MODEMSTATE", 8: "FLOWCONTROL-SUSPEND",
231
+ 9: "FLOWCONTROL-RESUME", 10: "SET-LINESTATE-MASK", 11: "SET-MODEMSTATE-MASK",
232
+ 12: "PURGE-DATA",
233
+ }
234
+ # The ones that set a port setting: the size of the value and the values RFC 2217 defines
235
+ # (None: any); 0 asks for the current setting, the rest are reserved.
236
+ _SETTINGS = {
237
+ 1: (4, None),
238
+ 2: (1, frozenset({0, 5, 6, 7, 8})),
239
+ 3: (1, frozenset(range(6))), # none, odd, even, mark, space
240
+ 4: (1, frozenset(range(4))), # 1, 2, 1.5 stop bits
241
+ }
242
+ _SIGNATURE, _SET_CONTROL, _PURGE_DATA = 0, 5, 12
243
+ _SERVER_SIGNATURE = bytes([100]) # (pyserial has no constant for it)
244
+ _FLOW_CONTROL = frozenset({1, 2, 3}) # SET-CONTROL: no / XON-XOFF / hardware flow control
245
+ # SET-CONTROL values that change the port: flow control, BREAK, DTR and RTS on / off
246
+ _CONTROL_CHANGES = frozenset({1, 2, 3, 5, 6, 8, 9, 11, 12})
247
+ # what a SET-CONTROL value belongs to: its query (flow control out, BREAK, DTR, RTS, flow
248
+ # control in); 17 (DCD) and 19 (DSR flow control) are outbound / both, 18 (DTR) inbound
249
+ _CONTROL_QUERY = {**dict.fromkeys((0, 1, 2, 3, 17, 19), 0), **dict.fromkeys((4, 5, 6), 4),
250
+ **dict.fromkeys((7, 8, 9), 7), **dict.fromkeys((10, 11, 12), 10),
251
+ **dict.fromkeys((13, 14, 15, 16, 18), 13)}
252
+ # the masks' acknowledgements (RFC 2217: the server echoes the mask it now uses)
253
+ _MASK_ACKS = {10: _rfc2217.SERVER_SET_LINESTATE_MASK, 11: _rfc2217.SERVER_SET_MODEMSTATE_MASK}
254
+ _NEEDS_VALUE = frozenset({5, 10, 11, 12})
255
+ _PURGE_VALUES = frozenset({1, 2, 3}) # receive / transmit / both buffers
256
+ #: what an empty SIGNATURE (a request for ours) is answered with by default
257
+ DEFAULT_SIGNATURE = "ser2net"
258
+
259
+
260
+ def _acts_on_port(suboption: bytes) -> Optional[bool]:
261
+ """Does a subnegotiation act on the serial port? None: no (a query, a mask, ...);
262
+ True: it changes the port's settings (the data before it must have left first); False:
263
+ it purges the port's buffers (the data before it must have been written first)."""
264
+ if suboption[:1] != _rfc2217.COM_PORT_OPTION or len(suboption) < 3:
265
+ return None
266
+ command, value = suboption[1], suboption[2:]
267
+ if command in _SETTINGS:
268
+ return True if any(value) else None # (0 asks for the current setting)
269
+ if command == _SET_CONTROL:
270
+ return True if value[0] in _CONTROL_CHANGES else None
271
+ if command == _PURGE_DATA:
272
+ return False
273
+ return None
274
+
275
+
276
+ def _show(value: bytes) -> str:
277
+ """A request's value for the log (the first bytes of a long one)."""
278
+ if not value:
279
+ return "without a value"
280
+ return value[:8].hex(" ") + (" ..." if len(value) > 8 else "")
281
+
282
+
283
+ if TYPE_CHECKING:
284
+ class _PortManagerBase(_rfc2217.PortManager):
285
+ # PortManager's private telnet handlers, which _PortManager calls and overrides;
286
+ # pyserial's type stubs (types-pyserial) leave them out
287
+ def _telnet_negotiate_option(self, command: bytes, option: bytes) -> None: ...
288
+ def _telnet_process_command(self, command: bytes) -> None: ...
289
+ def _telnet_process_subnegotiation(self, suboption: bytes) -> None: ...
290
+ else:
291
+ _PortManagerBase = _rfc2217.PortManager
292
+
293
+
294
+ class _PortManager(_PortManagerBase):
295
+ """pyserial's RFC 2217 server engine with a parser of our own in front of it
296
+ (feed_parts). It keeps PortManager's parser state (mode, suboption, telnet_command), so
297
+ the command handlers and anything that looks at that state work as before. Commands go
298
+ to PortManager's handlers after a check of their value (_telnet_process_subnegotiation);
299
+ SIGNATURE and SET-CONTROL are answered here."""
300
+
301
+ # PortManager's parser state (set in its __init__)
302
+ mode: int
303
+ # the subnegotiation under way (None: none); pyserial keeps a bytearray here, its
304
+ # stubs say bytes (the ignore is unused where they aren't installed)
305
+ suboption: Optional[bytearray] # type: ignore[assignment, unused-ignore]
306
+ telnet_command: bytes
307
+
308
+ def __init__(self, serial_port, connection, log: Optional[Callable[[str], None]] = None,
309
+ signature: str = ""):
310
+ self._note = log or _noop # (PortManager's own `logger` is a logging.Logger)
311
+ text = signature if isinstance(signature, str) and signature else DEFAULT_SIGNATURE
312
+ self._signature = text.encode("utf-8", "replace")
313
+ super().__init__(serial_port, connection)
314
+
315
+ def feed(self, data: bytes) -> bytes:
316
+ """The bytes for the serial port in ``data``, its commands carried out at once
317
+ (feed_parts for a caller that has no port to keep them in order with; a BREAK is
318
+ left out)."""
319
+ out = bytearray()
320
+ for part in self.feed_parts(data):
321
+ if isinstance(part, bytes):
322
+ out += part
323
+ elif isinstance(part, PortCommand):
324
+ part.apply()
325
+ return bytes(out)
326
+
327
+ def feed_parts(self, data: bytes) -> list:
328
+ """Parse bytes from the network; returns what they hold, in order: the bytes for
329
+ the serial port, BREAK for an IAC BRK, and a PortCommand for a command that acts on
330
+ the port and for every command after it or after a BREAK in ``data`` (so the
331
+ replies keep their order); the commands before those are carried out at once. What
332
+ filter() does, but a run of data bytes and escaped IACs is passed on, or added to
333
+ the subnegotiation under way, in one go; only the bytes of a command go through the
334
+ state machine one at a time. Raises ProtocolError once a subnegotiation grows past
335
+ MAX_SUBNEGOTIATION."""
336
+ parts: list = []
337
+ out = bytearray()
338
+
339
+ def flush() -> None:
340
+ if out:
341
+ parts.append(bytes(out))
342
+ out.clear()
343
+
344
+ def later(apply: Callable[[], None], settle: bool = False) -> None:
345
+ flush()
346
+ parts.append(PortCommand(apply, settle))
347
+
348
+ i, n = 0, len(data)
349
+ while i < n:
350
+ mode = self.mode
351
+ if mode == M_NORMAL:
352
+ end = data_run_end(data, i)
353
+ if end > i:
354
+ run = data[i:end]
355
+ if 0xFF in run:
356
+ run = run.replace(b"\xff\xff", b"\xff")
357
+ if self.suboption is None:
358
+ out += run
359
+ else:
360
+ self._add_to_suboption(run)
361
+ i = end
362
+ if i == n:
363
+ break
364
+ self.mode = M_IAC_SEEN # data[i] is the IAC of a command
365
+ i += 1
366
+ continue
367
+ byte = data[i:i + 1]
368
+ i += 1
369
+ self.mode = M_NORMAL
370
+ if mode == M_NEGOTIATE: # the option of a DO/DONT/WILL/WONT
371
+ if parts:
372
+ later(partial(self._telnet_negotiate_option, self.telnet_command, byte))
373
+ else:
374
+ self._telnet_negotiate_option(self.telnet_command, byte)
375
+ elif byte == _IAC: # an escaped 0xFF split across two reads
376
+ if self.suboption is None:
377
+ out += byte
378
+ else:
379
+ self._add_to_suboption(byte)
380
+ elif byte == _SB:
381
+ self.suboption = bytearray()
382
+ elif byte == _SE:
383
+ if self.suboption is None:
384
+ self._note("telnet IAC SE without IAC SB ignored")
385
+ else:
386
+ suboption, self.suboption = bytes(self.suboption), None
387
+ acts = _acts_on_port(suboption)
388
+ if parts or acts is not None:
389
+ later(partial(self._telnet_process_subnegotiation, suboption),
390
+ settle=acts is True)
391
+ else:
392
+ self._telnet_process_subnegotiation(suboption)
393
+ elif byte in _NEGOTIATION:
394
+ self.telnet_command = byte
395
+ self.mode = M_NEGOTIATE
396
+ elif byte == _BRK: # a serial BREAK, after the data before it
397
+ flush()
398
+ parts.append(BREAK)
399
+ elif parts:
400
+ later(partial(self._telnet_process_command, byte))
401
+ else:
402
+ self._telnet_process_command(byte)
403
+ flush()
404
+ return parts
405
+
406
+ def filter(self, data):
407
+ """PortManager's generator interface, on top of feed()."""
408
+ out = self.feed(data)
409
+ if out:
410
+ yield out
411
+
412
+ def _add_to_suboption(self, data: bytes) -> None:
413
+ sub = self.suboption
414
+ assert sub is not None # noqa: S101 - called only during a subnegotiation
415
+ if len(sub) + len(data) > MAX_SUBNEGOTIATION:
416
+ raise subnegotiation_too_long()
417
+ sub += data
418
+
419
+ def _telnet_process_subnegotiation(self, suboption: bytes) -> None:
420
+ """PortManager's handler, after a check of the value. RFC 2217 refuses a request by
421
+ answering with the current setting, and PortManager's handlers raise on a value
422
+ they can't read (struct.error, KeyError, TypeError):
423
+ - a SET-BAUDRATE/DATASIZE/PARITY/STOPSIZE value that is too short or reserved is
424
+ handled as a request for the current setting (value 0), which is the answer;
425
+ - a SET-CONTROL, mask or PURGE-DATA without a (defined) value is ignored;
426
+ - a value the serial port refuses comes back from _ModemSafeSerial as ValueError,
427
+ which PortManager answers with the current setting itself;
428
+ - anything else that fails is answered with the current setting where RFC 2217
429
+ has an answer, a failed purge is acknowledged.
430
+ Each of these is logged; none ends the session. SIGNATURE and SET-CONTROL are
431
+ handled here (_set_control), a mask is acknowledged once PortManager stored it."""
432
+ if suboption[:1] != _rfc2217.COM_PORT_OPTION or len(suboption) < 2:
433
+ super()._telnet_process_subnegotiation(suboption) # not RFC 2217: ignored
434
+ return
435
+ command, value = suboption[1], suboption[2:]
436
+ name = _COMMANDS.get(command, f"command {command}")
437
+ setting = _SETTINGS.get(command)
438
+ if setting is not None:
439
+ size, defined = setting
440
+ if len(value) < size or (defined is not None and value[0] not in defined):
441
+ self._note(f"RFC 2217 {name} {_show(value)} refused (malformed or reserved "
442
+ "value); answered with the current setting")
443
+ suboption = suboption[:2] + bytes(size) # a request for the current setting
444
+ elif command in _NEEDS_VALUE and (
445
+ not value or (command == _PURGE_DATA and value[0] not in _PURGE_VALUES)):
446
+ self._note(f"RFC 2217 {name} {_show(value)} ignored (malformed or reserved value)")
447
+ return
448
+ if command == _SIGNATURE:
449
+ if not value: # (with a text: the client's own signature, nothing to answer)
450
+ self.rfc2217_send_subnegotiation(_SERVER_SIGNATURE, self._signature)
451
+ return
452
+ flow = None
453
+ try:
454
+ if command == _SET_CONTROL:
455
+ if value[0] in _FLOW_CONTROL:
456
+ flow = {attr: getattr(self.serial, attr, False)
457
+ for attr in ("xonxoff", "rtscts", "dsrdtr")}
458
+ self._set_control(value[0])
459
+ return
460
+ super()._telnet_process_subnegotiation(suboption)
461
+ if command in _MASK_ACKS:
462
+ self.rfc2217_send_subnegotiation(_MASK_ACKS[command], value[:1])
463
+ except Exception as e:
464
+ self._note(f"RFC 2217 {name} {_show(value)} failed ({type(e).__name__}: {e}); "
465
+ "answered with the current setting")
466
+ self._answer_current(command, value, flow)
467
+
468
+ def _set_control(self, value: int) -> None:
469
+ """SET-CONTROL: change flow control (one mode at a time), BREAK, DTR or RTS and
470
+ acknowledge it, or answer a query with the port's state. A flow control pyserial
471
+ can't set (inbound only, DCD, DTR, DSR) or a reserved value is refused with the
472
+ current setting of what it belongs to (outbound flow control for a reserved one)."""
473
+ ser = self.serial
474
+ if value in _FLOW_CONTROL:
475
+ for attr, on in (("xonxoff", value == 2), ("rtscts", value == 3)):
476
+ if getattr(ser, attr) != on:
477
+ setattr(ser, attr, on)
478
+ if value != 1 and getattr(ser, "dsrdtr", False): # (no flow control: see above)
479
+ ser.dsrdtr = False
480
+ reply = value
481
+ elif value in (5, 6):
482
+ ser.break_condition = value == 5
483
+ reply = value
484
+ elif value in (8, 9):
485
+ ser.dtr = value == 8
486
+ reply = value
487
+ elif value in (11, 12):
488
+ ser.rts = value == 11
489
+ reply = value
490
+ else:
491
+ query = _CONTROL_QUERY.get(value, 0)
492
+ if query != value:
493
+ self._note(f"RFC 2217 SET-CONTROL {value} refused (a flow control this port "
494
+ "can't set, or a reserved value); answered with the current "
495
+ "setting")
496
+ reply = self._control_state(query)
497
+ self.rfc2217_send_subnegotiation(_rfc2217.SERVER_SET_CONTROL, bytes([reply]))
498
+
499
+ def _control_state(self, query: int) -> int:
500
+ """The answer to a SET-CONTROL query (0, 4, 7, 10 or 13): the port's state."""
501
+ ser = self.serial
502
+ if query == 4:
503
+ return 5 if ser.break_condition else 6
504
+ if query == 7:
505
+ return 8 if ser.dtr else 9
506
+ if query == 10:
507
+ return 11 if ser.rts else 12
508
+ dsrdtr = getattr(ser, "dsrdtr", False)
509
+ if query == 13: # inbound: XON/XOFF, hardware (RTS), DTR
510
+ return 15 if ser.xonxoff else 16 if ser.rtscts else 18 if dsrdtr else 14
511
+ # outbound / both: XON/XOFF, hardware (CTS), DSR (pyserial's order)
512
+ return 2 if ser.xonxoff else 3 if ser.rtscts else 19 if dsrdtr else 1
513
+
514
+ def _answer_current(self, command: int, value: bytes, flow: Optional[dict]) -> None:
515
+ """After a request that failed: undo what a flow control change did halfway, then
516
+ answer with the current setting (a purge: acknowledge it)."""
517
+ for attr, old in (flow or {}).items():
518
+ with contextlib.suppress(Exception):
519
+ if getattr(self.serial, attr, False) != old:
520
+ setattr(self.serial, attr, old)
521
+ with contextlib.suppress(Exception):
522
+ if command in _SETTINGS:
523
+ super()._telnet_process_subnegotiation(
524
+ _rfc2217.COM_PORT_OPTION + bytes([command]) + bytes(_SETTINGS[command][0]))
525
+ elif command == _SET_CONTROL:
526
+ self.rfc2217_send_subnegotiation(
527
+ _rfc2217.SERVER_SET_CONTROL,
528
+ bytes([self._control_state(_CONTROL_QUERY.get(value[0], 0))]))
529
+ elif command == _PURGE_DATA:
530
+ self.rfc2217_send_subnegotiation(_rfc2217.SERVER_PURGE_DATA, value[:1])
531
+
532
+
533
+ class Rfc2217Session(ProtocolSession):
534
+ def __init__(self, serial_instance, poll_interval: float = 1.0, read_only: bool = False,
535
+ log: Optional[Callable[[str], None]] = None, signature: str = "") -> None:
536
+ """``log``: where what the client sends that is refused or ignored is reported;
537
+ ``signature``: what a SIGNATURE request is answered with (blank: "ser2net")."""
538
+ self._conn = _NetConnection()
539
+ self._serial = _ModemSafeSerial(serial_instance, read_only=read_only, log=log)
540
+ # PortManager.__init__ emits initial telnet negotiation into _conn.
541
+ self._pm = _PortManager(self._serial, self._conn, log=log, signature=signature)
542
+ self.poll_interval = poll_interval if poll_interval and poll_interval > 0 else 1.0
543
+
544
+ def initial_net_bytes(self) -> bytes:
545
+ return self.take_net_out()
546
+
547
+ def from_network_parts(self, data: bytes) -> list:
548
+ # the serial-bound bytes and the commands between them; replies go to _conn.write
549
+ pm = self._pm
550
+ if pm.mode == M_NORMAL and pm.suboption is None and 0xFF not in data:
551
+ # no command in this chunk: it all goes to the port as it is
552
+ return [data] if data else []
553
+ return pm.feed_parts(data)
554
+
555
+ def break_left_on(self) -> bool:
556
+ """The client set BREAK on (SET-CONTROL) and did not turn it off again."""
557
+ return bool(self._serial._lines.get("break_condition"))
558
+
559
+ def from_serial(self, data: bytes) -> bytes:
560
+ return data.replace(b"\xff", b"\xff\xff") if 0xFF in data else data
561
+
562
+ def take_net_out(self) -> bytes:
563
+ out = bytes(self._conn.buf)
564
+ self._conn.buf.clear()
565
+ return out
566
+
567
+ def poll(self) -> bytes:
568
+ # push modem-line (CTS/DSR/RI/CD) change notifications to the client
569
+ try:
570
+ self._pm.check_modem_lines()
571
+ except Exception:
572
+ pass
573
+ return self.take_net_out()
574
+
575
+ def serial_changed(self, serial) -> None:
576
+ """Drive the bridge's port from now on: the reopened one (given the client's
577
+ settings, so the client goes on as before) or None while it is closed. The modem
578
+ lines are reported to the client as they are now. Raises ProtocolError when the
579
+ reopened port refuses a setting the client has (the client would be told one
580
+ thing while the port runs at another)."""
581
+ refused = self._serial.rebind(serial)
582
+ with contextlib.suppress(Exception):
583
+ self._pm.check_modem_lines()
584
+ if refused:
585
+ raise ProtocolError("the reopened serial port refused the client's settings ("
586
+ + ", ".join(refused) + ")")