browsermem 0.1.0__py3-none-win_amd64.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.
browsermem/__init__.py ADDED
@@ -0,0 +1,66 @@
1
+ """browsermem -- real-time browser tab URLs and titles on Windows.
2
+
3
+ Get the URL of the active tab::
4
+
5
+ >>> import browsermem
6
+ >>> browsermem.current_url()
7
+ 'https://github.com/BinaryBreaker/browsermem'
8
+
9
+ React to tab changes as they happen::
10
+
11
+ >>> monitor = browsermem.TabMonitor()
12
+ >>> @monitor.on_domain("youtube.com")
13
+ ... def watching(tab):
14
+ ... print("Now watching:", tab.title)
15
+ >>> monitor.run_forever()
16
+
17
+ See https://github.com/BinaryBreaker/browsermem for the full documentation.
18
+ """
19
+
20
+ from ._native import lib as _lib
21
+
22
+ __version__: str = _lib.bm_version().decode()
23
+
24
+ from .api import ( # noqa: E402
25
+ current_url,
26
+ dump_urls,
27
+ get_active_tab,
28
+ get_all_tabs,
29
+ get_tab,
30
+ list_windows,
31
+ version,
32
+ )
33
+ from .errors import ( # noqa: E402
34
+ AccessDeniedError,
35
+ BrowserMemError,
36
+ NotFoundError,
37
+ StateError,
38
+ )
39
+ from .forensics import MemoryImage # noqa: E402
40
+ from .history import TabHistory, Visit # noqa: E402
41
+ from .models import Browser, BrowserWindow, EventKind, Tab, UrlCount # noqa: E402
42
+ from .monitor import TabMonitor # noqa: E402
43
+
44
+ __all__ = [
45
+ "AccessDeniedError",
46
+ "Browser",
47
+ "BrowserMemError",
48
+ "BrowserWindow",
49
+ "EventKind",
50
+ "MemoryImage",
51
+ "NotFoundError",
52
+ "StateError",
53
+ "Tab",
54
+ "TabHistory",
55
+ "TabMonitor",
56
+ "UrlCount",
57
+ "Visit",
58
+ "__version__",
59
+ "current_url",
60
+ "dump_urls",
61
+ "get_active_tab",
62
+ "get_all_tabs",
63
+ "get_tab",
64
+ "list_windows",
65
+ "version",
66
+ ]
browsermem/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
browsermem/_native.py ADDED
@@ -0,0 +1,139 @@
1
+ """ctypes bindings mirroring ``native/include/browsermem.h``. Internal module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import os
7
+ import sys
8
+ from ctypes import (
9
+ CFUNCTYPE,
10
+ POINTER,
11
+ Structure,
12
+ c_char_p,
13
+ c_double,
14
+ c_int,
15
+ c_int32,
16
+ c_uint32,
17
+ c_uint64,
18
+ c_void_p,
19
+ )
20
+
21
+ DLL_NAME = "browsermem.dll"
22
+
23
+ # Status codes
24
+ OK = 0
25
+ ERR_INVALID_ARG = -1
26
+ ERR_NOT_FOUND = -2
27
+ ERR_ACCESS = -3
28
+ ERR_STATE = -4
29
+ ERR_INTERNAL = -5
30
+
31
+
32
+ class bm_candidate(Structure):
33
+ _fields_ = [("url", c_char_p), ("score", c_double)]
34
+
35
+
36
+ class bm_tab(Structure):
37
+ _fields_ = [
38
+ ("event", c_int32),
39
+ ("browser", c_int32),
40
+ ("browser_name", c_char_p),
41
+ ("pid", c_uint32),
42
+ ("candidate_count", c_uint32),
43
+ ("hwnd", c_uint64),
44
+ ("title", c_char_p),
45
+ ("caption", c_char_p),
46
+ ("url", c_char_p),
47
+ ("confidence", c_double),
48
+ ("timestamp_ms", c_uint64),
49
+ ("scan_ms", c_uint32),
50
+ ("reserved", c_uint32),
51
+ ("candidates", POINTER(bm_candidate)),
52
+ ]
53
+
54
+
55
+ class bm_window(Structure):
56
+ _fields_ = [
57
+ ("hwnd", c_uint64),
58
+ ("pid", c_uint32),
59
+ ("browser", c_int32),
60
+ ("browser_name", c_char_p),
61
+ ("caption", c_char_p),
62
+ ("title", c_char_p),
63
+ ("is_foreground", c_int32),
64
+ ("reserved", c_int32),
65
+ ]
66
+
67
+
68
+ class bm_url_entry(Structure):
69
+ _fields_ = [("url", c_char_p), ("count", c_uint32), ("reserved", c_uint32)]
70
+
71
+
72
+ class bm_monitor_options(Structure):
73
+ _fields_ = [
74
+ ("struct_size", c_uint32),
75
+ ("browser_mask", c_uint32),
76
+ ("debounce_ms", c_uint32),
77
+ ("rescan_ms", c_uint32),
78
+ ("cache_ttl_ms", c_uint32),
79
+ ("all_windows", c_int32),
80
+ ("emit_unresolved", c_int32),
81
+ ("reserved", c_int32),
82
+ ]
83
+
84
+
85
+ TAB_CALLBACK = CFUNCTYPE(None, POINTER(bm_tab), c_void_p)
86
+
87
+
88
+ def _locate_dll() -> str:
89
+ here = os.path.dirname(os.path.abspath(__file__))
90
+ candidates = [os.environ.get("BROWSERMEM_DLL"), os.path.join(here, DLL_NAME)]
91
+ for path in candidates:
92
+ if path and os.path.isfile(path):
93
+ return os.path.abspath(path)
94
+ raise ImportError(
95
+ f"{DLL_NAME} was not found next to the browsermem package. Install a wheel "
96
+ "(pip install browsermem), build from source (pip install .), or set "
97
+ "BROWSERMEM_DLL to the DLL's full path."
98
+ )
99
+
100
+
101
+ def _load() -> ctypes.CDLL:
102
+ if sys.platform != "win32":
103
+ raise ImportError("browsermem supports Windows only")
104
+ lib = ctypes.CDLL(_locate_dll())
105
+
106
+ def fn(name: str, restype, *argtypes) -> None:
107
+ f = getattr(lib, name)
108
+ f.restype = restype
109
+ f.argtypes = list(argtypes)
110
+
111
+ P = POINTER
112
+ fn("bm_version", c_char_p)
113
+ fn("bm_last_error", c_char_p)
114
+ fn("bm_list_windows", c_int, c_uint32, P(P(bm_window)), P(c_uint32))
115
+ fn("bm_windows_free", None, P(bm_window))
116
+ fn("bm_get_active_tab", c_int, c_uint32, P(P(bm_tab)))
117
+ fn("bm_get_tab", c_int, c_uint64, P(P(bm_tab)))
118
+ fn("bm_tab_free", None, P(bm_tab))
119
+ fn("bm_dump_urls", c_int, c_uint32, P(P(bm_url_entry)), P(c_uint32))
120
+ fn("bm_urls_free", None, P(bm_url_entry))
121
+ fn("bm_image_create", c_int, P(c_void_p))
122
+ fn("bm_image_capture", c_int, c_uint32, P(c_void_p))
123
+ fn("bm_image_add_region", c_int, c_void_p, c_uint64, c_void_p, c_uint64)
124
+ fn("bm_image_info", c_int, c_void_p, P(c_uint64), P(c_uint32))
125
+ fn("bm_image_urls", c_int, c_void_p, P(P(bm_url_entry)), P(c_uint32))
126
+ fn("bm_image_resolve", c_int, c_void_p, c_char_p, c_int32, P(P(bm_tab)))
127
+ fn("bm_image_free", None, c_void_p)
128
+ fn("bm_monitor_options_init", None, P(bm_monitor_options))
129
+ fn("bm_monitor_start", c_int, P(bm_monitor_options), TAB_CALLBACK, c_void_p, P(c_void_p))
130
+ fn("bm_monitor_stop", c_int, c_void_p)
131
+ return lib
132
+
133
+
134
+ lib = _load()
135
+
136
+
137
+ def last_error() -> str:
138
+ raw = lib.bm_last_error()
139
+ return raw.decode("utf-8", "replace") if raw else ""
browsermem/api.py ADDED
@@ -0,0 +1,117 @@
1
+ """One-shot queries against running browsers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ctypes import POINTER, byref, c_uint32
6
+ from typing import List, Optional, Union
7
+
8
+ from . import _native
9
+ from ._native import bm_tab, bm_url_entry, bm_window, lib # noqa: F401
10
+ from .errors import NotFoundError, check
11
+ from .models import (
12
+ BrowserFilter,
13
+ BrowserWindow,
14
+ Tab,
15
+ UrlCount,
16
+ _browser,
17
+ _s,
18
+ _tab_from_native,
19
+ browser_mask,
20
+ )
21
+
22
+
23
+ def version() -> str:
24
+ """Version of the native library."""
25
+ return _s(lib.bm_version())
26
+
27
+
28
+ def list_windows(browsers: BrowserFilter = None) -> List[BrowserWindow]:
29
+ """All browser windows, most recently active first. Does not read memory."""
30
+ arr = POINTER(bm_window)()
31
+ count = c_uint32()
32
+ check(lib.bm_list_windows(browser_mask(browsers), byref(arr), byref(count)))
33
+ try:
34
+ return [
35
+ BrowserWindow(
36
+ hwnd=w.hwnd,
37
+ pid=w.pid,
38
+ browser=_browser(w.browser),
39
+ browser_name=_s(w.browser_name),
40
+ caption=_s(w.caption),
41
+ title=_s(w.title),
42
+ is_foreground=bool(w.is_foreground),
43
+ )
44
+ for w in (arr[i] for i in range(count.value))
45
+ ]
46
+ finally:
47
+ if arr:
48
+ lib.bm_windows_free(arr)
49
+
50
+
51
+ def get_active_tab(browsers: BrowserFilter = None) -> Optional[Tab]:
52
+ """Active tab of the focused (or most recently focused) browser window.
53
+
54
+ Returns ``None`` when no matching browser window is open.
55
+ """
56
+ ptr = POINTER(bm_tab)()
57
+ status = lib.bm_get_active_tab(browser_mask(browsers), byref(ptr))
58
+ if status == _native.ERR_NOT_FOUND:
59
+ return None
60
+ check(status)
61
+ try:
62
+ return _tab_from_native(ptr.contents)
63
+ finally:
64
+ lib.bm_tab_free(ptr)
65
+
66
+
67
+ def current_url(browsers: BrowserFilter = None) -> Optional[str]:
68
+ """URL of the active tab, or ``None`` if no browser is open or it can't be resolved.
69
+
70
+ Shortcut for ``get_active_tab().url``.
71
+ """
72
+ tab = get_active_tab(browsers)
73
+ return tab.url if tab else None
74
+
75
+
76
+ def get_tab(window: Union[BrowserWindow, int]) -> Tab:
77
+ """Active tab of a specific window (a :class:`BrowserWindow` or an HWND).
78
+
79
+ Raises :class:`NotFoundError` if the handle is not a supported browser window.
80
+ """
81
+ hwnd = window.hwnd if isinstance(window, BrowserWindow) else int(window)
82
+ ptr = POINTER(bm_tab)()
83
+ check(lib.bm_get_tab(hwnd, byref(ptr)))
84
+ try:
85
+ return _tab_from_native(ptr.contents)
86
+ finally:
87
+ lib.bm_tab_free(ptr)
88
+
89
+
90
+ def get_all_tabs(browsers: BrowserFilter = None) -> List[Tab]:
91
+ """The active tab of every open browser window."""
92
+ tabs = []
93
+ for window in list_windows(browsers):
94
+ try:
95
+ tabs.append(get_tab(window))
96
+ except NotFoundError: # window closed meanwhile
97
+ continue
98
+ return tabs
99
+
100
+
101
+ def dump_urls(pid: int = 0) -> List[UrlCount]:
102
+ """Every URL string in a process's memory, most frequent first.
103
+
104
+ ``pid=0`` picks the most recently active browser.
105
+ """
106
+ arr = POINTER(bm_url_entry)()
107
+ count = c_uint32()
108
+ check(lib.bm_dump_urls(pid, byref(arr), byref(count)))
109
+ return _url_list(arr, count.value)
110
+
111
+
112
+ def _url_list(arr, count: int) -> List[UrlCount]:
113
+ try:
114
+ return [UrlCount(_s(arr[i].url), arr[i].count) for i in range(count)]
115
+ finally:
116
+ if arr:
117
+ lib.bm_urls_free(arr)
Binary file
browsermem/cli.py ADDED
@@ -0,0 +1,182 @@
1
+ """``browsermem`` command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import contextlib
7
+ import json
8
+ import sys
9
+ from typing import List, Optional, Sequence
10
+
11
+ from . import __version__
12
+ from .api import dump_urls, get_active_tab, list_windows
13
+ from .errors import BrowserMemError
14
+ from .forensics import MemoryImage, write_minidump
15
+ from .models import Browser, EventKind, Tab, UrlCount
16
+ from .monitor import TabMonitor
17
+
18
+ _EVENT_LABEL = {
19
+ EventKind.SNAPSHOT: "snapshot",
20
+ EventKind.TAB_CHANGED: "tab-changed",
21
+ EventKind.WINDOW_ACTIVATED: "activated",
22
+ EventKind.URL_CHANGED: "url-changed",
23
+ EventKind.WINDOW_CLOSED: "closed",
24
+ }
25
+
26
+
27
+ def _print_json(obj: object) -> None:
28
+ print(json.dumps(obj, ensure_ascii=False), flush=True)
29
+
30
+
31
+ def _print_tab(tab: Tab, as_json: bool, verbose: bool) -> None:
32
+ if as_json:
33
+ _print_json(tab.to_dict())
34
+ return
35
+ print(f"[{tab.timestamp:%H:%M:%S}] {_EVENT_LABEL[tab.event]:<11} "
36
+ f"{tab.browser_name:<15} {tab.title}")
37
+ print(f" {tab.url or '<unresolved>'} "
38
+ f"(confidence {tab.confidence:.2f}, {tab.scan_ms} ms)", flush=True)
39
+ if verbose:
40
+ for url, score in tab.candidates:
41
+ print(f" {score:6.2f} {url}")
42
+
43
+
44
+ def _print_urls(urls: List[UrlCount], limit: Optional[int], as_json: bool) -> None:
45
+ urls = urls[:limit] if limit else urls
46
+ if as_json:
47
+ _print_json([u._asdict() for u in urls])
48
+ else:
49
+ for u in urls:
50
+ print(f"{u.count:7} {u.url}")
51
+
52
+
53
+ def _browsers(values: Optional[List[str]]) -> Optional[List[Browser]]:
54
+ return [Browser.parse(v) for v in values] if values else None
55
+
56
+
57
+ def _cmd_active(a: argparse.Namespace) -> int:
58
+ tab = get_active_tab(_browsers(a.browser))
59
+ if tab is None:
60
+ print("No browser window found.", file=sys.stderr)
61
+ return 1
62
+ _print_tab(tab, a.json, a.verbose)
63
+ return 0
64
+
65
+
66
+ def _cmd_windows(a: argparse.Namespace) -> int:
67
+ windows = list_windows(_browsers(a.browser))
68
+ if a.json:
69
+ _print_json([w.to_dict() for w in windows])
70
+ else:
71
+ for w in windows:
72
+ mark = "*" if w.is_foreground else " "
73
+ print(f"{mark} {w.browser_name:<15} pid={w.pid:<6} hwnd=0x{w.hwnd:x} {w.title}")
74
+ return 0
75
+
76
+
77
+ def _cmd_watch(a: argparse.Namespace) -> int:
78
+ monitor = TabMonitor(
79
+ lambda tab: _print_tab(tab, a.json, a.verbose),
80
+ browsers=_browsers(a.browser),
81
+ all_windows=a.all,
82
+ rescan_ms=a.rescan,
83
+ debounce_ms=a.debounce,
84
+ )
85
+ if not a.json:
86
+ print("Watching browser tabs... (Ctrl+C to stop)", flush=True)
87
+ monitor.run_forever()
88
+ return 0
89
+
90
+
91
+ def _cmd_urls(a: argparse.Namespace) -> int:
92
+ _print_urls(dump_urls(a.pid), a.limit, a.json)
93
+ return 0
94
+
95
+
96
+ def _cmd_minidump(a: argparse.Namespace) -> int:
97
+ write_minidump(a.pid, a.output)
98
+ print(f"Wrote {a.output}", file=sys.stderr)
99
+ return 0
100
+
101
+
102
+ def _cmd_analyze(a: argparse.Namespace) -> int:
103
+ with MemoryImage.from_minidump(a.dump, private_only=not a.all_memory) as image:
104
+ if not a.json:
105
+ print(f"Loaded {image!r}", file=sys.stderr)
106
+ if a.title:
107
+ browser = a.browser[0] if a.browser else None
108
+ _print_tab(image.resolve(a.title, browser), a.json, a.verbose)
109
+ else:
110
+ _print_urls(image.urls(), a.limit, a.json)
111
+ return 0
112
+
113
+
114
+ def build_parser() -> argparse.ArgumentParser:
115
+ p = argparse.ArgumentParser(
116
+ prog="browsermem",
117
+ description="Recover browser tab URLs and titles from browser process memory.",
118
+ )
119
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
120
+ sub = p.add_subparsers(dest="command", required=True, metavar="COMMAND")
121
+
122
+ def common(sp: argparse.ArgumentParser, browser: bool = True) -> None:
123
+ sp.add_argument("--json", action="store_true", help="machine-readable JSON output")
124
+ sp.add_argument("-v", "--verbose", action="store_true", help="show URL candidates")
125
+ if browser:
126
+ sp.add_argument("-b", "--browser", action="append", metavar="NAME",
127
+ help="limit to a browser (chrome, edge, brave, ...); repeatable")
128
+
129
+ sp = sub.add_parser("active", help="URL of the active tab")
130
+ common(sp)
131
+ sp.set_defaults(func=_cmd_active)
132
+
133
+ sp = sub.add_parser("windows", help="list browser windows")
134
+ common(sp)
135
+ sp.set_defaults(func=_cmd_windows)
136
+
137
+ sp = sub.add_parser("watch", help="stream tab-change events")
138
+ common(sp)
139
+ sp.add_argument("--all", action="store_true", help="include background windows")
140
+ sp.add_argument("--rescan", type=int, default=0, metavar="MS",
141
+ help="rescan the focused tab every MS milliseconds")
142
+ sp.add_argument("--debounce", type=int, default=600, metavar="MS")
143
+ sp.set_defaults(func=_cmd_watch)
144
+
145
+ sp = sub.add_parser("urls", help="every URL in a live process's memory")
146
+ common(sp, browser=False)
147
+ sp.add_argument("--pid", type=int, default=0, help="process id (default: active browser)")
148
+ sp.add_argument("-n", "--limit", type=int, help="show at most N URLs")
149
+ sp.set_defaults(func=_cmd_urls)
150
+
151
+ sp = sub.add_parser("minidump", help="write a full-memory dump of a process")
152
+ sp.add_argument("pid", type=int)
153
+ sp.add_argument("output")
154
+ sp.set_defaults(func=_cmd_minidump)
155
+
156
+ sp = sub.add_parser("analyze", help="analyse a minidump offline")
157
+ common(sp)
158
+ sp.add_argument("dump", help="path to a .dmp file")
159
+ sp.add_argument("-t", "--title", help="resolve the URL for this tab title / caption")
160
+ sp.add_argument("-n", "--limit", type=int, help="show at most N URLs")
161
+ sp.add_argument("--all-memory", action="store_true",
162
+ help="scan every region, not just private writable memory")
163
+ sp.set_defaults(func=_cmd_analyze)
164
+ return p
165
+
166
+
167
+ def main(argv: Optional[Sequence[str]] = None) -> int:
168
+ for stream in (sys.stdout, sys.stderr):
169
+ with contextlib.suppress(AttributeError, ValueError): # e.g. replaced streams
170
+ stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined]
171
+ args = build_parser().parse_args(argv)
172
+ try:
173
+ return args.func(args)
174
+ except (BrowserMemError, OSError, KeyError) as e:
175
+ print(f"browsermem: error: {e}", file=sys.stderr)
176
+ return 1
177
+ except KeyboardInterrupt:
178
+ return 130
179
+
180
+
181
+ if __name__ == "__main__":
182
+ sys.exit(main())
browsermem/errors.py ADDED
@@ -0,0 +1,44 @@
1
+ """Exception hierarchy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from . import _native
6
+
7
+
8
+ class BrowserMemError(Exception):
9
+ """Base class for all browsermem errors. ``status`` is the native status code."""
10
+
11
+ def __init__(self, message: str, status: int = _native.ERR_INTERNAL):
12
+ super().__init__(message)
13
+ self.status = status
14
+
15
+
16
+ class NotFoundError(BrowserMemError):
17
+ """No matching browser window or process."""
18
+
19
+
20
+ class AccessDeniedError(BrowserMemError):
21
+ """The target process could not be opened or read (e.g. it runs elevated)."""
22
+
23
+
24
+ class StateError(BrowserMemError):
25
+ """The call is not allowed in the current state."""
26
+
27
+
28
+ _BY_STATUS = {
29
+ _native.ERR_INVALID_ARG: ValueError,
30
+ _native.ERR_NOT_FOUND: NotFoundError,
31
+ _native.ERR_ACCESS: AccessDeniedError,
32
+ _native.ERR_STATE: StateError,
33
+ }
34
+
35
+
36
+ def check(status: int) -> None:
37
+ """Raise the matching exception for a non-zero native status."""
38
+ if status == _native.OK:
39
+ return
40
+ message = _native.last_error() or f"native call failed with status {status}"
41
+ cls = _BY_STATUS.get(status, BrowserMemError)
42
+ if cls is ValueError:
43
+ raise ValueError(message)
44
+ raise cls(message, status)