|
1 | 1 | import json |
2 | 2 | import queue |
| 3 | +import re |
3 | 4 | import threading |
4 | 5 | from collections.abc import Callable, Generator |
5 | 6 | from enum import Enum |
|
8 | 9 | from mistapi.__api_response import APIResponse as _APIResponse |
9 | 10 | from mistapi.__logger import logger as LOGGER |
10 | 11 |
|
| 12 | +# Matches ANSI CSI sequences, OSC sequences, and character set designations |
| 13 | +_ANSI_ESCAPE_RE = re.compile( |
| 14 | + r"\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07]*\x07|\x1b[()][A-B0-2]" |
| 15 | +) |
| 16 | + |
| 17 | +# Detects VT100 cursor positioning / clear-screen (triggers screen-buffer mode) |
| 18 | +_SCREEN_MODE_RE = re.compile(r"\x1b\[[\d;]*H|\x1b\[2J") |
| 19 | + |
| 20 | + |
| 21 | +class _VT100Screen: |
| 22 | + """Minimal VT100 terminal emulator for rendering screen-based output. |
| 23 | +
|
| 24 | + Handles the subset of VT100 sequences used by Junos ``top`` and |
| 25 | + ``monitor interface`` commands: cursor positioning, screen/line |
| 26 | + clearing, and cursor movement. SGR (colors), scroll regions, and |
| 27 | + mode changes are silently ignored. |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__(self, rows: int = 80, cols: int = 200) -> None: |
| 31 | + self.rows = rows |
| 32 | + self.cols = cols |
| 33 | + self.cursor_row = 0 |
| 34 | + self.cursor_col = 0 |
| 35 | + self.grid: list[list[str]] = [[" "] * cols for _ in range(rows)] |
| 36 | + |
| 37 | + def feed(self, text: str) -> None: |
| 38 | + """Process *text* (may contain VT100 sequences) into the screen buffer.""" |
| 39 | + i = 0 |
| 40 | + n = len(text) |
| 41 | + while i < n: |
| 42 | + ch = text[i] |
| 43 | + |
| 44 | + if ch == "\x1b" and i + 1 < n: |
| 45 | + nxt = text[i + 1] |
| 46 | + if nxt == "[": |
| 47 | + # CSI sequence: \x1b[ <params> <cmd> |
| 48 | + j = i + 2 |
| 49 | + params = "" |
| 50 | + while j < n and text[j] in "0123456789;": |
| 51 | + params += text[j] |
| 52 | + j += 1 |
| 53 | + if j < n: |
| 54 | + self._handle_csi(params, text[j]) |
| 55 | + i = j + 1 |
| 56 | + else: |
| 57 | + i = j |
| 58 | + continue |
| 59 | + if nxt in "()": |
| 60 | + # Character-set designation – skip 3 bytes |
| 61 | + i += 3 if i + 2 < n else n |
| 62 | + continue |
| 63 | + if nxt == "]": |
| 64 | + # OSC sequence – skip until BEL |
| 65 | + j = i + 2 |
| 66 | + while j < n and text[j] != "\x07": |
| 67 | + j += 1 |
| 68 | + i = j + 1 |
| 69 | + continue |
| 70 | + # Unknown escape – skip \x1b and the next char |
| 71 | + i += 2 |
| 72 | + continue |
| 73 | + |
| 74 | + if ch == "\r": |
| 75 | + self.cursor_col = 0 |
| 76 | + i += 1 |
| 77 | + continue |
| 78 | + |
| 79 | + if ch == "\n": |
| 80 | + self.cursor_row += 1 |
| 81 | + self.cursor_col = 0 |
| 82 | + if self.cursor_row >= self.rows: |
| 83 | + self.grid.pop(0) |
| 84 | + self.grid.append([" "] * self.cols) |
| 85 | + self.cursor_row = self.rows - 1 |
| 86 | + i += 1 |
| 87 | + continue |
| 88 | + |
| 89 | + if ch == "\x00": |
| 90 | + i += 1 |
| 91 | + continue |
| 92 | + |
| 93 | + # Printable character |
| 94 | + if 0 <= self.cursor_row < self.rows and 0 <= self.cursor_col < self.cols: |
| 95 | + self.grid[self.cursor_row][self.cursor_col] = ch |
| 96 | + self.cursor_col += 1 |
| 97 | + i += 1 |
| 98 | + |
| 99 | + # ------------------------------------------------------------------ |
| 100 | + def _handle_csi(self, params: str, cmd: str) -> None: |
| 101 | + nums = [] |
| 102 | + for p in params.split(";") if params else []: |
| 103 | + try: |
| 104 | + nums.append(int(p)) |
| 105 | + except ValueError: |
| 106 | + nums.append(0) |
| 107 | + |
| 108 | + if cmd in ("H", "f"): # Cursor position |
| 109 | + row = (nums[0] - 1) if nums else 0 |
| 110 | + col = (nums[1] - 1) if len(nums) > 1 else 0 |
| 111 | + self.cursor_row = max(0, min(row, self.rows - 1)) |
| 112 | + self.cursor_col = max(0, min(col, self.cols - 1)) |
| 113 | + elif cmd == "A": # Cursor up |
| 114 | + self.cursor_row = max(0, self.cursor_row - (nums[0] if nums else 1)) |
| 115 | + elif cmd == "B": # Cursor down |
| 116 | + self.cursor_row = min( |
| 117 | + self.rows - 1, self.cursor_row + (nums[0] if nums else 1) |
| 118 | + ) |
| 119 | + elif cmd == "C": # Cursor forward |
| 120 | + self.cursor_col = min( |
| 121 | + self.cols - 1, self.cursor_col + (nums[0] if nums else 1) |
| 122 | + ) |
| 123 | + elif cmd == "D": # Cursor back |
| 124 | + self.cursor_col = max(0, self.cursor_col - (nums[0] if nums else 1)) |
| 125 | + elif cmd == "J": # Erase in display |
| 126 | + n = nums[0] if nums else 0 |
| 127 | + if n == 2: |
| 128 | + self.grid = [[" "] * self.cols for _ in range(self.rows)] |
| 129 | + self.cursor_row = 0 |
| 130 | + self.cursor_col = 0 |
| 131 | + elif n == 0: |
| 132 | + for c in range(self.cursor_col, self.cols): |
| 133 | + self.grid[self.cursor_row][c] = " " |
| 134 | + for r in range(self.cursor_row + 1, self.rows): |
| 135 | + self.grid[r] = [" "] * self.cols |
| 136 | + elif cmd == "K": # Erase in line |
| 137 | + n = nums[0] if nums else 0 |
| 138 | + if n == 0: |
| 139 | + for c in range(self.cursor_col, self.cols): |
| 140 | + self.grid[self.cursor_row][c] = " " |
| 141 | + elif n == 1: |
| 142 | + for c in range(self.cursor_col + 1): |
| 143 | + self.grid[self.cursor_row][c] = " " |
| 144 | + elif n == 2: |
| 145 | + self.grid[self.cursor_row] = [" "] * self.cols |
| 146 | + # SGR (m), scroll region (r), mode set/reset (l, h) – ignore |
| 147 | + |
| 148 | + # ------------------------------------------------------------------ |
| 149 | + def render(self) -> str: |
| 150 | + """Return screen content as text with trailing whitespace trimmed.""" |
| 151 | + lines = ["".join(row).rstrip() for row in self.grid] |
| 152 | + while lines and not lines[-1]: |
| 153 | + lines.pop() |
| 154 | + return "\n".join(lines) |
| 155 | + |
11 | 156 |
|
12 | 157 | class TimerAction(Enum): |
13 | 158 | """ |
@@ -176,6 +321,8 @@ def __init__( |
176 | 321 | self.session_id: str | None = None |
177 | 322 | self.capture_id: str | None = None |
178 | 323 | self._on_message_cb = on_message |
| 324 | + self._screen: _VT100Screen | None = None |
| 325 | + self._screen_mode: bool = False |
179 | 326 | self._extract_trigger_ids() |
180 | 327 |
|
181 | 328 | def _extract_trigger_ids(self): |
@@ -252,7 +399,8 @@ def _handle_message(self, msg): |
252 | 399 | self._timeout_handler(Timer.FIRST_MESSAGE_TIMEOUT, TimerAction.START) |
253 | 400 | elif self._extract_session_id(msg): |
254 | 401 | # Stop the first message timeout timer on receiving the first message |
255 | | - self._timeout_handler(Timer.FIRST_MESSAGE_TIMEOUT, TimerAction.STOP) |
| 402 | + if self.timers[Timer.FIRST_MESSAGE_TIMEOUT.value]["thread"]: |
| 403 | + self._timeout_handler(Timer.FIRST_MESSAGE_TIMEOUT, TimerAction.STOP) |
256 | 404 | LOGGER.debug("data: %s", msg) |
257 | 405 | raw = self._extract_raw(msg) |
258 | 406 | if raw: |
@@ -323,8 +471,19 @@ def _extract_raw(self, message, root: bool = True): |
323 | 471 | return self._extract_raw(event["data"], root=False) |
324 | 472 | if "raw" in event: |
325 | 473 | self.received_messages += 1 |
326 | | - LOGGER.debug("Extracted raw message: %s", event["raw"]) |
327 | | - return event["raw"] |
| 474 | + raw_value = event["raw"] |
| 475 | + if isinstance(raw_value, str): |
| 476 | + # Detect screen-mode (cursor positioning / clear-screen) |
| 477 | + if not self._screen_mode and _SCREEN_MODE_RE.search(raw_value): |
| 478 | + self._screen_mode = True |
| 479 | + self._screen = _VT100Screen() |
| 480 | + if self._screen_mode and self._screen is not None: |
| 481 | + self._screen.feed(raw_value) |
| 482 | + raw_value = self._screen.render() |
| 483 | + else: |
| 484 | + raw_value = _ANSI_ESCAPE_RE.sub("", raw_value) |
| 485 | + LOGGER.debug("Extracted raw message: %s", raw_value) |
| 486 | + return raw_value |
328 | 487 | if "pcap_dict" in event: |
329 | 488 | self.received_messages += 1 |
330 | 489 | LOGGER.debug("Extracted pcap data: %s", event["pcap_dict"]) |
|
0 commit comments