1use std::{collections::BTreeSet, ffi::CStr, fmt, fs, mem::MaybeUninit};
15
16use minicbor::{Decode, Encode};
17
18use crate::{
19 lock::host_name,
20 records::{Family, Record, RecordKey},
21};
22
23const STATUS_FILE: &str = "/proc/self/status";
25
26const CPU_INFO_FILE: &str = "/proc/cpuinfo";
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct IdentityKey;
32
33impl IdentityKey {
34 const BYTES: &'static [u8] = b"identity";
36}
37
38impl RecordKey for IdentityKey {
39 fn encode_key(
40 &self,
41 out: &mut Vec<u8>,
42 ) {
43 out.extend_from_slice(Self::BYTES);
44 }
45
46 fn decode_key(bytes: &[u8]) -> Option<Self> {
47 (bytes == Self::BYTES).then_some(Self)
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
54pub struct CacheIdentity {
55 #[n(0)]
57 pub host: String,
58 #[n(1)]
60 pub user: u32,
61 #[n(2)]
63 pub group: u32,
64 #[n(3)]
66 pub groups: Vec<u32>,
67 #[n(4)]
70 pub umask: Option<u32>,
71 #[n(5)]
73 pub machine: String,
74 #[n(6)]
77 pub cpu_models: Vec<String>,
78}
79
80impl Record for CacheIdentity {
81 type Key = IdentityKey;
82
83 const FAMILY: Family = Family::Meta;
84}
85
86impl CacheIdentity {
87 #[must_use]
89 pub fn current() -> Self {
90 Self {
91 host: host_name(),
92 user: unsafe { libc::geteuid() },
94 group: unsafe { libc::getegid() },
96 groups: supplementary_groups(),
97 umask: fs::read_to_string(STATUS_FILE)
98 .ok()
99 .and_then(|status| umask_of_status(&status)),
100 machine: machine(),
101 cpu_models: fs::read_to_string(CPU_INFO_FILE)
102 .map_or_default(|info| cpu_models_of_info(&info)),
103 }
104 }
105
106 #[must_use]
113 pub fn differences(
114 &self,
115 current: &Self,
116 ) -> Vec<IdentityDifference> {
117 IdentityPart::ALL
118 .into_iter()
119 .filter(|part| part.differs(self, current))
120 .map(|part| {
121 IdentityDifference {
122 part,
123 stored: part.value(self),
124 current: part.value(current),
125 }
126 })
127 .collect()
128 }
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
133pub enum IdentityPart {
134 Host,
136 User,
138 Group,
140 Groups,
142 Umask,
144 Machine,
146 CpuModel,
148}
149
150impl IdentityPart {
151 pub const ALL: [Self; 7] = [
153 Self::Host,
154 Self::User,
155 Self::Group,
156 Self::Groups,
157 Self::Umask,
158 Self::Machine,
159 Self::CpuModel,
160 ];
161
162 #[must_use]
164 pub const fn name(self) -> &'static str {
165 match self {
166 Self::Host => "host name",
167 Self::User => "effective user ID",
168 Self::Group => "effective group ID",
169 Self::Groups => "supplementary groups",
170 Self::Umask => "umask",
171 Self::Machine => "machine architecture",
172 Self::CpuModel => "CPU model",
173 }
174 }
175
176 #[must_use]
179 pub fn differs(
180 self,
181 stored: &CacheIdentity,
182 current: &CacheIdentity,
183 ) -> bool {
184 match self {
185 Self::Host => stored.host != current.host,
186 Self::User => stored.user != current.user,
187 Self::Group => stored.group != current.group,
188 Self::Groups => stored.groups != current.groups,
189 Self::Umask => stored.umask != current.umask,
190 Self::Machine => stored.machine != current.machine,
191 Self::CpuModel => stored.cpu_models != current.cpu_models,
192 }
193 }
194
195 #[must_use]
203 pub fn value(
204 self,
205 identity: &CacheIdentity,
206 ) -> String {
207 match self {
208 Self::Host => quoted(&identity.host),
209 Self::User => identity.user.to_string(),
210 Self::Group => identity.group.to_string(),
211 Self::Groups => bracketed(identity.groups.iter().map(u32::to_string)),
212 Self::Umask => {
213 identity
214 .umask
215 .map_or_else(|| String::from("unknown"), |umask| format!("{umask:04o}"))
216 },
217 Self::Machine => quoted(&identity.machine),
218 Self::CpuModel => bracketed(identity.cpu_models.iter().map(String::as_str).map(quoted)),
219 }
220 }
221}
222
223fn quoted(text: &str) -> String {
227 let mut shown = String::from('"');
228 for character in text.chars() {
229 match character {
230 '"' | '\\' => {
231 shown.push('\\');
232 shown.push(character);
233 },
234 control if control.is_control() => shown.extend(control.escape_unicode()),
235 other => shown.push(other),
236 }
237 }
238 shown.push('"');
239 shown
240}
241
242fn bracketed(items: impl Iterator<Item = String>) -> String {
244 format!("[{}]", items.collect::<Vec<_>>().join(", "))
245}
246
247impl fmt::Display for IdentityPart {
248 fn fmt(
249 &self,
250 f: &mut fmt::Formatter<'_>,
251 ) -> fmt::Result {
252 f.write_str(self.name())
253 }
254}
255
256#[derive(Debug, Clone, PartialEq, Eq)]
259pub struct IdentityDifference {
260 pub part: IdentityPart,
262 pub stored: String,
264 pub current: String,
266}
267
268impl fmt::Display for IdentityDifference {
269 fn fmt(
270 &self,
271 f: &mut fmt::Formatter<'_>,
272 ) -> fmt::Result {
273 write!(
274 f,
275 "{}: {} in the cache, {} now",
276 self.part, self.stored, self.current
277 )
278 }
279}
280
281#[must_use]
283pub fn identity_differences_text(differences: &[IdentityDifference]) -> String {
284 differences
285 .iter()
286 .map(ToString::to_string)
287 .collect::<Vec<_>>()
288 .join("; ")
289}
290
291fn supplementary_groups() -> Vec<u32> {
296 let count = unsafe { libc::getgroups(0, std::ptr::null_mut()) };
298 let Ok(len) = usize::try_from(count) else {
299 return Vec::new();
300 };
301 let mut groups: Vec<libc::gid_t> = Vec::new();
302 if groups.try_reserve_exact(len).is_err() {
303 return Vec::new();
304 }
305 groups.resize(len, 0);
306 let filled = unsafe { libc::getgroups(count, groups.as_mut_ptr()) };
308 let Ok(filled) = usize::try_from(filled) else {
309 return Vec::new();
310 };
311 groups.truncate(filled);
312 groups.sort_unstable();
313 groups.dedup();
314 groups
315}
316
317fn machine() -> String {
319 let mut names = MaybeUninit::<libc::utsname>::uninit();
320 if unsafe { libc::uname(names.as_mut_ptr()) } != 0 {
322 return String::from("(unknown)");
323 }
324 let names = unsafe { names.assume_init() };
326 unsafe { CStr::from_ptr(names.machine.as_ptr()) }
328 .to_string_lossy()
329 .into_owned()
330}
331
332fn umask_of_status(status: &str) -> Option<u32> {
335 status.lines().find_map(|line| {
336 let value = line.strip_prefix("Umask:")?;
337 u32::from_str_radix(value.trim(), 8).ok()
338 })
339}
340
341fn cpu_models_of_info(info: &str) -> Vec<String> {
343 info.lines()
344 .filter_map(|line| {
345 let (key, value) = line.split_once(':')?;
346 (key.trim() == "model name").then(|| value.trim().to_owned())
347 })
348 .collect::<BTreeSet<_>>()
349 .into_iter()
350 .collect()
351}
352
353#[cfg(test)]
356pub(crate) struct CpuModelCollision {
357 pub(crate) stored: Vec<String>,
359 pub(crate) stored_text: &'static str,
361 pub(crate) current: Vec<String>,
363 pub(crate) current_text: &'static str,
365}
366
367#[cfg(test)]
373pub(crate) fn colliding_cpu_models() -> Vec<CpuModelCollision> {
374 let collision = |stored: &[&str],
375 stored_text: &'static str,
376 current: &[&str],
377 current_text: &'static str| {
378 CpuModelCollision {
379 stored: stored.iter().copied().map(String::from).collect(),
380 stored_text,
381 current: current.iter().copied().map(String::from).collect(),
382 current_text,
383 }
384 };
385 vec![
386 collision(&[], "[]", &["none"], r#"["none"]"#),
387 collision(&[], "[]", &[""], r#"[""]"#),
388 collision(&[""], r#"[""]"#, &["none"], r#"["none"]"#),
389 collision(&["A; B"], r#"["A; B"]"#, &["A", "B"], r#"["A", "B"]"#),
390 collision(
391 &[r#"A", "B"#],
392 r#"["A\", \"B"]"#,
393 &["A", "B"],
394 r#"["A", "B"]"#,
395 ),
396 ]
397}
398
399#[cfg(test)]
401#[allow(
402 clippy::disallowed_macros,
403 clippy::disallowed_methods,
404 reason = "test code: the tests assert and lock"
405)]
406mod tests {
407 use super::*;
408
409 fn identity() -> CacheIdentity {
411 CacheIdentity {
412 host: String::from("builder"),
413 user: 1000,
414 group: 100,
415 groups: vec![10, 100],
416 umask: Some(0o022),
417 machine: String::from("x86_64"),
418 cpu_models: vec![String::from("Example CPU")],
419 }
420 }
421
422 #[test]
425 fn the_umask_is_the_octal_value_of_its_status_line() {
426 let status = "Name:\tkizz\nUmask:\t0027\nState:\tR (running)\n";
427 assert_eq!(umask_of_status(status), Some(0o027));
428 assert_eq!(umask_of_status("Name:\tkizz\n"), None);
429 assert_eq!(umask_of_status("Umask:\t0089\n"), None);
430 }
431
432 #[test]
435 fn cpu_models_are_the_sorted_distinct_model_names() {
436 let info = "processor\t: 0\nmodel name\t: Fast Core\nflags\t\t: fpu\n\nprocessor\t: \
437 1\nmodel name\t: Efficient Core\n\nprocessor\t: 2\nmodel name\t: Fast Core\n";
438 assert_eq!(cpu_models_of_info(info), vec![
439 String::from("Efficient Core"),
440 String::from("Fast Core"),
441 ]);
442 assert_eq!(
443 cpu_models_of_info("processor\t: 0\nCPU part\t: 0xd0c\n"),
444 Vec::<String>::new()
445 );
446 }
447
448 #[test]
450 fn the_same_identity_has_no_differences() {
451 assert_eq!(identity().differences(&identity()), Vec::new());
452 }
453
454 #[test]
459 fn differences_compare_the_fields_not_their_text() {
460 for CpuModelCollision {
461 stored: stored_models,
462 stored_text,
463 current: current_models,
464 current_text,
465 } in colliding_cpu_models()
466 {
467 let stored = CacheIdentity {
468 cpu_models: stored_models,
469 ..identity()
470 };
471 let current = CacheIdentity {
472 cpu_models: current_models,
473 ..identity()
474 };
475 assert_eq!(IdentityPart::CpuModel.value(&stored), stored_text);
476 assert_eq!(IdentityPart::CpuModel.value(¤t), current_text);
477 assert_ne!(stored_text, current_text);
478 let differences = stored.differences(¤t);
479 assert_eq!(
480 differences,
481 vec![IdentityDifference {
482 part: IdentityPart::CpuModel,
483 stored: String::from(stored_text),
484 current: String::from(current_text),
485 }],
486 "{stored:?} and {current:?}"
487 );
488 assert_eq!(
489 identity_differences_text(&differences),
490 format!("CPU model: {stored_text} in the cache, {current_text} now")
491 );
492 assert!(IdentityPart::CpuModel.differs(&stored, ¤t));
493 assert!(!IdentityPart::CpuModel.differs(&stored, &stored));
494 }
495 let changed = [
496 (IdentityPart::Host, CacheIdentity {
497 host: String::from("other-builder"),
498 ..identity()
499 }),
500 (IdentityPart::User, CacheIdentity {
501 user: 1001,
502 ..identity()
503 }),
504 (IdentityPart::Group, CacheIdentity {
505 group: 101,
506 ..identity()
507 }),
508 (IdentityPart::Groups, CacheIdentity {
509 groups: vec![10],
510 ..identity()
511 }),
512 (IdentityPart::Umask, CacheIdentity {
513 umask: None,
514 ..identity()
515 }),
516 (IdentityPart::Machine, CacheIdentity {
517 machine: String::from("other-architecture"),
518 ..identity()
519 }),
520 (IdentityPart::CpuModel, CacheIdentity {
521 cpu_models: Vec::new(),
522 ..identity()
523 }),
524 ];
525 for (part, other) in changed {
526 for candidate in IdentityPart::ALL {
527 assert_eq!(
528 candidate.differs(&identity(), &other),
529 candidate == part,
530 "{candidate} when {part} changed"
531 );
532 }
533 }
534 }
535
536 #[test]
540 fn values_show_every_case() {
541 let mut other = identity();
542 other.host = String::from("say \"hi\"\\\tthere\n");
543 other.groups.clear();
544 other.umask = None;
545 other.cpu_models = vec![String::from("A"), String::from("B")];
546 let differences = identity().differences(&other);
547 assert_eq!(
548 identity_differences_text(&differences),
549 concat!(
550 r#"host name: "builder" in the cache, "say \"hi\"\\\u{9}there\u{a}" now; "#,
551 "supplementary groups: [10, 100] in the cache, [] now; ",
552 "umask: 0022 in the cache, unknown now; ",
553 r#"CPU model: ["Example CPU"] in the cache, ["A", "B"] now"#,
554 )
555 );
556 assert_eq!(IdentityPart::User.value(&identity()), "1000");
557 assert_eq!(IdentityPart::Group.value(&identity()), "100");
558 assert_eq!(IdentityPart::Machine.value(&identity()), r#""x86_64""#);
559 assert_eq!(IdentityPart::Groups.value(&other), "[]");
560 other.groups = vec![0];
561 assert_eq!(IdentityPart::Groups.value(&other), "[0]");
562 other.umask = Some(0);
563 assert_eq!(IdentityPart::Umask.value(&other), "0000");
564 other.cpu_models.clear();
565 assert_eq!(IdentityPart::CpuModel.value(&other), "[]");
566 }
567
568 #[test]
571 fn the_identity_encodes_deterministically_and_round_trips() {
572 let mut unknown = identity();
573 unknown.groups.clear();
574 unknown.umask = None;
575 unknown.cpu_models.clear();
576 for record in [identity(), unknown] {
577 let first = minicbor::to_vec(&record).unwrap();
578 assert_eq!(minicbor::to_vec(&record).unwrap(), first);
579 assert_eq!(minicbor::decode::<CacheIdentity>(&first).unwrap(), record);
580 assert_eq!(first.get(..2), Some(&[0x87, 0x67][..]));
583 }
584 }
585
586 #[test]
589 fn identity_keys_round_trip() {
590 let mut bytes = Vec::new();
591 IdentityKey.encode_key(&mut bytes);
592 assert_eq!(bytes, b"identity");
593 assert_eq!(IdentityKey::decode_key(&bytes), Some(IdentityKey));
594 assert_eq!(IdentityKey::decode_key(b"schema-version"), None);
595 assert_eq!(
596 crate::records::database_key::<CacheIdentity>(&IdentityKey),
597 b"meta/identity"
598 );
599 }
600}