okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ok-refused 5fdb9aa4a into f-own-intc7ec1e8fe

main
24.3 KiB492 linesraw
1"""Fetching update files: small documents, and large archives with resume and progress.
2
3This is the only network code of the update path. It is reached from `strata update` / `strata components update` and
4the app's explicit "Update" step, never from a start or a serve: ``require_acquisition`` is called by the caller before
5anything here runs, and it refuses under ``STRATA_NO_ACQUIRE``.
6
7A *source* is where the feed lives: an ``https://`` URL (or ``http://`` to a loopback address, which is how a local test
8feed is served), a ``file://`` URL, or a plain folder / file path. Everything the feed points at is resolved against it
9by `resolve_ref`, which refuses a reference that leaves the source.
10"""
11
12from __future__ import annotations
13
14import hashlib
15import http.client
16import ipaddress
17import os
18import re
19import shutil
20import threading
21import time
22import email.utils
23import datetime as _dt
24import errno
25import urllib.error
26import urllib.parse
27import urllib.request
28from pathlib import Path
29from typing import Callable
30
31from strata_control import netpolicy
32from strata_control import tls
33
34tls.install()      # #3722: the operating system's certificates, like the browser
35
36CHUNK = 1 << 20
37WAITED_S = 0.002                 # a read that took longer than this had to wait for the server
38# errors on the DESTINATION (the .part file) that waiting cannot cure: raised at once, as before the network rule, never retried
39# (a full disk, a quota, a read-only drive, no permission); any other write error (EIO on a flaky drive, a share that drops) is retried
40_DEST_ERRNOS = {e for e in (errno.ENOSPC, getattr(errno, "EDQUOT", None), errno.EROFS, errno.EACCES, errno.EPERM) if e is not None}
41_DEST_OPEN_ERRORS = (PermissionError, IsADirectoryError, NotADirectoryError, FileNotFoundError)
42
43
44def _destination(exc: BaseException) -> BaseException:
45    exc.strata_destination = True        # read in _transfer: a plain TransferError, not an Interrupted
46    return exc
47
48
49# The sentence for a .part file that cannot be written because its drive is full, over quota or read-only (owner 11-11: plain words, which
50# folder, how much more, that the part is kept). The error's own words stay at the end in brackets, as before, for a report.
51# Owner-approved wording (11-11, par\OWNER-WORDING-1111.md): no word changes without a new approval.
52NO_ROOM_WORDS = {
53    "full": "The drive that holds {folder} is full, so {what} stopped downloading after {got} of {size}. It needs about {need} more there{free}. "
54            "Free up space on that drive, then try again; {kept}.",
55    "free": " ({free} is free now)",
56    "quota": "Your storage quota on the drive that holds {folder} is used up, so {what} stopped downloading after {got} of {size}. It needs about "
57             "{need} more there. Delete files you no longer need, or ask whoever looks after this computer for a larger quota, then try again; "
58             "{kept}.",
59    "read_only": "The drive that holds {folder} can only be read right now, not written, so {what} could not be saved there. Restart the computer "
60                 "and try again; if the drive stays read-only, check it for errors. {kept_cap}.",
61    "kept": "the part already downloaded is kept and the next try continues from there",
62    "none_kept": "nothing was saved yet",
63}
64
65
66def _size_words(n: int) -> str:
67    """Bytes for a person: "1.9 GB", "412 MB"; "1 MB" for any non-zero amount below it, "0 MB" for none."""
68    if n <= 0:
69        return "0 MB"
70    return f"{n / 1e9:.1f} GB" if n >= 1e9 else f"{max(1, round(n / 1e6))} MB"
71
72
73def _no_room_kind(exc: BaseException) -> str | None:
74    """"full", "quota" or "read_only" for a destination error that has its own sentence; None for any other (no permission keeps its words)."""
75    if not isinstance(exc, OSError):
76        return None
77    if exc.errno == errno.ENOSPC or getattr(exc, "winerror", None) in (112, 39):    # ERROR_DISK_FULL, ERROR_HANDLE_DISK_FULL
78        return "full"
79    if getattr(errno, "EDQUOT", None) is not None and exc.errno == errno.EDQUOT:
80        return "quota"
81    if exc.errno == errno.EROFS:
82        return "read_only"
83    return None
84
85
86def no_room_words(exc: BaseException, partial: Path, got: int, size: int, what: str, location: str = "") -> str | None:
87    """The plain sentence for a full / over-quota / read-only destination, ending with the error's own words; None for any other error.
88    `what` names the file ("the engine 0.1.59 (cuda)"); the generic "the download" becomes "the file <name>". The free space is read once,
89    here, and left out when it cannot be read."""
90    kind = _no_room_kind(exc)
91    if kind is None:
92        return None
93    folder = str(Path(partial).parent)
94    if not what or what == "the download":
95        name = urllib.parse.urlparse(location).path.rsplit("/", 1)[-1] if location else ""
96        what = f"the file {name}" if name else "the download"
97    free = ""
98    if kind == "full":
99        try:
100            free = NO_ROOM_WORDS["free"].format(free=_size_words(shutil.disk_usage(folder).free))
101        except (OSError, ValueError):
102            free = ""
103    kept = NO_ROOM_WORDS["kept" if got > 0 else "none_kept"]
104    said = NO_ROOM_WORDS[kind].format(folder=folder, what=what, got=_size_words(got), size=_size_words(size),
105                                      need=_size_words(max(0, size - got)), free=free, kept=kept, kept_cap=kept[:1].upper() + kept[1:])
106    return f"{said}\n({type(exc).__name__}: {exc})"      # on a line of its own: a terminal never breaks it in two
107
108
109SMALL_LIMIT = 8 << 20
110ENV_ALLOW_HTTP = "STRATA_UPDATE_ALLOW_HTTP"
111
112
113class TransferError(RuntimeError):
114    """Something could not be fetched. `resumable` says whether a partial file was kept for the next attempt."""
115
116    def __init__(self, message: str, *, resumable: bool = False):
117        super().__init__(message)
118        self.resumable = resumable
119
120
121class ChecksumMismatch(TransferError):
122    """The bytes arrived but are not the bytes the signed feed names. The partial file was deleted."""
123
124
125class Unreachable(TransferError):
126    """The server did not answer, or this computer could not connect (strata_control/netpolicy.py). `failure` is the NetFailure; str() is its
127    plain sentence."""
128
129    def __init__(self, failure: "netpolicy.NetFailure", what: str = "the download", resumable: bool = False):
130        super().__init__(failure.headline(what) + " " + failure.next_step(), resumable=resumable)
131        self.failure, self.what = failure, what
132
133
134class Interrupted(TransferError):
135    """A connection broke or stalled after the server had answered; `download` resumes it while bytes keep coming."""
136
137
138class Cancelled(TransferError):
139    """The caller asked to stop. The partial file is kept."""
140
141    def __init__(self, message: str = "cancelled"):
142        super().__init__(message, resumable=True)
143
144
145def _is_loopback(host: str) -> bool:
146    if host in ("localhost",):
147        return True
148    try:
149        return ipaddress.ip_address(host).is_loopback
150    except ValueError:
151        return False
152
153
154def kind_of(source: str) -> str:
155    """"http", "https", "file" or "path"."""
156    parsed = urllib.parse.urlparse(source)
157    if len(parsed.scheme) == 1:                     # a Windows drive letter
158        return "path"
159    if parsed.scheme in ("http", "https", "file"):
160        return parsed.scheme
161    if parsed.scheme:
162        raise TransferError(f"the update source scheme {parsed.scheme!r} is not supported (https, a loopback http, file or a folder)")
163    return "path"
164
165
166def check_url_policy(url: str, environ=None) -> None:
167    environ = os.environ if environ is None else environ
168    parsed = urllib.parse.urlparse(url)
169    if parsed.scheme == "https":
170        return
171    if parsed.scheme == "http":
172        if _is_loopback(parsed.hostname or "") or environ.get(ENV_ALLOW_HTTP) == "1":
173            return
174        raise TransferError(f"{url} is plain http; updates are fetched over https (a loopback address is the only exception)")
175    raise TransferError(f"{url} is not an https address")
176
177
178def _local_path(source: str) -> Path:
179    if source.startswith("file:"):
180        parsed = urllib.parse.urlparse(source)
181        path = urllib.request.url2pathname(parsed.path)
182        if os.name == "nt" and path.startswith(("/", "\\")) and len(path) > 2 and path[2] == ":":
183            path = path[1:]
184        return Path(path)
185    return Path(source)
186
187
188def base_of(source: str) -> str:
189    """The folder / URL prefix that references in the feed are relative to."""
190    kind = kind_of(source)
191    if kind in ("http", "https"):
192        return source.rsplit("/", 1)[0] + "/"
193    path = _local_path(source)
194    return str(path.parent if path.suffix else path)
195
196
197def resolve_ref(base: str, ref: str, environ=None) -> str:
198    """The absolute location a feed reference points at. A relative reference stays inside the base; an absolute one must
199    pass the URL policy (https, or a loopback http) and, for a local base, may not be a remote address at all."""
200    if not isinstance(ref, str) or not ref or "\0" in ref or "\\" in ref:
201        raise TransferError(f"the feed contains an unusable file reference {ref!r}")
202    parsed = urllib.parse.urlparse(ref)
203    kind = kind_of(base)
204    if parsed.scheme:
205        if kind in ("path", "file"):
206            raise TransferError(f"the local feed refers to a remote address ({ref}); a local feed may only name files inside its own folder")
207        check_url_policy(ref, environ)
208        return ref
209    if ref.startswith("/") or ".." in ref.split("/"):
210        raise TransferError(f"the feed reference {ref!r} leaves the feed's own location")
211    if kind in ("http", "https"):
212        return urllib.parse.urljoin(base if base.endswith("/") else base + "/", ref)
213    root = _local_path(base).resolve()
214    target = (root / ref).resolve()
215    if root != target and root not in target.parents:
216        raise TransferError(f"the feed reference {ref!r} leaves the feed's own folder")
217    return str(target)
218
219
220class _PolicyRedirects(urllib.request.HTTPRedirectHandler):
221    def redirect_request(self, req, fp, code, msg, headers, newurl):
222        check_url_policy(newurl)
223        return super().redirect_request(req, fp, code, msg, headers, newurl)
224
225
226_opener = netpolicy.build_opener(_PolicyRedirects)      # the network rule: the connection phase is bounded, a stalled read ends after 60 s
227_USER_AGENT = "strata-updater/1"
228
229
230_SERVER_DATE: list = []
231
232
233def server_date():
234    """The time the update server named in the `Date` header of its last answer (a timezone-aware datetime), or None. It lets a feed that
235    looks expired be told from a PC whose clock is wrong."""
236    return _SERVER_DATE[-1] if _SERVER_DATE else None
237
238
239def _remember_date(response) -> None:
240    try:
241        parsed = email.utils.parsedate_to_datetime(response.headers.get("Date") or "")
242        if parsed is not None:
243            _SERVER_DATE[:] = [parsed if parsed.tzinfo else parsed.replace(tzinfo=_dt.timezone.utc)]
244    except (TypeError, ValueError):
245        pass
246
247
248FIRST_TRY_SECONDS = 12.0
249
250
251def _open_small(request, timeout: float, limit: int) -> bytes:
252    with _opener.open(request, timeout=timeout) as response:
253        _remember_date(response)
254        return response.read(limit + 1)
255
256
257def read_small(location: str, *, limit: int = SMALL_LIMIT, timeout: float = 30, say=None, automatic: bool = False) -> bytes:
258    """A small document (the feed, its signature). Larger than `limit` is refused, not truncated.
259    A web address gets one more try when the first one times out or the connection fails: about one request in 25 to github.com hung for the whole
260    timeout on a PC whose next 24 answered in half a second (measured on a 3060 PC: the first-run card said "offline" a moment before the install's
261    own read worked). The first try therefore waits at most 12 s; the second the full `timeout`."""
262    kind = kind_of(location)
263    _SERVER_DATE.clear()                                 # only the answer of this read counts
264    try:
265        if kind in ("http", "https"):
266            check_url_policy(location)
267            request = urllib.request.Request(location, headers={"User-Agent": _USER_AGENT, "Cache-Control": "no-cache"})
268            try:                                         # the network rule: 12 s, then one retry with the full timeout; clear failures at once
269                def attempt(req, timeout):
270                    _SERVER_DATE.clear()                 # only the answer of the try that worked counts
271                    return _open_small(req, timeout, limit)
272                data = netpolicy.open_url(attempt, request, limits=(min(timeout, FIRST_TRY_SECONDS), timeout), say=say,
273                                        automatic=automatic)   # automatic: a read nobody asked for (netpolicy rule 4b)   # say: the waiting line (W1)
274            except netpolicy.NetFailure as failure:
275                raise Unreachable(failure, "the update feed") from None
276        else:
277            path = _local_path(location)
278            if path.stat().st_size > limit:
279                raise TransferError(f"{location} is larger than {limit} bytes")
280            data = path.read_bytes()
281    except TransferError:
282        raise
283    except urllib.error.HTTPError as exc:
284        raise TransferError(f"the update server answered {exc.code} for {location}") from None
285    except (urllib.error.URLError, OSError, TimeoutError) as exc:
286        reason = getattr(exc, "reason", exc)
287        hint = ""
288        if tls.is_certificate_error(exc):
289            raise TransferError(tls.explain(tls.host_of(location))) from None
290        raise TransferError(f"could not read {location} ({type(exc).__name__}: {reason}){hint}") from None
291    if len(data) > limit:
292        raise TransferError(f"{location} is larger than {limit} bytes")
293    return data
294
295
296def sha256_file(path: Path) -> str:
297    digest = hashlib.sha256()
298    with Path(path).open("rb") as stream:
299        for block in iter(lambda: stream.read(CHUNK), b""):
300            digest.update(block)
301    return digest.hexdigest()
302
303
304def download(location: str, partial: Path, *, size: int, sha256: str,
305             progress: Callable[[int, int], None] | None = None,
306             cancel: threading.Event | None = None, timeout: float = 60, what: str | None = None,
307             say: Callable[[str], None] | None = None) -> Path:
308    """Fetch `location` into `partial` (resuming what is there) and return it once it has exactly `size` bytes and the
309    SHA-256 `sha256`. An interrupted transfer keeps the partial file (`TransferError.resumable`); a complete file with the
310    wrong hash is deleted, because resuming cannot repair it.
311
312    The network rule (strata_control/netpolicy.py): a server that does not answer the first request fails in about 44 s (`Unreachable`, with
313    `say` given a line naming the host after 5 s); once bytes have come, a dropped or stalled connection (no byte for 60 s, `timeout`) is
314    resumed from the byte it reached, again and again while bytes keep coming, and the download stops only after 5 minutes in a row without a
315    new byte. There is no total time cap. `what` names the file in the messages ("the engine 0.1.59")."""
316    partial = Path(partial)
317    partial.parent.mkdir(parents=True, exist_ok=True)
318    have = partial.stat().st_size if partial.exists() else 0
319    if have > size:
320        partial.unlink()
321        have = 0
322    if have < size:
323        what = what or "the download"
324        clock = netpolicy.StallClock()
325        first = True
326        while True:
327            have = partial.stat().st_size if partial.exists() else 0
328            clock.progress(have)
329            try:
330                _transfer(location, partial, have, size, progress, cancel, timeout, first=first, what=what, say=say)
331                got = partial.stat().st_size if partial.exists() else 0
332                if got >= size or kind_of(location) not in ("http", "https") or got <= have:
333                    break                                  # complete (or a local copy, or nothing new: the size check below says so)
334                # the answer ended early: resumed below, as a dropped connection is
335            except Unreachable:
336                if first:
337                    raise                                  # rule 3: the server did not answer at all - say so now, not in 5 minutes
338            except Interrupted:
339                pass                                       # a dropped or stalled connection: resumed below while bytes keep coming
340            first = False
341            now = partial.stat().st_size if partial.exists() else 0
342            clock.progress(now)
343            if clock.expired():
344                words = clock.words(what, now, size)
345                raise TransferError(f"{words[0]} {words[1]}", resumable=True) from None
346            if (cancel or threading.Event()).wait(netpolicy.RETRY_GAP_S):
347                raise Cancelled()
348    elif progress:
349        progress(size, size)
350    final = partial.stat().st_size
351    if final != size:
352        raise TransferError(f"{location} delivered {final} of {size} bytes; the partial file is kept and the next try resumes it",
353                            resumable=True)
354    if sha256_file(partial) != sha256.lower():
355        partial.unlink(missing_ok=True)
356        raise ChecksumMismatch(f"{location} does not match the SHA-256 in the signed feed; the download was deleted")
357    return partial
358
359
360def _opener_for(stall: float):
361    return _opener if stall == netpolicy.STALL_S else netpolicy.build_opener(_PolicyRedirects, stall=stall)
362
363
364def _transfer(location, partial: Path, have: int, size: int, progress, cancel, timeout, *, first: bool = True, what: str = "the download",
365              say=None) -> None:
366    kind = kind_of(location)
367    done = have
368    try:
369        if kind in ("http", "https"):
370            check_url_policy(location)
371            headers = {"User-Agent": _USER_AGENT}
372            if have:
373                headers["Range"] = f"bytes={have}-"
374            request = urllib.request.Request(location, headers=headers)
375            opener = _opener_for(float(timeout or netpolicy.STALL_S))
376            try:
377                answer = netpolicy.open_url(opener.open, request, say=say, check_memory=first)
378            except netpolicy.NetFailure as failure:
379                raise Unreachable(failure, what, resumable=True) from None
380            with answer as response:
381                if have and not _resumes_at(response, have, size):
382                    if response.status == 206:               # another range: its bytes are not the file's, ask again from the start
383                        partial.unlink(missing_ok=True)
384                        return _transfer(location, partial, 0, size, progress, cancel, timeout, first=first, what=what, say=say)
385                    have = done = 0                          # the server ignored the range and sent the whole file: start over, never append to a prefix
386                _copy(response, partial, "wb" if not have else "ab", done, size, progress, cancel)
387        else:
388            path = _local_path(location)
389            try:
390                opened = path.open("rb")
391            except (FileNotFoundError, NotADirectoryError, IsADirectoryError, PermissionError) as exc:
392                # a local source that cannot be OPENED does not get better by waiting: raised at once as before the network
393                # rule (a plain TransferError, so download() does not retry it), with main's words; a read that fails AFTER
394                # the open is still an Interrupted below, retried while bytes keep coming (a USB or network drive hiccup)
395                got = partial.stat().st_size if partial.exists() else 0
396                raise TransferError(f"the download of {location} was interrupted after {got} of {size} bytes "
397                                    f"({type(exc).__name__}: {exc}); the partial file is kept and the next try resumes it",
398                                    resumable=True) from None
399            with opened as source:
400                source.seek(have)
401                _copy(source, partial, "ab" if have else "wb", have, size, progress, cancel)
402    except (Cancelled, Unreachable):
403        raise
404    except urllib.error.HTTPError as exc:
405        if exc.code == 416:
406            partial.unlink(missing_ok=True)
407            raise TransferError(f"the server could not resume {location}; the partial file was removed, try again",
408                                resumable=False) from None
409        raise TransferError(f"the update server answered {exc.code} for {location}") from None
410    except (urllib.error.URLError, OSError, TimeoutError, ConnectionError, http.client.HTTPException) as exc:
411        if tls.is_certificate_error(exc):
412            raise TransferError(tls.explain(tls.host_of(location)), resumable=True) from None
413        got = partial.stat().st_size if partial.exists() else 0
414        reason = getattr(exc, "reason", exc)
415        said = (f"the download of {location} was interrupted after {got} of {size} bytes "
416                f"({type(exc).__name__}: {reason}); the partial file is kept and the next try resumes it")
417        if getattr(exc, "strata_destination", False):     # the .part cannot be written (a full disk, no permission): at once, as before
418            said = no_room_words(exc, partial, got, size, what, location) or said     # full / quota / read-only: in plain words
419            raise TransferError(said, resumable=True) from None
420        raise Interrupted(said, resumable=True) from None
421
422
423_CONTENT_RANGE = re.compile(r"\s*bytes (\d+)-(\d+)/(\d+|\*)\s*$")
424
425
426def _resumes_at(response, have: int, size: int) -> bool:
427    """Whether a resumed answer is a 206 whose Content-Range starts at byte `have` of a file of `size` bytes."""
428    if response.status != 206:
429        return False
430    m = _CONTENT_RANGE.match(response.headers.get("Content-Range") or "")
431    return bool(m) and int(m.group(1)) == have and (m.group(3) == "*" or int(m.group(3)) == size)
432
433
434def _copy(source, partial: Path, mode: str, done: int, size: int, progress, cancel) -> None:
435    """Write what the source delivers to the partial file. It takes what has arrived (read1) and gathers it up to CHUNK, handing it on at once when a read had
436    to wait; when the connection stalls, the bytes gathered so far are written before the error goes on, so the next try resumes after them
437    and the network rule's 5 minutes without a NEW byte are counted on the file's size (strata_control/netpolicy.py)."""
438    read = getattr(source, "read1", None) or source.read
439    try:
440        opened = partial.open(mode)
441    except _DEST_OPEN_ERRORS as exc:                       # the .part cannot be written here at all
442        raise _destination(exc)
443    except OSError as exc:                                 # nor on a full or read-only drive (EROFS at the open was retried for 5 minutes)
444        if exc.errno in _DEST_ERRNOS or _no_room_kind(exc):
445            raise _destination(exc)
446        raise
447
448    def put(out, data) -> None:
449        try:
450            out.write(data)
451        except OSError as exc:
452            if exc.errno in _DEST_ERRNOS:
453                _destination(exc)
454            raise
455
456    source_failed = False
457    try:
458        with opened as out:
459            while True:
460                if cancel is not None and cancel.is_set():
461                    out.flush()
462                    raise Cancelled()
463                gathered = bytearray()
464                end = False
465                try:
466                    while len(gathered) < CHUNK:
467                        began = time.monotonic()
468                        piece = read(CHUNK - len(gathered))
469                        if not piece:
470                            end = True
471                            break
472                        gathered += piece
473                        if time.monotonic() - began > WAITED_S:
474                            break                          # this read waited for the server: do not hold what we have any longer
475                except BaseException:
476                    source_failed = True
477                    put(out, gathered)                     # a stall or a break: what did arrive stays on disk
478                    raise
479                if gathered:
480                    if done + len(gathered) > size:
481                        raise TransferError("the server sent more bytes than the feed says; the download was stopped")
482                    put(out, gathered)
483                    done += len(gathered)
484                    if progress:
485                        progress(done, size)
486                if end:
487                    break
488            out.flush()
489    except OSError as exc:                                 # a buffered write fails at flush or close: the same rule
490        if not source_failed and exc.errno in _DEST_ERRNOS:
491            _destination(exc)
492        raise