mod host;
mod login_screen;
mod machine;
mod repl;
pub use crate::machine::{
Account, AuditCategory, Capability, Configuration, FileMetadata, FirewallRule, Group, Machine,
MachineBuilder, MachineError, OsKind, PasswordPolicy, PreferenceValue, Process, RegistryValue,
Service,
};
pub use engine::{
ActorId, AuthorizationData, CreateOptions, DetachedNamespace, Engine, Error as EngineError,
EventData, EventType, Id, Metadata, MetadataPatch, MetadataValue, Name, ObjectEvent, ObjectId,
ObjectKind, Operation, SubscriptionId, Timestamp, VirtualPath,
};
pub use os::{AccessClass, FileMode, OsError, Permission};
use os::Credentials;
use os::unix::unix_os::UnixOs;
use os::windows::Windows;
use shell::Shell;
use shell::bash::Bash;
use shell::cmd::Cmd;
use shell::powershell::PowerShell;
use shell::zsh::Zsh;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SessionInterruption {
Cancelled,
DeadlineExceeded,
}
#[derive(Debug, Default)]
struct SessionControlState {
cancelled: AtomicBool,
deadline: Mutex<Option<Instant>>,
}
#[derive(Clone, Debug, Default)]
pub struct SessionControl {
state: Arc<SessionControlState>,
}
impl SessionControl {
pub fn cancel(&self) {
self.state.cancelled.store(true, Ordering::Release);
}
pub fn reset_cancellation(&self) {
self.state.cancelled.store(false, Ordering::Release);
}
pub fn set_timeout(&self, timeout: Duration) {
*self.state.deadline.lock().expect("deadline lock poisoned") =
Instant::now().checked_add(timeout);
}
pub fn clear_deadline(&self) {
*self.state.deadline.lock().expect("deadline lock poisoned") = None;
}
pub fn interruption(&self) -> Option<SessionInterruption> {
if self.state.cancelled.load(Ordering::Acquire) {
return Some(SessionInterruption::Cancelled);
}
self.state
.deadline
.lock()
.expect("deadline lock poisoned")
.is_some_and(|deadline| Instant::now() >= deadline)
.then_some(SessionInterruption::DeadlineExceeded)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SessionOutcome {
Exited(i32),
Cancelled,
DeadlineExceeded,
}
impl From<SessionInterruption> for SessionOutcome {
fn from(value: SessionInterruption) -> Self {
match value {
SessionInterruption::Cancelled => Self::Cancelled,
SessionInterruption::DeadlineExceeded => Self::DeadlineExceeded,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShellChoice {
Bash,
Zsh,
PowerShell,
Cmd,
}
pub struct Session<'os> {
shell: Box<dyn Shell + 'os>,
exited: bool,
control: SessionControl,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommandOutput {
status: u8,
stdout: Vec<u8>,
stderr: Vec<u8>,
session_exited: bool,
}
impl CommandOutput {
pub const fn status(&self) -> u8 {
self.status
}
pub const fn success(&self) -> bool {
self.status == 0
}
pub fn stdout(&self) -> &[u8] {
&self.stdout
}
pub fn stdout_text(&self) -> String {
String::from_utf8_lossy(&self.stdout).into_owned()
}
pub fn stderr(&self) -> &[u8] {
&self.stderr
}
pub fn stderr_text(&self) -> String {
String::from_utf8_lossy(&self.stderr).into_owned()
}
pub const fn session_exited(&self) -> bool {
self.session_exited
}
}
#[derive(Debug)]
pub enum SessionError {
Shell(String),
ShellNotAvailable {
shell: ShellChoice,
os: &'static str,
},
Exited,
Cancelled,
DeadlineExceeded,
}
impl std::fmt::Display for SessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SessionError::Shell(message) => write!(f, "shell failed: {message}"),
SessionError::ShellNotAvailable { shell, os } => {
write!(f, "the {shell:?} shell is not available on {os}")
}
SessionError::Exited => f.write_str("the shell session has exited"),
SessionError::Cancelled => f.write_str("the shell session was cancelled"),
SessionError::DeadlineExceeded => f.write_str("the shell session deadline elapsed"),
}
}
}
impl std::error::Error for SessionError {}
impl<'os> Session<'os> {
#[doc(hidden)]
pub fn unix(
unix: &'os UnixOs,
credentials: Credentials,
choice: ShellChoice,
) -> Result<Self, SessionError> {
let shell: Box<dyn Shell + 'os> = match choice {
ShellChoice::Bash => Box::new(
Bash::new(unix, credentials)
.map_err(|error| SessionError::Shell(error.to_string()))?,
),
ShellChoice::Zsh => Box::new(
Zsh::new(unix, credentials)
.map_err(|error| SessionError::Shell(error.to_string()))?,
),
other => {
return Err(SessionError::ShellNotAvailable {
shell: other,
os: "Unix",
});
}
};
Ok(Self {
shell,
exited: false,
control: SessionControl::default(),
})
}
#[doc(hidden)]
pub fn windows(
windows: &'os Windows,
actor: engine::ActorId,
choice: ShellChoice,
) -> Result<Self, SessionError> {
let shell: Box<dyn Shell + 'os> = match choice {
ShellChoice::PowerShell => Box::new(
PowerShell::new(windows, actor, windows.environment().clone())
.map_err(|error| SessionError::Shell(error.to_string()))?,
),
ShellChoice::Cmd => Box::new(
Cmd::new(windows, actor, windows.environment().clone())
.map_err(|error| SessionError::Shell(error.to_string()))?,
),
other => {
return Err(SessionError::ShellNotAvailable {
shell: other,
os: "Windows",
});
}
};
Ok(Self {
shell,
exited: false,
control: SessionControl::default(),
})
}
#[doc(hidden)]
pub fn default_choice(credentials: &Credentials) -> ShellChoice {
if credentials.user().shell().ends_with("/zsh") {
ShellChoice::Zsh
} else {
ShellChoice::Bash
}
}
#[doc(hidden)]
pub const fn default_windows_choice() -> ShellChoice {
ShellChoice::PowerShell
}
pub fn shell_name(&self) -> &'static str {
self.shell.name()
}
pub fn control(&self) -> SessionControl {
self.control.clone()
}
fn check_control(&self) -> Result<(), SessionError> {
match self.control.interruption() {
Some(SessionInterruption::Cancelled) => Err(SessionError::Cancelled),
Some(SessionInterruption::DeadlineExceeded) => Err(SessionError::DeadlineExceeded),
None => Ok(()),
}
}
pub fn execute(&mut self, command: &str) -> Result<CommandOutput, SessionError> {
self.execute_with_input(command, [])
}
pub fn execute_with_input(
&mut self,
command: &str,
input: impl AsRef<[u8]>,
) -> Result<CommandOutput, SessionError> {
if self.exited {
return Err(SessionError::Exited);
}
self.check_control()?;
let mut stdin = engine::BytesInput::new(input.as_ref().to_vec());
let mut stdout = engine::BytesOutput::new();
let mut stderr = engine::BytesOutput::new();
let mut status = self
.shell
.execute(command, &mut stdin, &mut stdout, &mut stderr)
.code();
if let Some(exit_status) = self.shell.take_exit_status() {
status = exit_status.code();
self.exited = true;
}
self.check_control()?;
Ok(CommandOutput {
status,
stdout: stdout.into_bytes(),
stderr: stderr.into_bytes(),
session_exited: self.exited,
})
}
pub fn run_interactive(self) -> i32 {
match self.run_interactive_controlled() {
SessionOutcome::Exited(status) => status,
SessionOutcome::Cancelled => 130,
SessionOutcome::DeadlineExceeded => 124,
}
}
pub fn run_interactive_controlled(self) -> SessionOutcome {
let mut session = repl::InteractiveSession::new(self.shell, self.control);
session.run()
}
pub fn run_line<R: std::io::Read + Send + Sync>(mut self, input: &mut R) -> i32 {
match repl::run_line_mode_controlled(&mut *self.shell, input, &self.control) {
SessionOutcome::Exited(status) => status,
SessionOutcome::Cancelled => 130,
SessionOutcome::DeadlineExceeded => 124,
}
}
pub fn run_line_controlled<R: std::io::Read + Send + Sync>(
mut self,
input: &mut R,
) -> SessionOutcome {
repl::run_line_mode_controlled(&mut *self.shell, input, &self.control)
}
}
#[doc(hidden)]
pub fn login(unix: &UnixOs, user_name: &str) -> Result<Credentials, os::OsError> {
login_with_password(unix, user_name, user_name)
}
#[doc(hidden)]
pub fn login_with_password(
unix: &UnixOs,
user_name: &str,
password: &str,
) -> Result<Credentials, os::OsError> {
let result = unix
.users()
.authenticate(user_name, password, unix.groups());
unix.record_login_attempt(user_name, result.is_ok());
result
}
#[doc(hidden)]
pub fn login_windows(
windows: &Windows,
user_name: &str,
password: Option<&str>,
interactive: bool,
) -> Result<engine::ActorId, String> {
let user = windows
.users()
.by_name(user_name)
.ok_or_else(|| format!("login failed: no account named '{user_name}'"))?;
if !user.enabled() {
return Err(format!(
"login failed: the account '{user_name}' is disabled"
));
}
let password = match password {
Some(password) => password.to_owned(),
None if !user.has_password() => String::new(),
None if interactive => prompt_password(&format!("Password for {user_name}: ")),
None => {
let mut password = String::new();
let _ = std::io::stdin().read_line(&mut password);
password.trim_end().to_owned()
}
};
windows
.authenticate(user_name, &password)
.map_err(|_| format!("login failed: incorrect password for '{user_name}'"))
}
#[doc(hidden)]
pub fn prompt_password(prompt: &str) -> String {
use crossterm::event::{self, Event};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use std::io::Write as _;
let _ = enable_raw_mode();
print!("{prompt}");
let _ = std::io::stdout().flush();
let mut password = String::new();
loop {
let key = match event::read() {
Ok(Event::Key(key)) => key,
Ok(_) => continue,
Err(_) => break,
};
let Some(key) = crate::host::translate_key(&key) else {
continue;
};
match key.key {
engine::Key::Enter => break,
engine::Key::Backspace => {
password.pop();
}
engine::Key::Character => {
if key.ctrl && key.character == Some('c') {
password.clear();
break;
}
if !key.ctrl
&& let Some(character) = key.character
{
password.push(character);
}
}
_ => {}
}
}
let _ = disable_raw_mode();
println!();
password
}