remote.v

2.7 KB · raw

1//! The remote interface: five operations, two backends.2//!3//! A remote is dumb storage that can do one safe swap. Everything clever —4//! what to upload, what diverged, how to combine — lives in `src/exchange`, above5//! this interface, so the folder and S3 backends stay thin and the sync logic6//! is written once and tested offline.78module remote910import rand11import os1213// get not finding a key is a normal answer, not an error, so `Object.found`14// carries it and errors mean real trouble (a refused connection, bad keys).15pub struct Object {16pub:17	found bool18	body  []u819	tag   string20}2122// Backend is one place to put bytes. `put_if_absent` never overwrites and23// `put_if_match` only overwrites when the version still matches, which is what24// makes two machines offering at once safe.25pub interface Backend {26mut:27	get(key string) !Object28	list(prefix string) ![]string29	list_dirs(prefix string) ![]string30	put_if_absent(key string, body []u8) !bool31	put_if_match(key string, body []u8, tag string) !bool32	delete(key string) !33}3435pub const probe_key = 'koh-probe'3637// check runs the connection test `koh remote` insists on before saving a38// setting: write a probe object, confirm a second write of it is refused, then39// delete it. A backend that cannot do that cannot keep two machines honest.40pub fn check(mut backend Backend) ! {41	payload := 'koh probe'.bytes()42	// Each check has its own key: with a shared one, two machines setting up43	// at once delete each other's probe and report a broken remote.44	key := '${probe_key}-${rand.hex(16)}'45	if !backend.put_if_absent(key, payload)! {46		return error('the remote refused to store a new object')47	}48	defer {49		// Also on the early returns below; deleting twice is harmless.50		backend.delete(key) or {}51	}52	if backend.put_if_absent(key, payload)! {53		return error('the remote overwrote an existing object — conditional writes are not working')54	}55	probe := backend.get(key)!56	if !probe.found || probe.body != payload {57		return error('the remote did not give back what was written')58	}59	// Strip needs delete, so a remote that cannot delete fails here.60	backend.delete(key)!61}6263/// Find the system CA bundle for HTTPS; plain HTTP needs no TLS roots.64pub fn tls_roots(url string) !string {65	mut roots := ''66	if url.starts_with('https://') {67		for path in [os.getenv('SSL_CERT_FILE'), '/etc/ssl/cert.pem',68			'/etc/ssl/certs/ca-certificates.crt', '/etc/ssl/certs/ca-bundle.crt',69			'/etc/pki/tls/certs/ca-bundle.crt', '/etc/ssl/ca-bundle.pem'] {70			if path != '' && os.is_file(path) {71				roots = path72				break73			}74		}75		if roots == '' {76			return error('no system CA bundle found — set SSL_CERT_FILE to your trusted CA bundle')77		}78	}79	return roots80}