Files
archived-camoufox/python/src/camoufox/addons.py
T
coffeegrind123andClaude Opus 5.5 7246d98e70 Download the default addons once under concurrent launches
add_default_addons() took `with Lock():` on a multiprocessing.Lock made
fresh for each call, which guarded nothing: two launches in one process
both found no manifest.json and both downloaded and extracted uBO into
the same directory. The lock is now one threading.Lock for the module.

A launch in another process does not see that lock, and it trusts any
addon directory holding a manifest.json. Extraction now goes into a
sibling temp directory that is renamed into place last, so the manifest
never appears before the rest of the addon.

The TypeScript launcher serializes the same check-then-extract on one
promise chain and extracts the same way.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 09:53:19 +03:00

114 lines
3.9 KiB
Python

import os
import shutil
import tempfile
from enum import Enum
from threading import Lock
from typing import List, Optional
from .exceptions import InvalidAddonPath
from .pkgman import INSTALL_DIR, unzip, webdl
# Addons are stored in a shared folder, not per-browser version
ADDONS_DIR = INSTALL_DIR / "addons"
# One lock for the module: `with Lock():` on a fresh multiprocessing.Lock per call
# guarded nothing, so concurrent launches in one process raced the same
# check-then-extract (rubenvereecken/camoufox ec08bf9).
_EXTRACT_LOCK = Lock()
class DefaultAddons(Enum):
"""
Default addons to be downloaded
"""
UBO = "https://addons.mozilla.org/firefox/downloads/latest/ublock-origin/latest.xpi"
def confirm_paths(paths: List[str]) -> None:
"""
Confirms that the addon paths are valid
"""
for path in paths:
if not os.path.isdir(path):
raise InvalidAddonPath(path)
if not os.path.exists(os.path.join(path, 'manifest.json')):
raise InvalidAddonPath(
'manifest.json is missing. Addon path must be a path to an extracted addon.'
)
def add_default_addons(
addons_list: List[str], exclude_list: Optional[List[DefaultAddons]] = None
) -> None:
"""
Adds default addons, minus any specified in exclude_list, to addons_list
"""
# Build a dictionary from DefaultAddons, excluding keys found in exclude_list
if exclude_list is None:
exclude_list = []
addons = [addon for addon in DefaultAddons if addon not in exclude_list]
with _EXTRACT_LOCK:
maybe_download_addons(addons, addons_list)
def download_and_extract(url: str, extract_path: str, name: str) -> None:
"""
Downloads and extracts an addon from a given URL to a specified path.
Extracts into a sibling temp dir and renames it into place last, so a
concurrent launch (another process, which the lock cannot see) never finds
a manifest.json in a directory whose other files are still being written.
"""
buffer = webdl(url, desc=f"Downloading addon ({name})", bar=False)
parent = os.path.dirname(extract_path)
tmp_dir = tempfile.mkdtemp(prefix=f".{name}.tmp-", dir=parent)
try:
unzip(buffer, tmp_dir, f"Extracting addon ({name})", bar=False)
shutil.rmtree(extract_path, ignore_errors=True)
os.replace(tmp_dir, extract_path)
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
def get_addon_path(addon_name: str) -> str:
"""
Returns a path to the addon in the shared addons folder.
"""
return str(ADDONS_DIR / addon_name)
def maybe_download_addons(
addons: List[DefaultAddons], addons_list: Optional[List[str]] = None
) -> None:
"""
Downloads and extracts addons from a given dictionary to a specified list
Skips downloading if the addon is already downloaded
"""
for addon in addons:
# Get the addon path
addon_path = get_addon_path(addon.name)
# Check if the addon is already extracted. A bare directory is not
# enough: a failed download leaves an empty dir behind, so require the
# manifest that confirm_paths() looks for.
if os.path.exists(os.path.join(addon_path, 'manifest.json')):
# Add the existing addon path to addons_list
if addons_list is not None:
addons_list.append(addon_path)
continue
# Addon isn't extracted, create directory and download
try:
os.makedirs(addon_path, exist_ok=True)
download_and_extract(addon.value, addon_path, addon.name)
# Add the new addon directory path to addons_list
if addons_list is not None:
addons_list.append(addon_path)
except Exception as e:
# Drop the partial directory so the next run re-downloads.
shutil.rmtree(addon_path, ignore_errors=True)
print(f"Failed to download and extract {addon.name}: {e}")