okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c7ec1e8fe
main
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 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 : 45exc .strata_destination = True # read in _transfer: a plain TransferError, not an Interrupted 46return 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.""" 68if n <= 0 : 69return "0 MB" 70return 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).""" 75if not isinstance (exc ,OSError ): 76return None 77if exc .errno == errno .ENOSPC or getattr (exc ,"winerror" ,None )in (112 ,39 ):# ERROR_DISK_FULL, ERROR_HANDLE_DISK_FULL 78return "full" 79if getattr (errno ,"EDQUOT" ,None )is not None and exc .errno == errno .EDQUOT : 80return "quota" 81if exc .errno == errno .EROFS : 82return "read_only" 83return 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, 89here, and left out when it cannot be read.""" 90kind = _no_room_kind (exc ) 91if kind is None : 92return None 93folder = str (Path (partial ).parent ) 94if not what or what == "the download" : 95name = urllib .parse .urlparse (location ).path .rsplit ("/" ,1 )[- 1 ]if location else "" 96what = f"the file { name } " if name else "the download" 97free = "" 98if kind == "full" : 99try : 100free = NO_ROOM_WORDS ["free" ].format (free = _size_words (shutil .disk_usage (folder ).free )) 101except (OSError ,ValueError ): 102free = "" 103kept = NO_ROOM_WORDS ["kept" if got > 0 else "none_kept" ] 104said = NO_ROOM_WORDS [kind ].format (folder = folder ,what = what ,got = _size_words (got ),size = _size_words (size ), 105need = _size_words (max (0 ,size - got )),free = free ,kept = kept ,kept_cap = kept [:1 ].upper ()+ kept [1 :]) 106return 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 116def __init__ (self ,message :str ,* ,resumable :bool = False ): 117super ().__init__ (message ) 118self .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 127plain sentence.""" 128 129def __init__ (self ,failure :"netpolicy.NetFailure" ,what :str = "the download" ,resumable :bool = False ): 130super ().__init__ (failure .headline (what )+ " " + failure .next_step (),resumable = resumable ) 131self .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 141def __init__ (self ,message :str = "cancelled" ): 142super ().__init__ (message ,resumable = True ) 143 144 145def _is_loopback (host :str )-> bool : 146if host in ("localhost" ,): 147return True 148try : 149return ipaddress .ip_address (host ).is_loopback 150except ValueError : 151return False 152 153 154def kind_of (source :str )-> str : 155""""http", "https", "file" or "path".""" 156parsed = urllib .parse .urlparse (source ) 157if len (parsed .scheme )== 1 :# a Windows drive letter 158return "path" 159if parsed .scheme in ("http" ,"https" ,"file" ): 160return parsed .scheme 161if parsed .scheme : 162raise TransferError (f"the update source scheme { parsed . scheme !r } is not supported (https, a loopback http, file or a folder)" ) 163return "path" 164 165 166def check_url_policy (url :str ,environ = None )-> None : 167environ = os .environ if environ is None else environ 168parsed = urllib .parse .urlparse (url ) 169if parsed .scheme == "https" : 170return 171if parsed .scheme == "http" : 172if _is_loopback (parsed .hostname or "" )or environ .get (ENV_ALLOW_HTTP )== "1" : 173return 174raise TransferError (f" { url } is plain http; updates are fetched over https (a loopback address is the only exception)" ) 175raise TransferError (f" { url } is not an https address" ) 176 177 178def _local_path (source :str )-> Path : 179if source .startswith ("file:" ): 180parsed = urllib .parse .urlparse (source ) 181path = urllib .request .url2pathname (parsed .path ) 182if os .name == "nt" and path .startswith (("/" ,"\\" ))and len (path )> 2 and path [2 ]== ":" : 183path = path [1 :] 184return Path (path ) 185return Path (source ) 186 187 188def base_of (source :str )-> str : 189"""The folder / URL prefix that references in the feed are relative to.""" 190kind = kind_of (source ) 191if kind in ("http" ,"https" ): 192return source .rsplit ("/" ,1 )[0 ]+ "/" 193path = _local_path (source ) 194return 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 199pass the URL policy (https, or a loopback http) and, for a local base, may not be a remote address at all.""" 200if not isinstance (ref ,str )or not ref or "\0" in ref or "\\" in ref : 201raise TransferError (f"the feed contains an unusable file reference { ref !r } " ) 202parsed = urllib .parse .urlparse (ref ) 203kind = kind_of (base ) 204if parsed .scheme : 205if kind in ("path" ,"file" ): 206raise TransferError (f"the local feed refers to a remote address ( { ref } ); a local feed may only name files inside its own folder" ) 207check_url_policy (ref ,environ ) 208return ref 209if ref .startswith ("/" )or ".." in ref .split ("/" ): 210raise TransferError (f"the feed reference { ref !r } leaves the feed's own location" ) 211if kind in ("http" ,"https" ): 212return urllib .parse .urljoin (base if base .endswith ("/" )else base + "/" ,ref ) 213root = _local_path (base ).resolve () 214target = (root / ref ).resolve () 215if root != target and root not in target .parents : 216raise TransferError (f"the feed reference { ref !r } leaves the feed's own folder" ) 217return str (target ) 218 219 220class _PolicyRedirects (urllib .request .HTTPRedirectHandler ): 221def redirect_request (self ,req ,fp ,code ,msg ,headers ,newurl ): 222check_url_policy (newurl ) 223return 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 235looks expired be told from a PC whose clock is wrong.""" 236return _SERVER_DATE [- 1 ]if _SERVER_DATE else None 237 238 239def _remember_date (response )-> None : 240try : 241parsed = utils .parsedate_to_datetime (response .headers .get ("Date" )or "" ) 242if parsed is not None : 243_SERVER_DATE [:]= [parsed if parsed .tzinfo else parsed .replace (tzinfo = _dt .timezone .utc )] 244except (TypeError ,ValueError ): 245pass 246 247 248FIRST_TRY_SECONDS = 12.0 249 250 251def _open_small (request ,timeout :float ,limit :int )-> bytes : 252with _opener .open (request ,timeout = timeout )as response : 253_remember_date (response ) 254return 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. 259A 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 260timeout 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 261own read worked). The first try therefore waits at most 12 s; the second the full `timeout`.""" 262kind = kind_of (location ) 263_SERVER_DATE .clear ()# only the answer of this read counts 264try : 265if kind in ("http" ,"https" ): 266check_url_policy (location ) 267request = urllib .request .Request (location ,headers = {"User-Agent" :_USER_AGENT ,"Cache-Control" :"no-cache" }) 268try :# the network rule: 12 s, then one retry with the full timeout; clear failures at once 269def attempt (req ,timeout ): 270_SERVER_DATE .clear ()# only the answer of the try that worked counts 271return _open_small (req ,timeout ,limit ) 272data = netpolicy .open_url (attempt ,request ,limits = (min (timeout ,FIRST_TRY_SECONDS ),timeout ),say = say , 273automatic = automatic )# automatic: a read nobody asked for (netpolicy rule 4b) # say: the waiting line (W1) 274except netpolicy .NetFailure as failure : 275raise Unreachable (failure ,"the update feed" )from None 276else : 277path = _local_path (location ) 278if path .stat ().st_size > limit : 279raise TransferError (f" { location } is larger than { limit } bytes" ) 280data = path .read_bytes () 281except TransferError : 282raise 283except urllib .error .HTTPError as exc : 284raise TransferError (f"the update server answered { exc . code } for { location } " )from None 285except (urllib .error .URLError ,OSError ,TimeoutError )as exc : 286reason = getattr (exc ,"reason" ,exc ) 287hint = "" 288if tls .is_certificate_error (exc ): 289raise TransferError (tls .explain (tls .host_of (location )))from None 290raise TransferError (f"could not read { location } ( { type ( exc ). __name__ } : { reason } ) { hint } " )from None 291if len (data )> limit : 292raise TransferError (f" { location } is larger than { limit } bytes" ) 293return data 294 295 296def sha256_file (path :Path )-> str : 297digest = hashlib .sha256 () 298with Path (path ).open ("rb" )as stream : 299for block in iter (lambda :stream .read (CHUNK ),b"" ): 300digest .update (block ) 301return digest .hexdigest () 302 303 304def download (location :str ,partial :Path ,* ,size :int ,sha256 :str , 305progress :Callable [[int ,int ],None ]| None = None , 306cancel :threading .Event | None = None ,timeout :float = 60 ,what :str | None = None , 307say :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 309SHA-256 `sha256`. An interrupted transfer keeps the partial file (`TransferError.resumable`); a complete file with the 310wrong hash is deleted, because resuming cannot repair it. 311 312The 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 314resumed 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 315new byte. There is no total time cap. `what` names the file in the messages ("the engine 0.1.59").""" 316partial = Path (partial ) 317partial .parent .mkdir (parents = True ,exist_ok = True ) 318have = partial .stat ().st_size if partial .exists ()else 0 319if have > size : 320partial .unlink () 321have = 0 322if have < size : 323what = what or "the download" 324clock = netpolicy .StallClock () 325first = True 326while True : 327have = partial .stat ().st_size if partial .exists ()else 0 328clock .progress (have ) 329try : 330_transfer (location ,partial ,have ,size ,progress ,cancel ,timeout ,first = first ,what = what ,say = say ) 331got = partial .stat ().st_size if partial .exists ()else 0 332if got >= size or kind_of (location )not in ("http" ,"https" )or got <= have : 333break # 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 335except Unreachable : 336if first : 337raise # rule 3: the server did not answer at all - say so now, not in 5 minutes 338except Interrupted : 339pass # a dropped or stalled connection: resumed below while bytes keep coming 340first = False 341now = partial .stat ().st_size if partial .exists ()else 0 342clock .progress (now ) 343if clock .expired (): 344words = clock .words (what ,now ,size ) 345raise TransferError (f" { words [ 0 ] } { words [ 1 ] } " ,resumable = True )from None 346if (cancel or threading .Event ()).wait (netpolicy .RETRY_GAP_S ): 347raise Cancelled () 348elif progress : 349progress (size ,size ) 350final = partial .stat ().st_size 351if final != size : 352raise TransferError (f" { location } delivered { final } of { size } bytes; the partial file is kept and the next try resumes it" , 353resumable = True ) 354if sha256_file (partial )!= sha256 .lower (): 355partial .unlink (missing_ok = True ) 356raise ChecksumMismatch (f" { location } does not match the SHA-256 in the signed feed; the download was deleted" ) 357return partial 358 359 360def _opener_for (stall :float ): 361return _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" , 365say = None )-> None : 366kind = kind_of (location ) 367done = have 368try : 369if kind in ("http" ,"https" ): 370check_url_policy (location ) 371headers = {"User-Agent" :_USER_AGENT } 372if have : 373headers ["Range" ]= f"bytes= { have } -" 374request = urllib .request .Request (location ,headers = headers ) 375opener = _opener_for (float (timeout or netpolicy .STALL_S )) 376try : 377answer = netpolicy .open_url (opener .open ,request ,say = say ,check_memory = first ) 378except netpolicy .NetFailure as failure : 379raise Unreachable (failure ,what ,resumable = True )from None 380with answer as response : 381if have and not _resumes_at (response ,have ,size ): 382if response .status == 206 :# another range: its bytes are not the file's, ask again from the start 383partial .unlink (missing_ok = True ) 384return _transfer (location ,partial ,0 ,size ,progress ,cancel ,timeout ,first = first ,what = what ,say = say ) 385have = 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 ) 387else : 388path = _local_path (location ) 389try : 390opened = path .open ("rb" ) 391except (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) 395got = partial .stat ().st_size if partial .exists ()else 0 396raise TransferError (f"the download of { location } was interrupted after { got } of { size } bytes " 397f"( { type ( exc ). __name__ } : { exc } ); the partial file is kept and the next try resumes it" , 398resumable = True )from None 399with opened as source : 400source .seek (have ) 401_copy (source ,partial ,"ab" if have else "wb" ,have ,size ,progress ,cancel ) 402except (Cancelled ,Unreachable ): 403raise 404except urllib .error .HTTPError as exc : 405if exc .code == 416 : 406partial .unlink (missing_ok = True ) 407raise TransferError (f"the server could not resume { location } ; the partial file was removed, try again" , 408resumable = False )from None 409raise TransferError (f"the update server answered { exc . code } for { location } " )from None 410except (urllib .error .URLError ,OSError ,TimeoutError ,ConnectionError ,http .client .HTTPException )as exc : 411if tls .is_certificate_error (exc ): 412raise TransferError (tls .explain (tls .host_of (location )),resumable = True )from None 413got = partial .stat ().st_size if partial .exists ()else 0 414reason = getattr (exc ,"reason" ,exc ) 415said = (f"the download of { location } was interrupted after { got } of { size } bytes " 416f"( { type ( exc ). __name__ } : { reason } ); the partial file is kept and the next try resumes it" ) 417if getattr (exc ,"strata_destination" ,False ):# the .part cannot be written (a full disk, no permission): at once, as before 418said = no_room_words (exc ,partial ,got ,size ,what ,location )or said # full / quota / read-only: in plain words 419raise TransferError (said ,resumable = True )from None 420raise 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.""" 428if response .status != 206 : 429return False 430m = _CONTENT_RANGE .match (response .headers .get ("Content-Range" )or "" ) 431return 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 436to wait; when the connection stalls, the bytes gathered so far are written before the error goes on, so the next try resumes after them 437and the network rule's 5 minutes without a NEW byte are counted on the file's size (strata_control/netpolicy.py).""" 438read = getattr (source ,"read1" ,None )or source .read 439try : 440opened = partial .open (mode ) 441except _DEST_OPEN_ERRORS as exc :# the .part cannot be written here at all 442raise _destination (exc ) 443except OSError as exc :# nor on a full or read-only drive (EROFS at the open was retried for 5 minutes) 444if exc .errno in _DEST_ERRNOS or _no_room_kind (exc ): 445raise _destination (exc ) 446raise 447 448def put (out ,data )-> None : 449try : 450out .write (data ) 451except OSError as exc : 452if exc .errno in _DEST_ERRNOS : 453_destination (exc ) 454raise 455 456source_failed = False 457try : 458with opened as out : 459while True : 460if cancel is not None and cancel .is_set (): 461out .flush () 462raise Cancelled () 463gathered = bytearray () 464end = False 465try : 466while len (gathered )< CHUNK : 467began = time .monotonic () 468piece = read (CHUNK - len (gathered )) 469if not piece : 470end = True 471break 472gathered += piece 473if time .monotonic ()- began > WAITED_S : 474break # this read waited for the server: do not hold what we have any longer 475except BaseException : 476source_failed = True 477put (out ,gathered )# a stall or a break: what did arrive stays on disk 478raise 479if gathered : 480if done + len (gathered )> size : 481raise TransferError ("the server sent more bytes than the feed says; the download was stopped" ) 482put (out ,gathered ) 483done += len (gathered ) 484if progress : 485progress (done ,size ) 486if end : 487break 488out .flush () 489except OSError as exc :# a buffered write fails at flush or close: the same rule 490if not source_failed and exc .errno in _DEST_ERRNOS : 491_destination (exc ) 492raise