191 lines
7.6 KiB
Python
191 lines
7.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Local-only builder of a fixed diagnostic example, never a target operator."""
|
|
import argparse
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import stat
|
|
import tarfile
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
CASE = '5b358997-3abc-43db-945f-f41855b4e3c0'
|
|
ARCHIVE = ROOT / 'devstate/server-time-source-bootstrap' / CASE / 'source.tar'
|
|
ARCHIVE_SHA = '0da5ed0d52d3e621ef6a23cbc065f9d7c93e5683547e0a02ae3c8da8a83884a5'
|
|
MANIFEST_SHA = 'bdf7839f832e2ea0cf230a0bd8a8fbff5d4a72d8fb7ba8208e0d252bad4b56ee'
|
|
NATIVE_SHA = '3fd9c7a969a583abf97e29165135a8c1044db5c951ad8bd4dbfee3ee77e7ccdc'
|
|
TRACKING_SHA = '7b042a24f38df53d3d553186d04bf6366c30fb77fe5c8ad66dfcf91290445297'
|
|
EXAMPLE = 'crates/time-source-linux/examples/operator_error_probe.rs'
|
|
PHASE = 'provider-error-diagnostic-v1'
|
|
|
|
PROBE = r'''// Standalone diagnostic only: no free error text, caller context or authority.
|
|
use std::{collections::BTreeSet, fmt::{self, Write as _}};
|
|
|
|
const KNOWN_TAGS: &[&str] = &[
|
|
__KNOWN_TAGS__
|
|
];
|
|
|
|
struct TagSink {
|
|
token: [u8; 96],
|
|
used: usize,
|
|
long_token: bool,
|
|
remaining: usize,
|
|
tags: BTreeSet<&'static str>,
|
|
truncated: bool,
|
|
}
|
|
impl TagSink {
|
|
fn new() -> Self {
|
|
Self { token: [0; 96], used: 0, long_token: false, remaining: 4096,
|
|
tags: BTreeSet::new(), truncated: false }
|
|
}
|
|
fn end_token(&mut self) {
|
|
if !self.long_token && let Ok(token) = std::str::from_utf8(&self.token[..self.used])
|
|
&& let Ok(index) = KNOWN_TAGS.binary_search(&token)
|
|
{
|
|
if self.tags.len() < 16 || self.tags.contains(KNOWN_TAGS[index]) {
|
|
self.tags.insert(KNOWN_TAGS[index]);
|
|
} else { self.truncated = true; }
|
|
}
|
|
self.used = 0;
|
|
self.long_token = false;
|
|
}
|
|
}
|
|
impl fmt::Write for TagSink {
|
|
fn write_str(&mut self, text: &str) -> fmt::Result {
|
|
for byte in text.bytes() {
|
|
if self.remaining == 0 {
|
|
// Discard an incomplete token: a truncated prefix is no tag.
|
|
self.used = 0;
|
|
self.long_token = true;
|
|
self.truncated = true;
|
|
return Err(fmt::Error);
|
|
}
|
|
self.remaining -= 1;
|
|
if byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_' {
|
|
if self.used < self.token.len() && !self.long_token {
|
|
self.token[self.used] = byte;
|
|
self.used += 1;
|
|
} else { self.long_token = true; }
|
|
} else { self.end_token(); }
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
if std::env::args_os().len() != 1 { std::process::exit(2); }
|
|
let result = (|| -> anyhow::Result<()> {
|
|
let mut source = rmm_time_source_linux::NativeTimeSource::open()?;
|
|
let _ = source.sample()?;
|
|
Ok(())
|
|
})();
|
|
let succeeded = result.is_ok();
|
|
let mut sink = TagSink::new();
|
|
let mut codes = BTreeSet::new();
|
|
let mut count = 0u8;
|
|
if let Err(error) = result {
|
|
for (index, cause) in error.chain().take(17).enumerate() {
|
|
if index == 16 { sink.truncated = true; break; }
|
|
count += 1;
|
|
if let Some(code) = cause.downcast_ref::<std::io::Error>().and_then(|e| e.raw_os_error()) {
|
|
if codes.len() < 8 || codes.contains(&code) { codes.insert(code); }
|
|
else { sink.truncated = true; }
|
|
}
|
|
// Display is consumed only by this bounded filtering sink. Never
|
|
// make, retain, print or serialize a free-form error string.
|
|
let _ = write!(&mut sink, "{cause}");
|
|
sink.end_token();
|
|
}
|
|
}
|
|
println!("{}", serde_json::json!({
|
|
"schema_version": 1,
|
|
"profile": "rmm.native-source-error.once.v1",
|
|
"provider_call_succeeded": succeeded,
|
|
"known_error_tags": sink.tags.into_iter().collect::<Vec<_>>(),
|
|
"os_error_codes": codes.into_iter().collect::<Vec<_>>(),
|
|
"cause_count": count,
|
|
"truncated": sink.truncated,
|
|
"clock_authority": false,
|
|
"source_quality_qualified": false,
|
|
"signed_attestation": false
|
|
}));
|
|
if !succeeded { std::process::exit(1); }
|
|
}
|
|
'''
|
|
|
|
|
|
def sha(raw):
|
|
return hashlib.sha256(raw).hexdigest()
|
|
|
|
|
|
def require(ok, reason):
|
|
if not ok:
|
|
raise RuntimeError(reason)
|
|
|
|
|
|
def encoded(value):
|
|
return (json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True) + '\n').encode('ascii')
|
|
|
|
|
|
def build_source():
|
|
info = ARCHIVE.lstat()
|
|
require(stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and info.st_uid == os.getuid()
|
|
and stat.S_IMODE(info.st_mode) == 0o600 and info.st_size == 225280, 'private_original_archive')
|
|
raw = ARCHIVE.read_bytes()
|
|
require(sha(raw) == ARCHIVE_SHA, 'exact_original_source_archive')
|
|
with tarfile.open(fileobj=io.BytesIO(raw), mode='r:') as archive:
|
|
manifest_raw = archive.extractfile('manifest.json').read()
|
|
require(sha(manifest_raw) == MANIFEST_SHA, 'original_manifest_bytes')
|
|
manifest = json.loads(manifest_raw)
|
|
sources = {}
|
|
for item in manifest['package_files']:
|
|
data = archive.extractfile(item['path']).read()
|
|
require(len(data) == item['bytes'] and sha(data) == item['sha256'], 'unchanged_original_package')
|
|
sources[item['path']] = data
|
|
require(sha(sources['crates/time-source-linux/src/native.rs']) == NATIVE_SHA and
|
|
sha(sources['crates/time-source-linux/src/tracking.rs']) == TRACKING_SHA,
|
|
'exact_unchanged_provider_and_tracking_sources')
|
|
tags = set()
|
|
for name in ('native', 'tracking', 'lib'):
|
|
tags.update(re.findall(rb'"((?:TIME|CHRONY)_[A-Z0-9_]+)', sources[f'crates/time-source-linux/src/{name}.rs']))
|
|
require(1 <= len(tags) <= 128 and all(len(tag) <= 96 for tag in tags)
|
|
and any(tag.startswith(b'CHRONY_') for tag in tags), 'closed_original_error_tag_enum')
|
|
table = '\n'.join(' "' + tag.decode('ascii') + '",' for tag in sorted(tags))
|
|
example = PROBE.replace('__KNOWN_TAGS__', table).encode('ascii')
|
|
require(len(example) <= 16384 and '__KNOWN_TAGS__' not in example.decode(), 'bounded_fixed_example')
|
|
return example, [tag.decode('ascii') for tag in sorted(tags)]
|
|
|
|
|
|
def prepare():
|
|
example, tags = build_source()
|
|
os.umask(0o077)
|
|
folder = ROOT / 'devstate/server-time-source-error-probe' / str(uuid.uuid4())
|
|
folder.mkdir(parents=True, mode=0o700)
|
|
def write(name, data):
|
|
with (folder / name).open('xb') as stream:
|
|
stream.write(data); stream.flush(); os.fsync(stream.fileno())
|
|
write('operator_error_probe.rs', example)
|
|
manifest = dict(profile='rmm.server-time-source.error-probe-source.v1', original_case=CASE,
|
|
own_target_phase=PHASE, original_source_tar_sha256=ARCHIVE_SHA, original_manifest_sha256=MANIFEST_SHA,
|
|
unchanged_native_sha256=NATIVE_SHA, unchanged_tracking_sha256=TRACKING_SHA,
|
|
generator_sha256=sha(Path(__file__).read_bytes()), example_path=EXAMPLE,
|
|
example_sha256=sha(example), example_bytes=len(example), known_error_tags=tags,
|
|
max_causes=16, max_tags=16, max_io_error_codes=8, max_formatted_input_bytes=4096,
|
|
free_error_text=False, clock_authority=False, source_quality_qualified=False,
|
|
target_executed=False, build_executed=False)
|
|
write('manifest.json', encoded(manifest))
|
|
fd = os.open(folder, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
|
try: os.fsync(fd)
|
|
finally: os.close(fd)
|
|
print(json.dumps(dict(path=str(folder), **manifest), sort_keys=True))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('command', choices=('prepare',))
|
|
parser.parse_args()
|
|
prepare()
|