"""Bounded same-origin site capture, and zimit as an optional engine. ``zimi create --site`` walks one origin breadth-first and packages what it finds as a single ZIM. It is deliberately NOT a browsertrix competitor: no JavaScript runs, so it covers the server-rendered 70% — documentation sites, wikis, blogs, forums — and refuses the rest loudly instead of producing a ZIM full of loading spinners. The SPA check runs on the FIRST page, before a single further request, because the alternative is spending an hour to discover the output is worthless. Every page goes through the SAME pipeline as single-page capture (``creator.render_captured_page``); the crawl adds only the part that needs crawl-wide knowledge — a link whose target this crawl captured becomes internal ZIM navigation, and every other link stays absolute and external. That knowledge is why the capture is two passes: only once the captured set is final can the writer tell an internal link from an external one without guessing at the future. ALL the network is in the first pass. A page is fetched, rendered, and its images and stylesheets pulled down immediately, before the crawl moves on — so when a page is reported captured, nothing about it is still outstanding. The rendered HTML and the asset bytes go to a spool on disk (one page in memory at a time, never the whole site) and the write pass reads them back: disk-bound, seconds, no requests. That ordering is not a performance trick first and an honesty fix second, it is one change with both effects. Fetching assets in the pass that has nothing else to do — the crawl spends most of its time waiting out the politeness delay — is where they were always free; doing it there is also the only way "this page is done" can be true when it is said. Resolving links stays in the second pass, because that is the part that genuinely needs to know the future. Bounds are enforced as they are spent, not checked afterwards: pages, depth, a total fetched-byte budget shared by pages and assets, and a polite MINIMUM INTERVAL between page requests — assets fetched inside that interval ride in the gap rather than adding to it, so the page cadence the site sees is exactly what it was and the peak request rate is lower than it used to be (the old write pass fetched every asset back to back with no delay at all). robots.txt is honored — including its Crawl-delay when it asks for more patience than the flag does. SIGINT/SIGTERM finish the page in flight and then write a valid ZIM of everything captured so far, because a crawl that dies with nothing to show for forty minutes of traffic is the failure mode zimit is most complained about for. The zimit engine (``--engine zimit``) is orchestration only: find a docker CLI, run ``ghcr.io/openzim/zimit``, stream its progress, move the ZIM it produced into the library. No zimit code is vendored or imported — it is GPL-3 and pinned to a single Python minor version, and the dependency boundary and the license boundary are the same boundary. """ import contextlib import dataclasses import html as _html import itertools import json import logging import mimetypes import os import re try: # 3.11 moved the pattern parser under re import re._constants as _sre import re._parser as _sre_parse except ImportError: # Python 3.10 import sre_constants as _sre import sre_parse as _sre_parse import shutil import signal import subprocess import tempfile import threading import time import urllib.error import urllib.parse import urllib.request import urllib.robotparser import zlib from collections import deque from typing import Any, Callable, Optional import zimi.server as _srv from zimi.creator import ( OFFLINE_REFUSAL, OFFERED_ENGINES, DEFAULT_ENGINE, DEFAULT_FETCH_TIMEOUT, DEFAULT_MAX_REDIRECTS, LANGUAGE_AUTO, OtherSiteLinks, SPA_REFUSAL, _A_TAG_RE, _externalize_links, _fetch_html, _finish_output, _fmt_bytes, _HREF_RE, _page_title_from_html, _try_register, _fetch_page, current_private_guard, urlopen_guarded, _user_agent, MOBILE_VIEWPORT, with_capture_identity, zimi_user_agent, AssetSpool, capture_engine, CreateError, looks_like_spa, report_blocked, resolve_language, scratch_dir, site_illustration, spool_target, looks_like_app, ) from zimi import capturegate as _gate from zimi import subproc from zimi.blocklist import blocked_phrase from zimi.zimwriter import ( MAX_DESCRIPTION_LENGTH, guess_mime, _plural, _slug, add_standard_metadata, atomic_zim_creator, normalize_language, history_record, mask_raw_text, media_tags, scraper_string, zim_name, zim_static_item_class, ) log = logging.getLogger("zimi.crawler") # ── crawl bounds ──────────────────────────────────────────────────────────── # 0 is no page limit: the byte budget and depth still bound the crawl, and the # URL queue, sized from the page limit when there is one, is bounded by them. # Sized for the sites people actually capture (Eric, 2026-09-25: "people want # bigger zims and shouldn't have to change it"). They were 200 pages, 5 hops # and 512 MiB, and gov.uk's travel advice alone is about 2,000 pages. At the # default half-second between pages, 10,000 is about an hour and a half. DEFAULT_MAX_PAGES = 10_000 DEFAULT_MAX_DEPTH = 10 DEFAULT_MAX_BYTES = 4 * 1000**3 # every byte fetched: pages AND assets DEFAULT_DELAY = 0.5 # seconds between page requests ROBOTS_TIMEOUT = 10.0 MAX_ROBOTS_BYTES = 512 * 1024 # The frontier holds URLs we may never capture — some 404, some turn out not # to be HTML — so it needs slack beyond the page cap. It also needs a ceiling: # a crawler that remembers every URL it has ever seen is how a Pi runs out of # memory on a wiki. FRONTIER_FACTOR = 4 # The queue's ceiling whatever the page limit says: 0 (no limit) or a huge # number left it growing until memory ran out. Two million URLs is a few # hundred MB; a crawl that fills it carries on with what it has queued. FRONTIER_MAX = 2_000_000 # Query strings are the classic crawler trap: session ids, sort orders, and # tracking parameters multiply one page into thousands. The rule is that a # query is part of a page's identity ONLY when it names a page of a sequence; # everything else is dropped before the URL is fetched or remembered, so # ?sort=asc and ?sessionid=abc collapse back onto the bare path while # ?page=2 stays a page in its own right. PAGINATION_KEYS = frozenset({"page", "p", "pg", "start", "offset"}) # A link is worth fetching unless its extension already says it is not a page. # The screen names what a page is NOT, never what it is: `.php`, `.aspx` and # friends are pages, and a rule built on an allowlist of extensions would # throw away half the server-rendered web on its way past. _PAGE_MIMES = frozenset({"text/html", "application/xhtml+xml"}) _NON_PAGE_MAJORS = ("image/", "video/", "audio/", "font/") _NON_PAGE_MIMES = frozenset( { "application/gzip", "application/javascript", "application/json", "application/octet-stream", "application/pdf", "application/x-bzip2", "application/x-tar", "application/xml", "application/zip", "text/css", "text/csv", "text/javascript", "text/markdown", "text/plain", } ) ZIMIT_IMAGE = "ghcr.io/openzim/zimit:latest" _DOCKER_PROBE_TIMEOUT = 20.0 # Starting a container to read `zimit --help` is slower than inspecting one. _ZIMIT_HELP_TIMEOUT = 60.0 # warc2zim's flag for appending to the Scraper metadata; zimit forwards it. SCRAPER_SUFFIX_FLAG = "--scraper-suffix" def _noop(_message): pass # ── URL handling ──────────────────────────────────────────────────────────── def normalize_url(url): """The canonical crawl key for a URL. Drops the fragment, lowercases scheme and host, drops a default port, and keeps only the pagination query parameters (sorted, so parameter order is not an identity). See ``PAGINATION_KEYS`` for why.""" parts = urllib.parse.urlsplit(url) scheme = parts.scheme.lower() host = (parts.hostname or "").lower() port = parts.port default = (scheme == "http" and port == 80) or (scheme == "https" and port == 443) if port and not default: host = f"{host}:{port}" kept = sorted( (k, v) for k, v in urllib.parse.parse_qsl(parts.query, keep_blank_values=True) if k.lower() in PAGINATION_KEYS ) return urllib.parse.urlunsplit( (scheme, host, parts.path or "/", urllib.parse.urlencode(kept), "") ) def _scope_path(path): """A path as the scope rules compare it: percent-decoded, so ``%C3%A9``, ``%c3%a9`` and ``é`` (or ``%7E`` and ``~``) are one path, with runs of slashes collapsed so ``//`` is the root and not a folder named nothing.""" return re.sub(r"/{2,}", "/", urllib.parse.unquote(path or "/")) or "/" def _folder_of(path): """The folder a path names or sits in: itself when it ends in ``/``, else everything up to its last slash.""" return path if path.endswith("/") else path[: path.rfind("/") + 1] def path_scope(url, links=()): """The path a whole-site capture stays under, from the address a person gave, or None for the whole site. A path ending in ``/`` is a folder, always: ``/docs/guide/`` stays under itself. A last segment with an extension is a page, and the capture stays in its folder: ``/docs/intro.html`` under ``/docs/``. A last segment with neither is ambiguous, and the seed page decides it: gov.uk's ``/foreign-travel-advice`` is a section whose pages live under ``/foreign-travel-advice/``, while a wiki's ``/wiki/Main_Page`` is one page among its siblings. It is a folder when ``links`` (the seed's own links) reach at least one page under it, and a page otherwise, so the capture stays in its parent folder. The site's root is the whole site.""" path = _scope_path(urllib.parse.urlsplit(url).path) last = path.rsplit("/", 1)[-1] if path.endswith("/") or "." in last: prefix = _folder_of(path) else: folder = path + "/" under = any( _scope_path(urllib.parse.urlsplit(link).path).startswith(folder) for link in links ) prefix = folder if under else _folder_of(path) return None if prefix == "/" else prefix def crawl_scope(given_url, seed_url, seed_links, note=None): """The scope a whole-site capture keeps to, decided once the seed page is in hand, and said out loud in plain words. From the address the person typed, unless the site redirected it somewhere outside that path: ``/docs`` answered by ``/en/docs/`` is the ``/en/docs/`` section, and staying under ``/docs/`` would capture one page. A bare origin is the whole site, wherever it redirects: ``/`` answered by ``/en/home.html`` must not shrink a whole-site capture to ``/en/``.""" say = note or _noop given = _scope_path(urllib.parse.urlsplit(given_url).path) if given == "/": return None address = given_url # The widest the typed path could mean. The seed landing outside even # that is a redirect to another section, and the section is where it went. widest = ( _folder_of(given) if "." in given.rsplit("/", 1)[-1] else given.rstrip("/") + "/" ) if not in_path_scope(seed_url, widest): address = seed_url say( f"the site sent {given} to {_scope_path(urllib.parse.urlsplit(seed_url).path)}; following it" ) scope = path_scope(address, seed_links) path = _scope_path(urllib.parse.urlsplit(address).path) if scope is None: say( f"capturing the whole site: {path} is a page, and nothing it links to is under it" ) elif scope.rstrip("/") == path.rstrip("/"): say( f"staying under {scope} (the path in the address); pages elsewhere on the site are left out" ) else: say( f"staying under {scope}: {path} is a page there, and nothing it links to is under it" ) return scope def in_path_scope(url, prefix): """Whether a page is under ``prefix`` (``/blog`` itself counts for ``/blog/``). Pages only: the images, styles and scripts a page needs are fetched wherever on the site they are, or the pages would break. Compared decoded, so an encoding difference is never a different section.""" if not prefix: return True path = _scope_path(urllib.parse.urlsplit(url).path) return path.startswith(prefix) or path == prefix.rstrip("/") def _origin_of(url): parts = urllib.parse.urlsplit(url) return f"{parts.scheme.lower()}://{parts.netloc.lower()}" def upgrade_scheme(url, origin): """``url`` with its scheme raised to https when it names the crawl's own host over plain http and the crawl is https. Same host, weaker scheme is how an old site links to itself (planetmath.org's index links 9,173 entries that way); following it over https is following the site, and following it over http would be the downgrade same_origin refuses. Any other difference — host, an explicit port, https-to-http — is left alone for same_origin to judge.""" u, o = urllib.parse.urlsplit(url), urllib.parse.urlsplit(origin) if ( u.scheme.lower() == "http" and o.scheme.lower() == "https" and (u.hostname or "").lower() == (o.hostname or "").lower() and u.port in (None, 80) and o.port in (None, 443) ): return urllib.parse.urlunsplit( ("https", u.hostname.lower(), u.path, u.query, u.fragment) ) return url def same_origin(url, origin): """Strict same-origin: scheme AND host AND port. An http link on an https site is a different origin and stays external — the alternative is silently following a scheme downgrade.""" return _origin_of(normalize_url(url)) == _origin_of(normalize_url(origin)) # ── scope ─────────────────────────────────────────────────────────────────── # # Which pages a site capture walks into. The kinds and the pattern flags are # browsertrix's own (zimit's --scopeType, --scopeIncludeRx, --scopeExcludeRx, # --extraHops), so a zimit command line translates to Zimi's one to one and # Zimi is never the narrower tool. "prefix" is the default and is Zimi's smart # reading of it: the seed's section, decided from the seed (crawl_scope). SCOPES = ("prefix", "host", "domain", "any") DEFAULT_SCOPE = "prefix" # A web form can send these, and every one is matched against every link the # crawl sees: enough for any real rule, few and short enough to stay cheap. MAX_SCOPE_PATTERNS = 20 MAX_SCOPE_PATTERN_CHARS = 500 MAX_EXTRA_HOPS = 10 # Python's re has no timeout and holds the GIL, so a pattern that backtracks # without end, (a+)+ against the right link, stalls the whole server. A # quantified group that itself holds a quantifier is the shape that does it; # it is refused, read from the parsed pattern, and a link is matched on its # first characters only. MAX_MATCHED_URL_CHARS = 2048 def _sre_op(name): """A parser opcode by name, or None where this Python has no such thing (possessive repeats and atomic groups are 3.11 additions).""" return getattr(_sre, name, None) _sre_repeats = tuple( op for op in (_sre_op("MAX_REPEAT"), _sre_op("MIN_REPEAT"), _sre_op("POSSESSIVE_REPEAT")) if op ) _sre_atomic = _sre_op("ATOMIC_GROUP") def _inner(op, av): """The sub-patterns a parsed item holds, as a list of parsed lists.""" if op in _sre_repeats: return [av[2]] if op == _sre.SUBPATTERN: return [av[-1]] if _sre_atomic is not None and op == _sre_atomic: return [av] if op in (_sre.ASSERT, _sre.ASSERT_NOT): return [av[1]] if op == _sre.GROUPREF_EXISTS: return [part for part in av[1:] if part is not None] if op == _sre.BRANCH: return list(av[1]) return [] def _literal_text(parsed): """The text of an alternative that is nothing but literal characters, or None when it holds anything else (a class, a dot, a repeat, a group).""" if all(op == _sre.LITERAL for op, _av in parsed): return "".join(chr(av) for _op, av in parsed) return None def _choice_can_overlap(options): """Whether two alternatives of a choice could match the same text: equal, one the start of another, or not plain literals so that nobody can say.""" texts = [_literal_text(option) for option in options] if any(text is None for text in texts): return True return any( a.startswith(b) or b.startswith(a) for i, a in enumerate(texts) for b in texts[i + 1 :] ) def _has_overlapping_choice(parsed): for op, av in parsed: if op == _sre.BRANCH and _choice_can_overlap(av[1]): return True if any(_has_overlapping_choice(part) for part in _inner(op, av)): return True return False def _holds_a_repeat(parsed): return any( op in _sre_repeats or any(_holds_a_repeat(part) for part in _inner(op, av)) for op, av in parsed ) def _repeats_a_repeat(parsed): """Whether a parsed pattern repeats, more than once, something that itself repeats: ``(a+)+``, ``(\\w*)*``, ``(x?){2,}``. ``(ab)+`` and ``a+b+`` are fine.""" for op, av in parsed: if op in _sre_repeats and av[1] > 1 and _holds_a_repeat(av[2]): return True if any(_repeats_a_repeat(part) for part in _inner(op, av)): return True return False def _repeats_an_overlapping_choice(parsed): """Whether a parsed pattern repeats, more than once, a group holding a choice whose options can overlap: ``(a|aa)+``, ``(x|x)*y``, ``(a|ab){1,50}``. Each pass can take either way, so the ways to match multiply with the text. A repeated choice of distinct plain words is fine, and so is any choice that is not repeated: ``(?:foo|bar)+``, ``(/en|/fr)*``, ``\\.(png|jpg)$``.""" for op, av in parsed: if op in _sre_repeats and av[1] > 1 and _has_overlapping_choice(av[2]): return True if any(_repeats_an_overlapping_choice(part) for part in _inner(op, av)): return True return False # Each unbounded wildcard multiplies the ways a link can be split between # them: two are instant on a long link, three take seconds per link, and # .*.*.* never finishes. MAX_WILDCARDS = 2 def _wildcards(parsed): """How many unbounded ``.`` repeats (``.*``, ``.+``) a parsed pattern holds.""" count = 0 for op, av in parsed: if op in _sre_repeats and av[1] == _sre.MAXREPEAT and list(av[2]) == [(_sre.ANY, None)]: count += 1 else: count += sum(_wildcards(part) for part in _inner(op, av)) return count def _patterns(values, flag): """Compiled regexes from a string or a list of them. A pattern that does not compile is the user's to fix, said with the pattern in it.""" if isinstance(values, str): values = [values] out = [] for raw in values or (): text = str(raw or "").strip() if not text: continue if len(text) > MAX_SCOPE_PATTERN_CHARS: raise CreateError( f"{flag}: a pattern is longer than {MAX_SCOPE_PATTERN_CHARS} characters" ) try: out.append(re.compile(text)) parsed = _sre_parse.parse(text) except re.error as e: raise CreateError( f"{flag} {text!r} is not a valid regular expression ({e})" ) if _repeats_a_repeat(parsed): raise CreateError( f"{flag} {text!r} repeats a group that itself repeats, which can hang the crawl; .* usually says the same" ) if _repeats_an_overlapping_choice(parsed): raise CreateError( f"{flag} {text!r} repeats a choice whose options can overlap, which can hang the crawl; " "list the options so that none starts another" ) if _wildcards(parsed) > MAX_WILDCARDS: raise CreateError( f"{flag} {text!r} has more than {MAX_WILDCARDS} .* in it, which can hang the crawl; " f"use {MAX_WILDCARDS} at most, or [^/]* for one part of the path" ) if len(out) > MAX_SCOPE_PATTERNS: raise CreateError(f"{flag}: at most {MAX_SCOPE_PATTERNS} patterns") return out def _matches(patterns, url): url = url[:MAX_MATCHED_URL_CHARS] return any(p.search(url) for p in patterns) def _base_domain(host): """The domain a ``domain`` scope covers: the host without a leading ``www.``, which is what browsertrix strips before matching subdomains.""" host = (host or "").lower() return host[4:] if host.startswith("www.") else host class CrawlScope: """The pages a site capture may visit. ``scope`` is one of ``SCOPES`` (kept as ``kind``). ``include`` patterns add pages to it, ``exclude`` patterns take pages out of it and win over everything, and ``extra_hops`` lets the crawl follow that many consecutive links out of it (a page found that way is captured; its in-scope links start counting again from nothing). Patterns match the normalized URL, anywhere in it. Settled once the seed is in hand (``settle``), because "the seed's section" and "the seed's host" are about the page the site actually answered with, not the address that was typed.""" def __init__(self, scope=None, include=(), exclude=(), extra_hops=0): kind = str(scope or DEFAULT_SCOPE).strip().lower() if kind not in SCOPES: raise CreateError(f"unknown scope {kind!r}: use one of {', '.join(SCOPES)}") hops = int(extra_hops or 0) if not 0 <= hops <= MAX_EXTRA_HOPS: raise CreateError(f"extra hops must be between 0 and {MAX_EXTRA_HOPS}") self.kind = kind self.include = _patterns(include, "--include") self.exclude = _patterns(exclude, "--exclude") self.extra_hops = hops self.origin = None self.prefix = None # the section, for kind "prefix"; None is the whole host self.domain = None @property def custom(self): """Whether anything beyond the default was asked for.""" return self.kind != DEFAULT_SCOPE or bool( self.include or self.exclude or self.extra_hops ) def settle(self, given_url, seed_url, seed_links, origin, note=None): say = note or _noop self.origin = origin host = urllib.parse.urlsplit(seed_url).hostname or "" if self.kind == "prefix": self.prefix = crawl_scope(given_url, seed_url, seed_links, note) elif self.kind == "host": say(f"capturing the whole site: every page on {host}") elif self.kind == "domain": self.domain = _base_domain(host) say(f"capturing {self.domain} and its subdomains") else: say("following links to any site; depth and the limits bound the capture") if self.include: say( "also capturing pages matching " + ", ".join(p.pattern for p in self.include) ) if self.exclude: say( "never capturing pages matching " + ", ".join(p.pattern for p in self.exclude) ) if self.extra_hops: say( f"following links out of scope {_plural(self.extra_hops, 'page')} further" ) return self def excluded(self, url): return _matches(self.exclude, url) def contains(self, url): """Whether a page is in scope on its own merits (no extra hops).""" if self.excluded(url): return False if _matches(self.include, url): return True if urllib.parse.urlsplit(url).scheme.lower() not in ("http", "https"): return False if self.kind == "prefix": return same_origin(url, self.origin) and in_path_scope(url, self.prefix) if self.kind == "host": return same_origin(url, self.origin) if self.kind == "domain": host = (urllib.parse.urlsplit(url).hostname or "").lower() return host == self.domain or host.endswith("." + self.domain) return True def hops(self, url, from_hops): """The hop count a page reached from a page ``from_hops`` out of scope would carry: 0 in scope, one more out of it while extra hops allow, else None (not visited).""" if self.contains(url): return 0 if self.excluded(url) or from_hops + 1 > self.extra_hops: return None return from_hops + 1 # ── capture options ───────────────────────────────────────────────────────── # # One table names every capture option once: what its value is, what makes a # value valid, its CLI flag, zimit's name for it, which engines honor it and # whether an admin may store it as a standing default. The CLI, /manage/create, # /manage/creator, the Create page and the zimit argv all read it, so a new # option is a row and not a change to six validators. # # A parser takes what a surface has (a flag's text, a JSON value, a stored # one) and returns the value, or None for "nobody said"; it raises CreateError # with a plain sentence for a value that is wrong. MAX_TIME_LIMIT = 30 * 86400 # seconds: a month is a long enough "limit" MIN_PAGE_TIMEOUT = 1 MAX_PAGE_TIMEOUT = 600 # seconds a single page may be waited on MAX_USER_AGENT_CHARS = 512 MAX_SITEMAP_URL_CHARS = 2048 MAX_DEPTH_CEILING = 50 MAX_DELAY = 60.0 # seconds between page requests MOBILE_DEVICE = "iPhone 13" # zimit's name for the phone a mobile capture is MAX_DETAIL_CHARS = 200 # an author or a publisher: one line, not a paragraph MAX_TAG_CHARS = 60 MAX_TAGS = 30 MIN_WORKERS = 1 MAX_WORKERS = 16 _DURATION_UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400} _DURATION_RE = re.compile(r"^(\d+(?:\.\d+)?)\s*([smhd]?)$") _CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]") def parse_duration(value): """Seconds from ``90m``, ``8h``, ``1d``, ``45s`` or a plain number of seconds. 0 is "no limit"; None is "not given".""" if value is None or (isinstance(value, str) and not value.strip()): return None if isinstance(value, bool): raise CreateError("a time limit is a duration such as 90m or 8h") if isinstance(value, (int, float)): seconds = value else: found = _DURATION_RE.match(str(value).strip().lower()) if not found: raise CreateError( f"not a time limit: {str(value)[:40]} (try 90m, 8h or a number of seconds)" ) seconds = float(found.group(1)) * _DURATION_UNITS[found.group(2) or "s"] seconds = int(seconds) if not 0 <= seconds <= MAX_TIME_LIMIT: raise CreateError( f"a time limit is between 1 second and {MAX_TIME_LIMIT // 86400} days (0 for none)" ) return seconds def format_duration(seconds): """``parse_duration``'s inverse, in the largest unit that divides evenly up to hours: 28800 is 8h, 5400 is 90m.""" seconds = int(seconds or 0) if not seconds: return "0" for unit, size in (("h", 3600), ("m", 60)): if seconds % size == 0: return f"{seconds // size}{unit}" return f"{seconds}s" def _parse_int(low, high, what): def parse(value): if value is None or (isinstance(value, str) and not value.strip()): return None try: n = int(str(value).strip()) if not isinstance(value, bool) else None except ValueError: n = None if n is None or not low <= n <= high: raise CreateError(f"{what} is a whole number from {low} to {high}") return n return parse def _parse_delay(value): if value is None or (isinstance(value, str) and not value.strip()): return None try: n = float(value) except (TypeError, ValueError): n = -1.0 if isinstance(value, bool) or not 0 <= n <= MAX_DELAY: raise CreateError(f"the delay is from 0 to {MAX_DELAY:g} seconds") return n def _parse_bool(what): def parse(value): if value is None: return None if not isinstance(value, bool): raise CreateError(f"{what} must be true or false") return value return parse def _parse_scope(value): if value is None or (isinstance(value, str) and not value.strip()): return None kind = str(value).strip().lower() if kind not in SCOPES: raise CreateError(f"unknown scope {kind[:20]!r}: use one of {', '.join(SCOPES)}") return kind def _parse_bytes(value): if value is None or (isinstance(value, str) and not value.strip()): return None return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else parse_size(value) def _parse_user_agent(value): if value is None: return None text = str(value).strip() if not text: return None if len(text) > MAX_USER_AGENT_CHARS or _CONTROL_CHARS.search(text): raise CreateError( f"a user agent is one line of at most {MAX_USER_AGENT_CHARS} characters" ) return text def _parse_line(what, limit): """One line of text for the ZIM's own metadata; None when empty.""" def parse(value): if value is None: return None text = " ".join(str(value).split()) if not text: return None if len(text) > limit or _CONTROL_CHARS.search(text): raise CreateError(f"{what} is one line of at most {limit} characters") return text return parse def _parse_description(value): """The ZIM description: the openZIM convention caps it, so a longer one is refused with its length rather than cut where nobody chose.""" text = _parse_line("a description", 10**6)(value) if text and len(text) > MAX_DESCRIPTION_LENGTH: raise CreateError( f"a ZIM description is at most {MAX_DESCRIPTION_LENGTH} characters " f"and this one is {len(text)}" ) return text def _parse_tags(value): """Tags as a list: ``a;b`` from a flag or a form, or a list from the API.""" if value is None or (isinstance(value, str) and not value.strip()): return None items = re.split(r"[;,]", value) if isinstance(value, str) else value if not isinstance(items, (list, tuple)): raise CreateError("tags are words separated by semicolons: news;health") tags = [] for item in items: tag = " ".join(str(item).split()) if not tag: continue if len(tag) > MAX_TAG_CHARS or _CONTROL_CHARS.search(tag): raise CreateError(f"a tag is at most {MAX_TAG_CHARS} characters") if tag not in tags: tags.append(tag) if len(tags) > MAX_TAGS: raise CreateError(f"a ZIM has at most {MAX_TAGS} tags") return tags or None def _parse_cookies(value): """The cookies as one tidy Cookie header; the error never carries them.""" if value is None or (isinstance(value, str) and not value.strip()): return None # What a request's echo shows in place of the cookies (see # ``redacted_request``): sent back as it was, it means "none this time". # A real Cookie header always has an "=", so the two cannot be confused. if value == _gate.COOKIES_SET: return None try: return _gate.normalize_cookies(value) except _gate.GateError as e: raise CreateError(str(e)) def _parse_skip_types(value): try: return _gate.parse_skip_types(value) except _gate.GateError as e: raise CreateError(str(e)) def _parse_engine(value): if value is None or (isinstance(value, str) and not value.strip()): return None name = str(value).strip().lower() if name not in OFFERED_ENGINES: raise CreateError(f"unknown engine {name[:20]!r}: use one of {', '.join(OFFERED_ENGINES)}") return name def _parse_language(value): if value is None or (isinstance(value, str) and not value.strip()): return None code = str(value).strip().lower() if code == LANGUAGE_AUTO: return None if not re.fullmatch(r"[a-z]{2,3}", code): raise CreateError("a language is a code like eng, fra or ara") # The code the ZIM will carry: a two-letter one translated, an unknown # one refused here rather than when the ZIM is written. try: return normalize_language(code) except ValueError: raise CreateError("a language is a code like eng, fra or ara") def _show_list(sep): return lambda v: sep.join(v) def _parse_sitemap(value): """True (find it: robots.txt, else /sitemap.xml), a URL, or False (off).""" if value is None or value is False or value is True: return value text = str(value).strip() if not text: return None parts = urllib.parse.urlsplit(text) if ( parts.scheme.lower() not in ("http", "https") or not parts.netloc or len(text) > MAX_SITEMAP_URL_CHARS ): raise CreateError("a sitemap is an http(s) address, or just --sitemap to find it") return text def _stored_sitemap(value): """A standing default can say "look for one", never name a file: an address describes one site.""" if not isinstance(value, bool): raise CreateError("the stored sitemap default is on or off") return value def _show_bytes(value): return _fmt_bytes(value) if value else "0" def _show(value): return "" if value is None else str(value) _BROWSER_ENGINES = ("rendered", "alive") _OWN_CRAWLER_ENGINES = ("builtin", "rendered", "singlefile", "alive") @dataclasses.dataclass(frozen=True) class CaptureOption: key: str # the option's name in code, the API and create_defaults.json flag: str # the CLI flag (the --no- spelling of a switch is argparse's) parse: Callable[[Any], Any] show: Callable[[Any], str] = _show # a value as text, for placeholders and notes engines: Optional[tuple] = None # None: every engine honors it zimit: Optional[str] = None # zimit's flag for it, when it has one storable: bool = True # an admin may store it as a standing default stored: Optional[Callable[[Any], Any]] = None # a stricter parser for storing needs: str = "" # what a refused engine is told the option is for never_stored: str = "" # why a storable=False option is refused as a default def honored_by(self, engine): return self.engines is None or (engine or DEFAULT_ENGINE) in self.engines def for_store(self, value): return (self.stored or self.parse)(value) CAPTURE_OPTIONS = { opt.key: opt for opt in ( # The ZIM's own details. They reach the metadata of every mode that # writes a ZIM, and zimit and warc2zim are handed the same words. CaptureOption("description", "--description", _parse_description, zimit="--description", storable=False, never_stored="a description describes one ZIM"), CaptureOption("creator", "--creator", _parse_line("an author", MAX_DETAIL_CHARS), zimit="--creator"), CaptureOption("publisher", "--publisher", _parse_line("a publisher", MAX_DETAIL_CHARS), zimit="--publisher"), CaptureOption("tags", "--tags", _parse_tags, _show_list(";"), zimit="--tags", storable=False, never_stored="tags describe one ZIM"), CaptureOption("time_limit", "--time-limit", parse_duration, format_duration, zimit="--timeLimit"), CaptureOption("sitemap", "--sitemap", _parse_sitemap, lambda v: "on" if v else "off", zimit="--useSitemap", stored=_stored_sitemap), CaptureOption("user_agent", "--user-agent", _parse_user_agent, zimit="--userAgent"), CaptureOption("mobile", "--mobile", _parse_bool("mobile"), lambda v: "on" if v else "off", zimit="--mobileDevice"), CaptureOption( "page_timeout", "--page-timeout", _parse_int(MIN_PAGE_TIMEOUT, MAX_PAGE_TIMEOUT, "the page timeout"), lambda v: f"{v}s", engines=_BROWSER_ENGINES + ("zimit",), zimit="--pageLoadTimeout", needs="the engines that drive a browser", ), # A credential: sent to the seed's host and nowhere else, kept nowhere. # zimit's browser runs outside Zimi and SingleFile has no scoped way to # take one, so both refuse it: a capture that was meant to be signed in # must not quietly run signed out. CaptureOption( "cookies", "--cookies", _parse_cookies, lambda v: _gate.COOKIES_SET, engines=("builtin", "rendered", "alive"), needs="the fast, rendered and alive engines", storable=False, never_stored="cookies are a credential and are never stored", ), # What a capture does not carry. Zimit has no flag that means these. CaptureOption( "skip_types", "--skip", _parse_skip_types, _show_list(","), engines=("builtin", "rendered", "alive", "zimit"), needs="the fast, rendered and alive engines", ), CaptureOption( "max_file_bytes", "--max-file-size", _parse_bytes, _show_bytes, engines=("builtin", "rendered", "alive", "zimit"), needs="the fast, rendered and alive engines", ), # The crawl's own frontier is one walk with one politeness clock; more # at once is zimit's (browsertrix's) to do. CaptureOption( "workers", "--workers", _parse_int(MIN_WORKERS, MAX_WORKERS, "the number of workers"), _show, engines=("zimit",), zimit="--workers", needs="the zimit engine", ), # What Create's pickers start on. Not options of a capture: the capture # already has fields for both, and these are what silence means there. CaptureOption("engine", "--engine", _parse_engine), CaptureOption("language", "--language", _parse_language), # Already options of their own, and now storable as defaults too. Their # engines and flags are handled where they always were; the rows are # what a stored value is checked by. CaptureOption("scope", "--scope", _parse_scope), CaptureOption("max_pages", "--max-pages", _parse_int(0, 10**9, "the page limit"), _show), CaptureOption("max_depth", "--max-depth", _parse_int(0, MAX_DEPTH_CEILING, "the depth"), _show), CaptureOption("max_bytes", "--max-bytes", _parse_bytes, _show_bytes, engines=_OWN_CRAWLER_ENGINES), CaptureOption("delay", "--delay", _parse_delay, lambda v: f"{v:g}s", engines=_OWN_CRAWLER_ENGINES), CaptureOption("block_ads", "--block-ads", _parse_bool("block_ads"), lambda v: "on" if v else "off", engines=_BROWSER_ENGINES), CaptureOption("capture_variants", "", _parse_bool("capture_variants"), lambda v: "on" if v else "off", engines=("rendered",)), # Not an option of a capture at all: whether the web may point one at # a private address. Stored by an admin, never sent with a job. CaptureOption("allow_private", "", _parse_bool("allow_private"), lambda v: "on" if v else "off"), ) } # What a request or a command line may carry per capture: the five options this # table was made for. The rest are stored defaults, or have their own fields. NEW_OPTION_KEYS = ( "time_limit", "sitemap", "user_agent", "mobile", "page_timeout", "cookies", "skip_types", "max_file_bytes", "workers", ) # The ones a capture of a single page, or of several, also has: how it presents # itself, how long a browser waits, what it sends and what it leaves out. The # rest (time limit, sitemap, workers) are about walking a site. PAGE_OPTION_KEYS = ( "user_agent", "mobile", "page_timeout", "cookies", "skip_types", "max_file_bytes", ) # The ZIM's own details: options of any mode that writes a ZIM, not only of a # site capture. DETAIL_KEYS = ("description", "creator", "publisher", "tags") # Stored, but not applied to a capture by fill_stored_defaults: the pickers # that read them, and the admin's switch. PICKER_KEYS = ("engine", "language") def capture_option_value(key, raw): """A per-capture value, checked: the parsed value or None for "not given".""" return CAPTURE_OPTIONS[key].parse(raw) def _engines_phrase(opt): return opt.needs or "every engine" def capture_options(raw, engine, *, strict, keys=NEW_OPTION_KEYS): """The new options a surface was given, parsed, with the engine's say. An option the engine cannot honor is refused when ``strict`` (a flag typed on the command line describes something that will not happen) and dropped otherwise (a web form whose engine picker moved on after the field was filled). Only what was given comes back.""" out = {} for key in keys: value = capture_option_value(key, raw.get(key)) if value is None: continue opt = CAPTURE_OPTIONS[key] if not opt.honored_by(engine): if strict: raise CreateError( f"{opt.flag} applies to {_engines_phrase(opt)}, which " f"{engine or DEFAULT_ENGINE} is not" ) continue out[key] = value return out def create_defaults_path(): return os.path.join(_srv.ZIMI_DATA_DIR, "create_defaults.json") def stored_defaults(path=None): """Every stored default that is still valid, by key. A hand-edited value the table does not accept falls back to the factory (it is not in the result), the way a stored boolean that is not a boolean always has.""" try: with open(path or create_defaults_path(), "r", encoding="utf-8") as fh: saved = json.load(fh) except (OSError, ValueError): return {} if not isinstance(saved, dict): return {} out = {} for key, value in saved.items(): opt = CAPTURE_OPTIONS.get(key) if opt is None or not opt.storable: continue try: value = opt.for_store(value) except CreateError: continue if value is not None and value != []: out[key] = value return out def validate_stored_defaults(updates): """What ``/manage/creator`` was asked to store, checked by the same rows. An empty string or null clears a default. Raises CreateError.""" out = {} for key, value in updates.items(): opt = CAPTURE_OPTIONS.get(key) if opt is None or not opt.storable: raise CreateError( (opt and opt.never_stored) or f"{str(key)[:40]!r} is not a setting that can be stored" ) out[key] = None if value is None or value in ("", []) else opt.for_store(value) return out def fill_stored_defaults(opts, engine, defaults=None, keys=None): """Capture value, then stored default, then factory: ``opts`` (what the capture asked for) gets every stored default it said nothing about and the engine honors. The factory is the absence of a key.""" stored = stored_defaults() if defaults is None else defaults for key, value in stored.items(): if key == "allow_private" or key in PICKER_KEYS or opts.get(key) is not None: continue if keys is not None and key not in keys: continue if CAPTURE_OPTIONS[key].honored_by(engine): opts[key] = value return opts def storable_keys(): """The options an admin may store, in the table's order. ``allow_private`` is the admin's own switch and is not among them.""" return [k for k, o in CAPTURE_OPTIONS.items() if o.storable and k != "allow_private"] def factory_text(): """What a capture uses for each storable option when nothing is stored, as display text; "" where the factory is none, no limit, the engine's own, or detection (engine "" is the fast one, language "" is auto).""" try: from zimi.renderer import BLOCK_ADS_DEFAULT, NAV_TIMEOUT, VARIANT_SWEEP_DEFAULT except Exception: BLOCK_ADS_DEFAULT = VARIANT_SWEEP_DEFAULT = True NAV_TIMEOUT = 45.0 onoff = lambda v: "on" if v else "off" # noqa: E731 text = { "creator": "Zimi", "publisher": "Zimi", "sitemap": "off", "mobile": "off", "user_agent": zimi_user_agent(), "page_timeout": CAPTURE_OPTIONS["page_timeout"].show(int(NAV_TIMEOUT)), "scope": DEFAULT_SCOPE, "max_pages": str(DEFAULT_MAX_PAGES), "max_depth": str(DEFAULT_MAX_DEPTH), "max_bytes": _show_bytes(DEFAULT_MAX_BYTES), "delay": CAPTURE_OPTIONS["delay"].show(DEFAULT_DELAY), "block_ads": onoff(BLOCK_ADS_DEFAULT), "capture_variants": onoff(VARIANT_SWEEP_DEFAULT), "workers": "1", } return {k: text.get(k, "") for k in storable_keys()} def zim_details(raw, *, stored=True): """The ZIM's own details a surface was given (description, creator, publisher, tags), checked, with the stored defaults behind them for author and publisher: the capture's value, then the stored default, then the factory (which is the absence of a key). Only what is set comes back. A folder asks for ``stored=False``: its zimi.txt comes between the two, so ``create_folder_zim`` reads the stored default itself.""" out = {} for key in DETAIL_KEYS: value = CAPTURE_OPTIONS[key].parse(raw.get(key)) if value is not None: out[key] = value if stored: fill_stored_defaults(out, None, {k: v for k, v in stored_defaults().items() if k in DETAIL_KEYS}) return out def detail_kwargs(details): """``zim_details`` as the keyword arguments the ``create_*_zim`` functions take (the author is ``creator_name`` there).""" kwargs = {k: details[k] for k in DETAIL_KEYS if k != "creator" and details.get(k)} if details.get("creator"): kwargs["creator_name"] = details["creator"] return kwargs def redacted_request(data): """A copy of a capture request that is safe to keep and to show: any cookies are replaced by the word ``set``.""" out = dict(data) if out.get("cookies"): out["cookies"] = _gate.COOKIES_SET return out def default_placeholders(defaults=None): """The stored defaults as text, for a form to show what silence means.""" stored = stored_defaults() if defaults is None else defaults return {k: CAPTURE_OPTIONS[k].show(v) for k, v in stored.items()} class _RobotsBook: """robots.txt for every origin a crawl reaches, read once each. A crawl that keeps to its origin only ever holds the one the caller read.""" def __init__(self, origin, robots, ignore, timeout, note): self._by_origin = {_origin_of(normalize_url(origin)): robots} self._ignore = ignore self._timeout = timeout self._note = note def allows(self, url): if self._ignore: return True origin = _origin_of(normalize_url(url)) if origin not in self._by_origin: self._by_origin[origin] = load_robots( origin, timeout=self._timeout, note=self._note ) return _robots_allows(self._by_origin[origin], url) # ── sitemap seeds ─────────────────────────────────────────────────────────── # # A sitemap lists pages the links never reach (an orphaned page, a deep # archive). The pages it names are seeded at depth 1 when the crawl's scope # admits them, and are walked like any other link from there. It is read with a # regex for , not an XML parser: the file is the site's, the parser's # entity handling is not worth trusting with it, and is all there is to # read. Every bound below is a hard one. MAX_SITEMAP_BYTES = 10 * 1024**2 # per file, once decompressed MAX_SITEMAP_URLS = 50_000 # in all, which is the protocol's own per-file ceiling MAX_SITEMAP_FILES = 25 # fetched, an index's children included MAX_SITEMAP_DEPTH = 2 # an index may list indexes, once DEFAULT_SITEMAP_PATH = "/sitemap.xml" _SITEMAP_INDEX_RE = re.compile(r"<(?:[\w-]+:)?sitemapindex\b", re.I) _CDATA_RE = re.compile(r"^\s*\s*$", re.S) _GZIP_MAGIC = b"\x1f\x8b" def _sitemap_text(data): """A sitemap's text: gunzipped when it is gzip (named .gz or not), and never more than ``MAX_SITEMAP_BYTES`` of it, so a compressed bomb is refused rather than expanded.""" if data[:2] == _GZIP_MAGIC: inflater = zlib.decompressobj(16 + zlib.MAX_WBITS) try: data = inflater.decompress(data, MAX_SITEMAP_BYTES) except zlib.error: raise CreateError("a sitemap that is not valid gzip") if inflater.unconsumed_tail: raise CreateError(f"a sitemap over {_fmt_bytes(MAX_SITEMAP_BYTES)}") elif len(data) > MAX_SITEMAP_BYTES: raise CreateError(f"a sitemap over {_fmt_bytes(MAX_SITEMAP_BYTES)}") return data.decode("utf-8", errors="replace") _LOC_OPEN = re.compile(r"<(?:[\w-]{1,40}:)?loc(?=[\s>/])[^<>]{0,300}>", re.I) _LOC_CLOSE = re.compile(r"", re.I) def sitemap_locs(text): """``(is_index, [url, ...])`` from a sitemap document. A linear scan, not one regex over the whole text: a pattern with ``.*?`` and a closing tag that never comes is quadratic or worse on hostile input, and Python's ``re`` holds the GIL while it runs. Every tag is matched at a position with a bounded pattern, so the cost is the text's length, and at most ``MAX_SITEMAP_URLS`` addresses are taken.""" locs = [] pos = 0 while len(locs) < MAX_SITEMAP_URLS: found = _LOC_OPEN.search(text, pos) if not found: break start = found.end() if text[start - 2 : start] == "/>": pos = start # : an empty tag, not one that opens continue close = None probe = text.find(" bytes`` is the read, a parameter so the private-address rule can wrap it.""" origin = _origin_of(seed_url) if fetch is None: def fetch(url): return _fetch_page(url, timeout=timeout, max_redirects=DEFAULT_MAX_REDIRECTS)[1] if spec is True: # A crawl that ignores robots rules still reads what robots.txt says # about sitemaps: reading a file is not obeying it. book = robots or (load_robots(origin, timeout=timeout, note=note) if ignore_robots else None) roots = list(book.site_maps() or []) if book else [] roots = roots or [origin + DEFAULT_SITEMAP_PATH] else: roots = [spec] urls, seen_files, files = [], set(), 0 todo = deque((root, 0) for root in roots) while todo and len(urls) < MAX_SITEMAP_URLS: sitemap, level = todo.popleft() if sitemap in seen_files: continue if files >= MAX_SITEMAP_FILES: note(f"sitemap: stopped after {MAX_SITEMAP_FILES} files") break seen_files.add(sitemap) files += 1 try: is_index, locs = sitemap_locs(_sitemap_text(fetch(sitemap))) except CreateError as e: note(f"sitemap: could not read {sitemap} ({str(e).splitlines()[0]})") continue if is_index: if level >= MAX_SITEMAP_DEPTH - 1: note(f"sitemap: {sitemap} nests deeper than {MAX_SITEMAP_DEPTH} levels; not followed") continue # A child must live where its index does: a sitemap that sends the # crawl to another host to read is not describing this site. todo.extend((c, level + 1) for c in locs if same_origin(c, _origin_of(sitemap))) else: urls.extend(locs[: MAX_SITEMAP_URLS - len(urls)]) if not urls: note("sitemap: no pages listed; crawling by links") elif len(urls) >= MAX_SITEMAP_URLS: note(f"sitemap: using the first {MAX_SITEMAP_URLS:,} pages it lists") return urls def looks_like_a_page(url): """False when the URL's own extension already says it is not a document (``.png``, ``.zip``, ``.css``). Extensionless and server-script URLs pass — the Content-Type check after the fetch is the real gate; this one only exists to avoid spending a request to learn what the name already said.""" guess = guess_mime(urllib.parse.urlsplit(url).path, fallback=None) if not guess or guess in _PAGE_MIMES: return True return not (guess.startswith(_NON_PAGE_MAJORS) or guess in _NON_PAGE_MIMES) def extract_links(page, base_url): """Every ```` on the page, absolute against ``base_url``. A ```` element is deliberately ignored: asset resolution already resolves against the fetched URL, and honoring it here alone would make links and assets disagree about what a relative reference means.""" out = [] # Blind to