use crate::error::{Error, RecordErrorKind};
use super::{backend, ProcessId, RawPid, StartToken};
pub const RECORD_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Platform {
Linux,
MacOs,
Windows,
Other(String),
}
impl Platform {
#[cfg(windows)]
pub fn current() -> Platform {
Platform::Windows
}
#[cfg(target_os = "linux")]
pub fn current() -> Platform {
Platform::Linux
}
#[cfg(target_os = "macos")]
pub fn current() -> Platform {
Platform::MacOs
}
pub fn as_str(&self) -> &str {
match self {
Platform::Linux => "linux",
Platform::MacOs => "macos",
Platform::Windows => "windows",
Platform::Other(s) => s,
}
}
pub fn from_wire(s: &str) -> Platform {
match s {
"linux" => Platform::Linux,
"macos" => Platform::MacOs,
"windows" => Platform::Windows,
other => Platform::Other(other.to_owned()),
}
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Platform {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Platform {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Platform, D::Error> {
Ok(Platform::from_wire(&String::deserialize(d)?))
}
}
#[cfg(feature = "serde")]
mod token_str {
pub(super) fn serialize<S: serde::Serializer>(v: &u64, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&v.to_string())
}
pub(super) fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
use serde::Deserialize;
let s = String::deserialize(d)?;
s.parse::<u64>().map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ProcessIdRecord {
#[cfg_attr(feature = "serde", serde(rename = "v"))]
pub version: u32,
pub platform: Platform,
pub pid: RawPid,
#[cfg_attr(feature = "serde", serde(with = "token_str"))]
pub token: u64,
#[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
pub boot_id: Option<String>,
#[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
pub pid_ns: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub(crate) struct Scope {
pub(crate) boot_id: Option<String>,
pub(crate) pid_ns: Option<u64>,
}
impl Scope {
#[cfg_attr(target_os = "linux", allow(dead_code))]
pub(crate) fn none() -> Scope {
Scope::default()
}
}
#[derive(Debug)]
pub(crate) struct ScopeReadError {
pub(crate) path: String,
pub(crate) source: std::io::Error,
}
pub(crate) fn scope_error(e: ScopeReadError) -> Error {
Error::IdentityRecord {
kind: RecordErrorKind::ScopeUnreadable,
detail: format!("{} could not be read: {}", e.path, e.source),
source: Some(e.source),
}
}
fn pid_is_addressable(pid: RawPid, here: &Platform) -> bool {
match here {
Platform::Windows => pid != 0,
_ => super::probe::signal_target(pid).is_some(),
}
}
pub(crate) fn reject(record: &ProcessIdRecord, scope: &Scope, kind: RecordErrorKind) -> Error {
Error::IdentityRecord {
kind,
detail: format!(
"record v{} from {} for pid {} (boot_id {:?} vs live {:?}, pid_ns {:?} vs live {:?})",
record.version,
record.platform.as_str(),
record.pid,
record.boot_id,
scope.boot_id,
record.pid_ns,
scope.pid_ns,
),
source: None,
}
}
pub(crate) fn validate(
record: &ProcessIdRecord,
here: &Platform,
scope: &Scope,
) -> Result<(RawPid, u64), RecordErrorKind> {
if record.version != RECORD_VERSION {
return Err(RecordErrorKind::UnknownVersion);
}
if &record.platform != here {
return Err(RecordErrorKind::ForeignPlatform);
}
if !pid_is_addressable(record.pid, here) {
return Err(RecordErrorKind::InvalidPid);
}
if let Some(live) = &scope.boot_id {
match &record.boot_id {
None => return Err(RecordErrorKind::MissingBootSession),
Some(saved) if saved != live => return Err(RecordErrorKind::ForeignBootSession),
Some(_) => {}
}
}
if let Some(live) = scope.pid_ns {
match record.pid_ns {
None => return Err(RecordErrorKind::MissingPidNamespace),
Some(saved) if saved != live => return Err(RecordErrorKind::ForeignPidNamespace),
Some(_) => {}
}
}
Ok((record.pid, record.token))
}
fn record_from(id: &ProcessId, scope: Result<Scope, ScopeReadError>) -> Result<ProcessIdRecord, Error> {
let scope = scope.map_err(scope_error)?;
Ok(ProcessIdRecord {
version: RECORD_VERSION,
platform: Platform::current(),
pid: id.pid,
token: id.start.raw(),
boot_id: scope.boot_id,
pid_ns: scope.pid_ns,
})
}
fn restore(
record: &ProcessIdRecord,
here: &Platform,
scope: Result<Scope, ScopeReadError>,
) -> Result<ProcessId, Error> {
let scope = scope.map_err(scope_error)?;
let (pid, token) = validate(record, here, &scope).map_err(|kind| reject(record, &scope, kind))?;
Ok(ProcessId {
pid,
start: StartToken::from_raw(token),
})
}
impl ProcessId {
pub fn to_record(&self) -> Result<ProcessIdRecord, Error> {
record_from(self, backend::session_scope())
}
}
impl TryFrom<&ProcessIdRecord> for ProcessId {
type Error = Error;
fn try_from(record: &ProcessIdRecord) -> Result<ProcessId, Error> {
restore(record, &Platform::current(), backend::session_scope())
}
}
impl TryFrom<ProcessIdRecord> for ProcessId {
type Error = Error;
fn try_from(record: ProcessIdRecord) -> Result<ProcessId, Error> {
ProcessId::try_from(&record)
}
}
#[cfg(test)]
#[path = "persist_tests.rs"]
mod persist_tests;
#[cfg(test)]
#[path = "persist_serde_tests.rs"]
mod persist_serde_tests;