fix: replace deprecated socket send/recv with modern asyncio streams (#51)#59
Open
deacon-mp wants to merge 1 commit intomitre:masterfrom
Open
fix: replace deprecated socket send/recv with modern asyncio streams (#51)#59deacon-mp wants to merge 1 commit intomitre:masterfrom
deacon-mp wants to merge 1 commit intomitre:masterfrom
Conversation
…itre#51) Caldera 5.0.0's contact_tcp.py calls writer.get_extra_info('socket') which returns a TransportSocket object that lacks send()/recv() methods, causing 'TransportSocket object has no attribute send'. This adds: - c_connection.py: async Connection wrapper around StreamReader/StreamWriter - c_session.py: Session class that caldera's contact_tcp.py imports - tcp_patch.py: runtime patch applied at plugin load to fix the TCP handler's accept/refresh/send methods to use the async Connection wrapper instead of the broken TransportSocket The patch auto-detects whether caldera has already been updated (main branch uses its own TCPSession) and is a no-op in that case.
6 tasks
There was a problem hiding this comment.
Pull request overview
This PR addresses Caldera 5.0.0 incompatibilities in the Manx TCP contact path by introducing stream-based abstractions and a runtime patch to replace deprecated socket send/recv usage that triggers TransportSocket errors.
Changes:
- Added
Connection(StreamReader/StreamWriter wrapper) andSessionmodel to match Caldera’s import expectations. - Introduced
tcp_patch.pymonkey-patch to replaceTcpSessionHandlermethods (accept/refresh/send/_attempt_connection) when the legacy API is detected. - Added unit tests covering the new wrapper/model and basic patch behavior.
Reviewed changes
Copilot reviewed 7 out of 8 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| app/c_connection.py | Adds async send()/recv() wrapper over asyncio streams. |
| app/c_session.py | Adds Session model class (expected import path for Caldera TCP contact). |
| app/tcp_patch.py | Adds runtime patch to swap TcpSessionHandler methods to stream-based I/O. |
| hook.py | Applies the TCP handler patch during plugin enable. |
| tests/test_c_connection.py | Unit tests for Connection wrapper behavior. |
| tests/test_c_session.py | Unit tests for Session model behavior. |
| tests/test_tcp_patch.py | Unit tests for patching logic and patched refresh/send behaviors. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+33
to
+41
| # If the accept method references 'get_extra_info', it needs patching. | ||
| # If it's already been patched or uses TCPSession, skip. | ||
| import inspect | ||
| try: | ||
| source = inspect.getsource(handler.accept) | ||
| return 'get_extra_info' in source | ||
| except (OSError, TypeError): | ||
| # Can't inspect, assume patching is safe (it's idempotent) | ||
| return True |
Comment on lines
+80
to
+83
| conn = next(i.connection for i in self.sessions if i.id == int(session_id)) | ||
| await conn.send(str.encode(' ')) | ||
| time.sleep(0.01) | ||
| await conn.send(str.encode('%s\n' % cmd)) |
| async def _patched_send(self, session_id: int, cmd: str, timeout: int = 60) -> Tuple[int, str, str, str]: | ||
| """Replacement for TcpSessionHandler.send that uses async Connection.""" | ||
| try: | ||
| conn = next(i.connection for i in self.sessions if i.id == int(session_id)) |
Comment on lines
+92
to
+110
| async def _patched_attempt_connection(self, session_id, connection, timeout): | ||
| """Replacement for TcpSessionHandler._attempt_connection using async recv.""" | ||
| buffer = 4096 | ||
| data = b'' | ||
| waited_seconds = 0 | ||
| time.sleep(0.1) # initial wait for fast operations. | ||
| while True: | ||
| try: | ||
| part = await connection.recv(buffer) | ||
| data += part | ||
| if len(part) < buffer: | ||
| break | ||
| except BlockingIOError as err: | ||
| if waited_seconds < timeout: | ||
| time.sleep(1) | ||
| waited_seconds += 1 | ||
| else: | ||
| self.log.error("Timeout reached for session %s", session_id) | ||
| return json.dumps(dict(status=1, pwd='~$ ', response=str(err))) |
Comment on lines
+101
to
+103
| data += part | ||
| if len(part) < buffer: | ||
| break |
Comment on lines
+92
to
+111
| async def _patched_attempt_connection(self, session_id, connection, timeout): | ||
| """Replacement for TcpSessionHandler._attempt_connection using async recv.""" | ||
| buffer = 4096 | ||
| data = b'' | ||
| waited_seconds = 0 | ||
| time.sleep(0.1) # initial wait for fast operations. | ||
| while True: | ||
| try: | ||
| part = await connection.recv(buffer) | ||
| data += part | ||
| if len(part) < buffer: | ||
| break | ||
| except BlockingIOError as err: | ||
| if waited_seconds < timeout: | ||
| time.sleep(1) | ||
| waited_seconds += 1 | ||
| else: | ||
| self.log.error("Timeout reached for session %s", session_id) | ||
| return json.dumps(dict(status=1, pwd='~$ ', response=str(err))) | ||
| return str(data, 'utf-8') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
TransportSocket object has no attribute 'send'c_connection.py(async Connection wrapper around StreamReader/StreamWriter) andc_session.py(Session class that caldera 5.0.0's contact_tcp.py imports fromplugins.manx.app)tcp_patch.pyruntime patch applied at plugin load that replaces the broken TcpSessionHandler methods (accept/refresh/send) to use the async Connection wrapper instead of the raw TransportSocketChanges
app/c_connection.py-- Async wrapper providingsend()/recv()overStreamWriter.write()/StreamReader.read()app/c_session.py-- Session model class imported by caldera'scontact_tcp.pyapp/tcp_patch.py-- Runtime monkey-patch for TcpSessionHandler to fix the deprecated APIhook.py-- Apply the patch at plugin enable timetests/-- Unit tests for Connection, Session, and the TCP patchRoot cause
Caldera 5.0.0's
contact_tcp.pycallswriter.get_extra_info('socket')which returns anasyncio.TransportSocketthat lackssend()/recv()methods. The fix wraps theStreamReader/StreamWriterpair in aConnectionobject that provides asyncsend()/recv().Test plan
pytest plugins/manx/tests/