update.v

7.7 KB · raw

1//! `koh update` — put a newer published koh in place of this one (§12).2//!3//! The source is a release document: Kepr's `/koh/releases/latest.json` by4//! default, or whatever `KOH_UPDATE_SOURCE` names. Koh installs only a5//! **newer** version than the one running, never merely a different one, so a6//! stale mirror cannot walk the binary backwards. Nothing is ever built here.78module update910import crypto.blake311import json212import net.http13import net.urllib14import os15import src.remote1617pub const default_source = 'https://kepr.uk/koh/releases/latest.json'18pub const source_env = 'KOH_UPDATE_SOURCE'19pub const repo = 'koh'20const file_scheme = 'file://'2122// One platform's file, in the shape Kepr answers with (§22.4).23struct PlatformFile {24	url    string25	blake3 string26	sha256 string27}2829// The release document: `notes` is omitted by Kepr when it is empty, so it is30// optional rather than an empty string.31struct Document {32	version   string33	notes     ?string34	platforms map[string]PlatformFile35}3637pub struct Available {38pub:39	version  string40	notes    string41	url      string42	blake3   string43	platform string44}4546// source is the document to read: the environment wins, so a self-hosted Kepr47// can serve its own koh.48pub fn source() string {49	named := os.getenv(source_env)50	if named != '' {51		return named52	}53	return default_source54}5556// Checked is what the source had to say: whether there is anything newer, and57// what it is when there is.58pub struct Checked {59pub:60	update    bool61	available Available62}6364// check asks the source what the newest koh is. Errors are errors; "nothing to65// do" is not one of them, so it is a field, not a failed call.66pub fn check(now string, platform string) !Checked {67	url := source()68	// The document supplies both the download address and its hash, so a plain-http source would69	// let anyone on the path replace both. Localhost is the one exception, for a mirror on this machine.70	parsed := urllib.parse(url) or { return error('${url} is not an address') }71	if parsed.scheme != 'https'72		&& !(parsed.scheme == 'http' && parsed.hostname().to_lower() in ['127.0.0.1', 'localhost',73			'::1']) {74		return error('koh update needs https — plain http is only for a source on this machine')75	}76	response := http.fetch(77		url:          url78		validate:     true79		verify:       remote.tls_roots(url)!80		enable_http2: false81	) or { return error('could not reach ${url}: ${err.msg()}') }82	if response.status_code != 200 {83		return error('${url} answered ${response.status_code}')84	}85	document := json2.decode[Document](response.body) or {86		// The parser's own message, carets and colour included, means nothing here.87		return error('${url} did not answer with a release document — try again later')88	}89	if document.version == '' {90		// A document with no version is not a release document, so say that rather91		// than pretending there is simply nothing to do.92		return error('${url} has no version — it is not a release document')93	}94	if compare_versions(document.version, now) <= 0 {95		return Checked{}96	}97	file := document.platforms[platform] or {98		return error('koh ${document.version} has no ${platform} file — run it on another machine')99	}100	return Checked{101		update:    true102		available: Available{103			version:  document.version104			notes:    document.notes or { '' }105			url:      file.url106			blake3:   file.blake3107			platform: platform108		}109	}110}111112// compare_versions orders two versions the way the spec asks: dot-separated113// components compared as numbers, so 2.10.0 is newer than 2.9.9. A component114// that is not a number is compared as text, so a strange version can never win115// by accident. Returns 1, 0 or -1.116pub fn compare_versions(a string, b string) int {117	left := a.split('.')118	right := b.split('.')119	for index in 0 .. if left.len > right.len { left.len } else { right.len } {120		one := if index < left.len { left[index] } else { '0' }121		two := if index < right.len { right[index] } else { '0' }122		order := compare_component(one, two)123		if order != 0 {124			return order125		}126	}127	return 0128}129130fn compare_component(a string, b string) int {131	// Leading zeros are not part of a number: 01 and 1 are the same version.132	left := a.trim_left('0')133	right := b.trim_left('0')134	if left == right {135		return 0136	}137	if left.len != right.len {138		return if left.len > right.len { 1 } else { -1 }139	}140	return if left > right { 1 } else { -1 }141}142143// install downloads the new binary, checks it, and swaps it in for the one144// running. The rename is the only step that changes anything, and it is the145// last one.146pub fn install(available Available) !string {147	bytes := download(available.url)!148	verify(bytes, available.blake3)!149	target := os.executable()150	fresh := write_beside(os.dir(target), bytes)!151	if os.user_os() == 'macos' {152		// An unsigned binary cannot run on Apple silicon at all, so a refused153		// signature is a refusal to install, not a warning.154		signed := os.execute('codesign -f -s - ${sh_quote(fresh)}')155		if signed.exit_code != 0 {156			os.rm(fresh) or {}157			return error('codesign refused the downloaded binary: ${signed.output.trim_space()}')158		}159	}160	// rename, not move: both paths are in one folder, so this is the atomic step161	// and a failure is a failure, never a half-written binary.162	os.rename(fresh, target)!163	return target164}165166fn download(url string) ![]u8 {167	if url.starts_with(file_scheme) {168		// A Kepr with a folder bucket hands out `file://` download URLs (dev and169		// tests only), so updating from one is the same code path with the file170		// read instead of fetched.171		path := url[file_scheme.len..]172		size := os.file_size(path)173		bytes := os.read_file(path) or {174			return error('could not read ${url}: ${err.msg()}')175		}.bytes()176		// The download is verified against the size it was said to be, and then177		// against its Blake3, before anything is signed or moved.178		if size > 0 && bytes.len != size {179			return error('${url} is ${size} bytes but ${bytes.len} arrived — refusing a partial download')180		}181		return bytes182	}183	response := http.fetch(184		url:          url185		validate:     true186		verify:       remote.tls_roots(url)!187		enable_http2: false188	) or { return error('could not download ${url}: ${err.msg()}') }189	if response.status_code != 200 {190		return error('${url} answered ${response.status_code}')191	}192	bytes := response.body.bytes()193	declared := response.header.get(.content_length) or { '' }194	if declared != '' && i64(declared.trim_space().int()) != bytes.len {195		return error('${url} said ${declared} bytes and sent ${bytes.len} — refusing a partial download')196	}197	return bytes198}199200// verify is the check that makes installing anything safe: the bytes must be201// what the document said, or they are thrown away.202fn verify(bytes []u8, expected string) ! {203	if bytes.len == 0 {204		return error('the download was empty')205	}206	if expected == '' {207		return error('the release document carries no Blake3 checksum — refusing to install it')208	}209	got := blake3.sum256(bytes).hex()210	if got != expected {211		return error('the download is not the published file (Blake3 ${got} instead of ${expected}) — refusing to install it')212	}213}214215// write_beside writes the new binary beside the one it will replace, so the rename is216// within one filesystem and therefore atomic. A folder that cannot be written217// is refused here, with the write's own error.218fn write_beside(dir string, bytes []u8) !string {219	fresh := os.join_path(dir, '.koh-new-${os.getpid()}')220	os.write_file_array(fresh, bytes) or {221		return error('cannot write beside ${dir} — put koh where this user can replace it (${err.msg()})')222	}223	os.chmod(fresh, 0o755)!224	return fresh225}226227// sh_quote keeps a path with a space in it one argument, and cannot be broken228// out of by a quote inside the path.229fn sh_quote(text string) string {230	return "'" + text.replace("'", "'\\''") + "'"231}