camoucore 0.1.2__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.
- camoucore/__init__.py +3 -0
- camoucore/_warnings.py +56 -0
- camoucore/cpu_affinity.py +154 -0
- camoucore/display.py +114 -0
- camoucore/download.py +207 -0
- camoucore/exceptions.py +128 -0
- camoucore/fpgen-model.json +22 -0
- camoucore/fpgen_model.py +193 -0
- camoucore/geoip.yml +40 -0
- camoucore/geolocation.py +335 -0
- camoucore/host.py +27 -0
- camoucore/ip.py +172 -0
- camoucore/locales.py +284 -0
- camoucore/product.py +55 -0
- camoucore/py.typed +0 -0
- camoucore/territoryInfo.xml +2024 -0
- camoucore/virtdisplay.py +247 -0
- camoucore/warnings.yml +14 -0
- camoucore-0.1.2.dist-info/METADATA +79 -0
- camoucore-0.1.2.dist-info/RECORD +22 -0
- camoucore-0.1.2.dist-info/WHEEL +4 -0
- camoucore-0.1.2.dist-info/licenses/LICENSE +26 -0
camoucore/__init__.py
ADDED
camoucore/_warnings.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import warnings
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Optional, Set, Type
|
|
5
|
+
|
|
6
|
+
from yaml import CLoader, load
|
|
7
|
+
|
|
8
|
+
with open(Path(__file__).parent / 'warnings.yml', 'r') as _f:
|
|
9
|
+
WARNINGS_DATA = load(_f, Loader=CLoader)
|
|
10
|
+
|
|
11
|
+
# Packages whose frames a warning skips: camoucore and every launcher built on it.
|
|
12
|
+
_INTERNAL: Set[Path] = {Path(__file__).parent}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def register_internal(package: Path) -> None:
|
|
16
|
+
_INTERNAL.add(Path(package))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _warn_from_caller(message: str, category: Type[Warning]) -> None:
|
|
20
|
+
"""Attribute the warning to the first frame outside camoucore and the
|
|
21
|
+
launchers, so it points at the user's call rather than at their internals."""
|
|
22
|
+
frame = inspect.currentframe()
|
|
23
|
+
while frame:
|
|
24
|
+
filename = Path(frame.f_code.co_filename)
|
|
25
|
+
if not any(filename.is_relative_to(package) for package in _INTERNAL):
|
|
26
|
+
break
|
|
27
|
+
frame = frame.f_back
|
|
28
|
+
|
|
29
|
+
if frame:
|
|
30
|
+
warnings.warn_explicit(
|
|
31
|
+
message,
|
|
32
|
+
category=category,
|
|
33
|
+
filename=frame.f_code.co_filename,
|
|
34
|
+
lineno=frame.f_lineno,
|
|
35
|
+
)
|
|
36
|
+
return
|
|
37
|
+
|
|
38
|
+
warnings.warn(message, category=category)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class LeakWarning(RuntimeWarning):
|
|
42
|
+
"""
|
|
43
|
+
Raised when a the user has a setting enabled that can cause detection.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
@staticmethod
|
|
47
|
+
def warn(warning: str, i_know_what_im_doing: Optional[bool] = None) -> None:
|
|
48
|
+
"""
|
|
49
|
+
Warns the user if a passed parameter can cause leaks. `warning` is the
|
|
50
|
+
message itself: each launcher words its own.
|
|
51
|
+
"""
|
|
52
|
+
if i_know_what_im_doing:
|
|
53
|
+
return
|
|
54
|
+
if i_know_what_im_doing is not None:
|
|
55
|
+
warning += '\nIf this is intentional, pass `i_know_what_im_doing=True`.'
|
|
56
|
+
_warn_from_caller(warning, LeakWarning)
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Pin the browser to as many CPU cores as the identity reports.
|
|
2
|
+
|
|
3
|
+
navigator.hardwareConcurrency is spoofed by the browser, but the number of
|
|
4
|
+
cores a page can *measure* (timing N parallel workers) is the number the OS
|
|
5
|
+
lets the browser run on. Reporting the fingerprint's value and pinning the
|
|
6
|
+
browser's CPU affinity to that many cores makes the two agree, so the drawn
|
|
7
|
+
value survives instead of being replaced by the host count.
|
|
8
|
+
|
|
9
|
+
The pin is applied to the Playwright driver process right before the browser
|
|
10
|
+
is launched -- child processes inherit the affinity mask on Linux and Windows,
|
|
11
|
+
so the browser and every content/GPU process it spawns run on the pinned set
|
|
12
|
+
-- and lifted from the driver again afterwards. macOS has no process affinity
|
|
13
|
+
API, so nothing can be pinned there and the launcher falls back to reporting
|
|
14
|
+
the host's (snapped) count.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import platform
|
|
19
|
+
import random
|
|
20
|
+
from typing import Iterable, List, Optional, Sequence
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def supported() -> bool:
|
|
24
|
+
"""Whether this host can constrain a process to a subset of its cores."""
|
|
25
|
+
system = platform.system()
|
|
26
|
+
if system == 'Linux':
|
|
27
|
+
return hasattr(os, 'sched_setaffinity')
|
|
28
|
+
return system == 'Windows'
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def host_cores() -> Optional[List[int]]:
|
|
32
|
+
"""The cores this process may run on, in order."""
|
|
33
|
+
try:
|
|
34
|
+
if hasattr(os, 'sched_getaffinity'):
|
|
35
|
+
return sorted(os.sched_getaffinity(0)) # type: ignore[attr-defined]
|
|
36
|
+
except OSError:
|
|
37
|
+
pass
|
|
38
|
+
if platform.system() == 'Windows':
|
|
39
|
+
mask = _win_get_mask(os.getpid())
|
|
40
|
+
if mask:
|
|
41
|
+
return _mask_to_cores(mask)
|
|
42
|
+
n = os.cpu_count()
|
|
43
|
+
return list(range(n)) if n else None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _pick(cores: Sequence[int], count: int) -> List[int]:
|
|
47
|
+
"""`count` adjacent cores from a random starting point (wrapping). Always
|
|
48
|
+
taking the first `count` stacked every browser on one host onto cores
|
|
49
|
+
0..count-1, so concurrent browsers measured far less parallelism than they
|
|
50
|
+
report; adjacent cores keep the SMT topology a real machine of that size
|
|
51
|
+
would have."""
|
|
52
|
+
start = random.randrange(len(cores))
|
|
53
|
+
return sorted((list(cores[start:]) + list(cores[:start]))[:count])
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def pin(pid: int, count: int) -> Optional[Sequence[int]]:
|
|
57
|
+
"""Restrict `pid` to `count` of its cores. Returns the previous set so it
|
|
58
|
+
can be handed back to `restore()`, or None if nothing was changed.
|
|
59
|
+
|
|
60
|
+
The caller must not pin the same process for two launches at once: the
|
|
61
|
+
browser inherits whatever mask the driver has when it is spawned."""
|
|
62
|
+
if count < 1 or not supported():
|
|
63
|
+
return None
|
|
64
|
+
system = platform.system()
|
|
65
|
+
if system == 'Linux':
|
|
66
|
+
try:
|
|
67
|
+
before = sorted(os.sched_getaffinity(pid)) # type: ignore[attr-defined]
|
|
68
|
+
if count >= len(before):
|
|
69
|
+
return None
|
|
70
|
+
os.sched_setaffinity(pid, set(_pick(before, count))) # type: ignore[attr-defined]
|
|
71
|
+
return before
|
|
72
|
+
except OSError:
|
|
73
|
+
return None
|
|
74
|
+
if system == 'Windows':
|
|
75
|
+
before_mask = _win_get_mask(pid)
|
|
76
|
+
if not before_mask:
|
|
77
|
+
return None
|
|
78
|
+
before = _mask_to_cores(before_mask)
|
|
79
|
+
if count >= len(before):
|
|
80
|
+
return None
|
|
81
|
+
return before if _win_set_mask(pid, _cores_to_mask(_pick(before, count))) else None
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def restore(pid: int, previous: Optional[Sequence[int]]) -> None:
|
|
86
|
+
"""Give `pid` back the cores it had before `pin()`."""
|
|
87
|
+
if not previous:
|
|
88
|
+
return
|
|
89
|
+
system = platform.system()
|
|
90
|
+
try:
|
|
91
|
+
if system == 'Linux':
|
|
92
|
+
os.sched_setaffinity(pid, set(previous)) # type: ignore[attr-defined]
|
|
93
|
+
elif system == 'Windows':
|
|
94
|
+
_win_set_mask(pid, _cores_to_mask(previous))
|
|
95
|
+
except OSError:
|
|
96
|
+
pass
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# -- Windows ---------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
_PROCESS_QUERY_INFORMATION = 0x0400
|
|
102
|
+
_PROCESS_SET_INFORMATION = 0x0200
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _mask_to_cores(mask: int) -> List[int]:
|
|
106
|
+
return [i for i in range(mask.bit_length()) if mask >> i & 1]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _cores_to_mask(cores: Iterable[int]) -> int:
|
|
110
|
+
mask = 0
|
|
111
|
+
for c in cores:
|
|
112
|
+
mask |= 1 << c
|
|
113
|
+
return mask
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _win_handle(pid: int):
|
|
117
|
+
import ctypes
|
|
118
|
+
|
|
119
|
+
k32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
120
|
+
return k32, k32.OpenProcess(_PROCESS_QUERY_INFORMATION | _PROCESS_SET_INFORMATION, False, pid)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _win_get_mask(pid: int) -> int:
|
|
124
|
+
try:
|
|
125
|
+
import ctypes
|
|
126
|
+
|
|
127
|
+
k32, h = _win_handle(pid)
|
|
128
|
+
if not h:
|
|
129
|
+
return 0
|
|
130
|
+
try:
|
|
131
|
+
proc_mask = ctypes.c_size_t()
|
|
132
|
+
sys_mask = ctypes.c_size_t()
|
|
133
|
+
if not k32.GetProcessAffinityMask(h, ctypes.byref(proc_mask), ctypes.byref(sys_mask)):
|
|
134
|
+
return 0
|
|
135
|
+
return int(proc_mask.value)
|
|
136
|
+
finally:
|
|
137
|
+
k32.CloseHandle(h)
|
|
138
|
+
except Exception:
|
|
139
|
+
return 0
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _win_set_mask(pid: int, mask: int) -> bool:
|
|
143
|
+
try:
|
|
144
|
+
import ctypes
|
|
145
|
+
|
|
146
|
+
k32, h = _win_handle(pid)
|
|
147
|
+
if not h:
|
|
148
|
+
return False
|
|
149
|
+
try:
|
|
150
|
+
return bool(k32.SetProcessAffinityMask(h, ctypes.c_size_t(mask)))
|
|
151
|
+
finally:
|
|
152
|
+
k32.CloseHandle(h)
|
|
153
|
+
except Exception:
|
|
154
|
+
return False
|
camoucore/display.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Host display geometry, in the units the browser lays its windows out in.
|
|
3
|
+
|
|
4
|
+
The browser sizes windows in **CSS pixels**, but `screeninfo` marks the process
|
|
5
|
+
per-monitor DPI aware and therefore reports **physical** pixels. Where Windows
|
|
6
|
+
display scaling is enabled the two differ by the scale factor: a 1920x1080 panel
|
|
7
|
+
at 150% is only 1280x720 CSS px. Deriving a window size from the physical
|
|
8
|
+
numbers overshoots the screen by that factor, so the window opens partly
|
|
9
|
+
off-screen.
|
|
10
|
+
|
|
11
|
+
macOS (`NSScreen.frame`) and X11 (xrandr) already report CSS pixels, so scaling
|
|
12
|
+
only ever applies on Windows.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from typing import Any, Mapping, NamedTuple, Optional
|
|
16
|
+
|
|
17
|
+
from screeninfo import get_monitors
|
|
18
|
+
|
|
19
|
+
from .host import OS_NAME
|
|
20
|
+
|
|
21
|
+
# Windows expresses DPI relative to this baseline: 144 DPI == 150% scaling.
|
|
22
|
+
_WINDOWS_BASE_DPI = 96
|
|
23
|
+
|
|
24
|
+
# shcore.h / winuser.h constants
|
|
25
|
+
_MDT_EFFECTIVE_DPI = 0
|
|
26
|
+
_MONITOR_DEFAULTTONEAREST = 2
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class DisplaySize(NamedTuple):
|
|
30
|
+
"""Size of a monitor in CSS pixels."""
|
|
31
|
+
|
|
32
|
+
width: int
|
|
33
|
+
height: int
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def has_display(env: Mapping[str, Any]) -> bool:
|
|
37
|
+
"""
|
|
38
|
+
Whether the host has a desktop session for the browser's window to open on.
|
|
39
|
+
|
|
40
|
+
DISPLAY / WAYLAND_DISPLAY only ever exist on Linux, so they cannot be the
|
|
41
|
+
sole probe: keying off DISPLAY alone skipped the screen constraints entirely
|
|
42
|
+
on Windows and macOS, where a session is always present.
|
|
43
|
+
"""
|
|
44
|
+
if OS_NAME != 'lin':
|
|
45
|
+
return True
|
|
46
|
+
return bool(env.get('DISPLAY') or env.get('WAYLAND_DISPLAY'))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def largest_display() -> Optional[DisplaySize]:
|
|
50
|
+
"""
|
|
51
|
+
Size of the roomiest attached monitor in CSS pixels, or None when the
|
|
52
|
+
display cannot be probed (no monitors, or enumeration failed).
|
|
53
|
+
"""
|
|
54
|
+
try:
|
|
55
|
+
monitors = get_monitors()
|
|
56
|
+
except Exception:
|
|
57
|
+
return None
|
|
58
|
+
if not monitors:
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
monitor = max(monitors, key=lambda m: m.width * m.height)
|
|
62
|
+
scale = _scale_factor(monitor)
|
|
63
|
+
return DisplaySize(
|
|
64
|
+
width=max(1, int(monitor.width / scale)),
|
|
65
|
+
height=max(1, int(monitor.height / scale)),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _scale_factor(monitor: Any) -> float:
|
|
70
|
+
"""
|
|
71
|
+
Physical pixels per CSS pixel on `monitor`. Always 1.0 outside Windows.
|
|
72
|
+
"""
|
|
73
|
+
if OS_NAME != 'win':
|
|
74
|
+
return 1.0
|
|
75
|
+
try:
|
|
76
|
+
dpi = _windows_monitor_dpi(monitor)
|
|
77
|
+
except Exception:
|
|
78
|
+
return 1.0 # Pre-Windows 8.1, or the shcore call is unavailable
|
|
79
|
+
return dpi / _WINDOWS_BASE_DPI if dpi > 0 else 1.0
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _windows_monitor_dpi(monitor: Any) -> int:
|
|
83
|
+
"""
|
|
84
|
+
Effective DPI of `monitor`, via shcore!GetDpiForMonitor (Windows 8.1+).
|
|
85
|
+
|
|
86
|
+
Private WinDLL handles are used rather than the process-wide `ctypes.windll`
|
|
87
|
+
cache so that annotating the prototypes cannot affect other libraries.
|
|
88
|
+
"""
|
|
89
|
+
import ctypes
|
|
90
|
+
from ctypes import wintypes
|
|
91
|
+
|
|
92
|
+
user32 = ctypes.WinDLL('user32') # type: ignore[attr-defined]
|
|
93
|
+
user32.MonitorFromPoint.argtypes = (wintypes.POINT, wintypes.DWORD)
|
|
94
|
+
user32.MonitorFromPoint.restype = wintypes.HANDLE
|
|
95
|
+
handle = user32.MonitorFromPoint(
|
|
96
|
+
wintypes.POINT(int(monitor.x), int(monitor.y)), _MONITOR_DEFAULTTONEAREST
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
shcore = ctypes.WinDLL('shcore') # type: ignore[attr-defined]
|
|
100
|
+
shcore.GetDpiForMonitor.argtypes = (
|
|
101
|
+
wintypes.HANDLE,
|
|
102
|
+
ctypes.c_int,
|
|
103
|
+
ctypes.POINTER(wintypes.UINT),
|
|
104
|
+
ctypes.POINTER(wintypes.UINT),
|
|
105
|
+
)
|
|
106
|
+
shcore.GetDpiForMonitor.restype = ctypes.c_long # HRESULT
|
|
107
|
+
dpi_x, dpi_y = wintypes.UINT(), wintypes.UINT()
|
|
108
|
+
|
|
109
|
+
hresult = shcore.GetDpiForMonitor(
|
|
110
|
+
handle, _MDT_EFFECTIVE_DPI, ctypes.byref(dpi_x), ctypes.byref(dpi_y)
|
|
111
|
+
)
|
|
112
|
+
if hresult != 0:
|
|
113
|
+
raise OSError(f'GetDpiForMonitor failed (0x{hresult & 0xFFFFFFFF:08X})')
|
|
114
|
+
return dpi_x.value
|
camoucore/download.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Downloading and unpacking release assets: browsers, the fpgen model, GeoIP databases.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
from io import BufferedWriter, BytesIO
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Callable, Dict, Optional, Union
|
|
11
|
+
from zipfile import ZipFile
|
|
12
|
+
|
|
13
|
+
import requests
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.progress import (
|
|
16
|
+
BarColumn,
|
|
17
|
+
DownloadColumn,
|
|
18
|
+
Progress,
|
|
19
|
+
SpinnerColumn,
|
|
20
|
+
TaskProgressColumn,
|
|
21
|
+
TextColumn,
|
|
22
|
+
TimeRemainingColumn,
|
|
23
|
+
TransferSpeedColumn,
|
|
24
|
+
)
|
|
25
|
+
from typing_extensions import TypeAlias
|
|
26
|
+
from yaml import CLoader, load
|
|
27
|
+
|
|
28
|
+
from .exceptions import CorruptedDownload
|
|
29
|
+
|
|
30
|
+
DownloadBuffer: TypeAlias = Union[BytesIO, tempfile._TemporaryFileWrapper, BufferedWriter]
|
|
31
|
+
|
|
32
|
+
LOCAL_DATA: Path = Path(__file__).parent
|
|
33
|
+
|
|
34
|
+
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
|
|
35
|
+
console = Console()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def rprint(msg: str, fg: Optional[str] = None, nl: bool = True) -> None:
|
|
39
|
+
"""
|
|
40
|
+
Print a styled message
|
|
41
|
+
"""
|
|
42
|
+
style = f"bold {fg}" if fg else "bold"
|
|
43
|
+
console.print(msg, style=style, end="\n" if nl else "", highlight=False)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
ProgressCallback: TypeAlias = 'Callable[[int, int], None]'
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def webdl(
|
|
50
|
+
url: str,
|
|
51
|
+
desc: Optional[str] = None,
|
|
52
|
+
buffer: Optional[DownloadBuffer] = None,
|
|
53
|
+
bar: bool = True,
|
|
54
|
+
progress_callback: Optional[ProgressCallback] = None,
|
|
55
|
+
) -> DownloadBuffer:
|
|
56
|
+
"""
|
|
57
|
+
Download a file from the given URL
|
|
58
|
+
"""
|
|
59
|
+
headers = (
|
|
60
|
+
{"Authorization": f"Bearer {GITHUB_TOKEN}"} if "api.github" in url and GITHUB_TOKEN else {}
|
|
61
|
+
)
|
|
62
|
+
response = requests.get(url, stream=True, headers=headers)
|
|
63
|
+
response.raise_for_status()
|
|
64
|
+
|
|
65
|
+
total_size = int(response.headers.get('content-length', 0))
|
|
66
|
+
block_size = 8192
|
|
67
|
+
if buffer is None:
|
|
68
|
+
buffer = BytesIO()
|
|
69
|
+
|
|
70
|
+
if progress_callback:
|
|
71
|
+
downloaded = 0
|
|
72
|
+
last_update = 0
|
|
73
|
+
for data in response.iter_content(block_size * 4):
|
|
74
|
+
size = buffer.write(data)
|
|
75
|
+
downloaded += size
|
|
76
|
+
if downloaded - last_update >= 65536 or downloaded == total_size:
|
|
77
|
+
progress_callback(downloaded, total_size)
|
|
78
|
+
last_update = downloaded
|
|
79
|
+
elif bar:
|
|
80
|
+
with Progress(
|
|
81
|
+
SpinnerColumn(),
|
|
82
|
+
TextColumn("[progress.description]{task.description}"),
|
|
83
|
+
BarColumn(),
|
|
84
|
+
DownloadColumn(),
|
|
85
|
+
TransferSpeedColumn(),
|
|
86
|
+
TimeRemainingColumn(),
|
|
87
|
+
console=console,
|
|
88
|
+
) as progress:
|
|
89
|
+
task = progress.add_task(desc or "Downloading", total=total_size)
|
|
90
|
+
for data in response.iter_content(block_size):
|
|
91
|
+
size = buffer.write(data)
|
|
92
|
+
progress.update(task, advance=size)
|
|
93
|
+
else:
|
|
94
|
+
downloaded = 0
|
|
95
|
+
for data in response.iter_content(block_size):
|
|
96
|
+
size = buffer.write(data)
|
|
97
|
+
downloaded += size
|
|
98
|
+
if total_size:
|
|
99
|
+
pct = (downloaded / total_size) * 100
|
|
100
|
+
print(f"\r{desc}: {pct:.0f}%", end="", flush=True)
|
|
101
|
+
print(f"\r{desc}: Complete" if desc else "")
|
|
102
|
+
|
|
103
|
+
buffer.seek(0)
|
|
104
|
+
return buffer
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def write_atomic(dest: Path, data: bytes, mtime: Optional[float] = None) -> None:
|
|
108
|
+
"""Write `dest` through a temporary file beside it, then replace it in one step.
|
|
109
|
+
|
|
110
|
+
The temporary file is created in dest's own directory, so it takes that
|
|
111
|
+
directory's permissions. A file staged in tempfile.mkdtemp() does not: since
|
|
112
|
+
Python 3.13 that directory is private on Windows, and a file moved out of it
|
|
113
|
+
keeps an owner-only ACL, so another account or elevation level cannot read it.
|
|
114
|
+
"""
|
|
115
|
+
tmp = dest.with_name(f".{dest.name}.{os.getpid()}.tmp")
|
|
116
|
+
try:
|
|
117
|
+
tmp.write_bytes(data)
|
|
118
|
+
if mtime is not None:
|
|
119
|
+
os.utime(tmp, (mtime, mtime))
|
|
120
|
+
os.replace(tmp, dest)
|
|
121
|
+
finally:
|
|
122
|
+
tmp.unlink(missing_ok=True)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def verify_sha256(buffer: DownloadBuffer, expected: Optional[str], desc: str = "asset") -> None:
|
|
126
|
+
"""
|
|
127
|
+
Check a downloaded buffer against its expected sha256 digest.
|
|
128
|
+
|
|
129
|
+
Raises CorruptedDownload on mismatch. Skips silently when no digest is
|
|
130
|
+
known, so installs from sources that publish no digest still work.
|
|
131
|
+
"""
|
|
132
|
+
if not expected:
|
|
133
|
+
rprint(f"Warning: no sha256 published for {desc}; skipping verification.", fg="yellow")
|
|
134
|
+
return
|
|
135
|
+
|
|
136
|
+
buffer.seek(0)
|
|
137
|
+
digest = hashlib.sha256()
|
|
138
|
+
for block in iter(lambda: buffer.read(1024 * 1024), b""):
|
|
139
|
+
digest.update(block)
|
|
140
|
+
buffer.seek(0)
|
|
141
|
+
|
|
142
|
+
actual = digest.hexdigest()
|
|
143
|
+
if actual != expected.lower():
|
|
144
|
+
raise CorruptedDownload(
|
|
145
|
+
f"Checksum mismatch for {desc}.\n"
|
|
146
|
+
f" expected sha256: {expected.lower()}\n"
|
|
147
|
+
f" actual sha256: {actual}\n"
|
|
148
|
+
"The download was corrupted or tampered with. Installation aborted."
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def unzip(
|
|
153
|
+
zip_file: DownloadBuffer,
|
|
154
|
+
extract_path: str,
|
|
155
|
+
desc: Optional[str] = None,
|
|
156
|
+
bar: bool = True,
|
|
157
|
+
) -> None:
|
|
158
|
+
"""
|
|
159
|
+
Extract a zip file to the given path
|
|
160
|
+
"""
|
|
161
|
+
with ZipFile(zip_file) as zf:
|
|
162
|
+
members = zf.infolist()
|
|
163
|
+
if bar:
|
|
164
|
+
with Progress(
|
|
165
|
+
SpinnerColumn(),
|
|
166
|
+
TextColumn("[progress.description]{task.description}"),
|
|
167
|
+
BarColumn(),
|
|
168
|
+
TaskProgressColumn(),
|
|
169
|
+
console=console,
|
|
170
|
+
) as progress:
|
|
171
|
+
task = progress.add_task(desc or "Extracting", total=len(members))
|
|
172
|
+
for member in members:
|
|
173
|
+
zf.extract(member, extract_path)
|
|
174
|
+
progress.update(task, advance=1)
|
|
175
|
+
else:
|
|
176
|
+
for i, member in enumerate(members):
|
|
177
|
+
zf.extract(member, extract_path)
|
|
178
|
+
if desc:
|
|
179
|
+
pct = ((i + 1) / len(members)) * 100
|
|
180
|
+
print(f"\r{desc}: {pct:.0f}%", end="", flush=True)
|
|
181
|
+
if desc:
|
|
182
|
+
print(f"\r{desc}: Complete")
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def flatten_single_root(extract_path: Union[str, Path]) -> None:
|
|
186
|
+
"""Move the contents of an archive's single top-level directory up.
|
|
187
|
+
|
|
188
|
+
A release zip can hold one directory (camouwolf-<version>-<release>/); the
|
|
189
|
+
launcher expects the binary and version.json directly in the install
|
|
190
|
+
directory.
|
|
191
|
+
"""
|
|
192
|
+
root = Path(extract_path)
|
|
193
|
+
entries = list(root.iterdir())
|
|
194
|
+
if len(entries) != 1 or not entries[0].is_dir() or entries[0].suffix == '.app':
|
|
195
|
+
return
|
|
196
|
+
inner = entries[0]
|
|
197
|
+
for child in inner.iterdir():
|
|
198
|
+
os.replace(child, root / child.name)
|
|
199
|
+
inner.rmdir()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def load_yaml(path: Path) -> Dict[str, Any]:
|
|
203
|
+
"""
|
|
204
|
+
Load a YAML file as a dictionary
|
|
205
|
+
"""
|
|
206
|
+
with open(path, 'r') as f:
|
|
207
|
+
return load(f, Loader=CLoader)
|
camoucore/exceptions.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Exceptions raised by camoucore. Each launcher re-exports them from its own
|
|
3
|
+
exceptions module, so a caller catches the same class either way.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CorruptedDownload(Exception):
|
|
8
|
+
"""
|
|
9
|
+
Raised when a downloaded asset does not match its expected sha256 digest.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
...
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class UnsupportedOS(Exception):
|
|
16
|
+
"""
|
|
17
|
+
Raised when the OS is not supported.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LocaleError(Exception):
|
|
24
|
+
"""
|
|
25
|
+
Raised when the locale is invalid.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class InvalidIP(Exception):
|
|
32
|
+
"""
|
|
33
|
+
Raised when an IP address is invalid.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class InvalidProxy(Exception):
|
|
40
|
+
"""
|
|
41
|
+
Raised when a proxy is invalid.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
...
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class UnknownIPLocation(LocaleError):
|
|
48
|
+
"""
|
|
49
|
+
Raised when the location of an IP is unknown.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
...
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class InvalidLocale(LocaleError):
|
|
56
|
+
"""
|
|
57
|
+
Raised when the locale input is invalid.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def invalid_input(cls, locale: str) -> 'InvalidLocale':
|
|
62
|
+
return cls(
|
|
63
|
+
f"Invalid locale: '{locale}'. Must be either a region, language, "
|
|
64
|
+
"language-region, or language-script-region."
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class UnknownTerritory(InvalidLocale):
|
|
69
|
+
"""
|
|
70
|
+
Raised when the territory is unknown.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
...
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class UnknownLanguage(InvalidLocale):
|
|
77
|
+
"""
|
|
78
|
+
Raised when the language is unknown.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
...
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class NotInstalledGeoIPExtra(ImportError):
|
|
85
|
+
"""
|
|
86
|
+
Raised when the maxminddb module is not installed.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
...
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class VirtualDisplayError(Exception):
|
|
93
|
+
"""
|
|
94
|
+
Raised when there is an error with the virtual display.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
...
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class CannotFindXvfb(VirtualDisplayError):
|
|
101
|
+
"""
|
|
102
|
+
Raised when Xvfb cannot be found.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
...
|
|
106
|
+
pass
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class CannotExecuteXvfb(VirtualDisplayError):
|
|
110
|
+
"""
|
|
111
|
+
Raised when Xvfb cannot be executed.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
...
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class VirtualDisplayNotSupported(VirtualDisplayError):
|
|
118
|
+
"""
|
|
119
|
+
Raised when the user tried to use a virtual display on a non-Linux OS.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
...
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class FpgenModelError(RuntimeError):
|
|
126
|
+
"""Raised when fpgen's pinned model cannot be installed where fpgen reads it."""
|
|
127
|
+
|
|
128
|
+
...
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"tag": "model-2/2026",
|
|
3
|
+
"asset": "model-release.zip",
|
|
4
|
+
"size": 1564571,
|
|
5
|
+
"sha256": "6530b8322cdaa4ec042921c8d9a0369a0e6e0269ba636c01a7203e4a2f109936",
|
|
6
|
+
"url": "https://github.com/scrapfly/fingerprint-generator/releases/download/model-2/2026/model-release.zip",
|
|
7
|
+
"repo": "scrapfly/fingerprint-generator",
|
|
8
|
+
"files": [
|
|
9
|
+
"fingerprint-network.json.zst",
|
|
10
|
+
"values.dat.zst",
|
|
11
|
+
"values.json.zst"
|
|
12
|
+
],
|
|
13
|
+
"file_sha256": {
|
|
14
|
+
"fingerprint-network.json.zst": "e1b0a7e60837c347f4b7d5dad4a20c356d521e0593e1bf4a8be39ea1e6a41ac4",
|
|
15
|
+
"values.dat.zst": "3da2cf0891a4a85ef6458f0fbdf9346acfcd04e5fd279a0ea22d7919e4eaf122",
|
|
16
|
+
"values.json.zst": "294decde5b6a1a52ed53d50a894130fa5c58f7cc804b78198f5c33f55b3ba66f"
|
|
17
|
+
},
|
|
18
|
+
"decompressed_sha256": {
|
|
19
|
+
"values.dat": "9ce7d16630e91654e73988f7d37e8c99987c09b9c779a7bb9dc7ad6355dcc2f0"
|
|
20
|
+
},
|
|
21
|
+
"note": "fpgen's model data, pinned. fpgen fetches this itself on first import with TLS verification DISABLED, no checksum, and a release selection that cannot reach this tag -- see fpgen_model.py. The TypeScript launcher loads the model the fpgen npm package pins (its MODEL_PIN), which typescript/tests/fpgen-model.test.ts holds equal to this file: bump both together. The sha256 values are the gate."
|
|
22
|
+
}
|