524 lines
32 KiB
Rust
524 lines
32 KiB
Rust
//! Read-only legacy import. Only a completely validated sibling staging tree becomes a profile.
|
|
use super::{Result, ServiceError};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::Value;
|
|
use sha2::{Digest, Sha256};
|
|
use std::{collections::{BTreeMap, BTreeSet}, fs::{self, File, Metadata, OpenOptions}, io::Read, path::{Component, Path, PathBuf}, time::SystemTime};
|
|
use teamspeach_core::{profile::Store, secure_fs};
|
|
|
|
const FILES: &[&str] = &["core/identity.json", "core/identities.json", "core/profile.json", "prefs.json", "files-settings.json", "client-volumes.json", "whisper.json", "keybinds.json"];
|
|
const TREES: &[&str] = &["chat-history/v1", "extensions"];
|
|
const MAX_FILE: u64 = 128 * 1024 * 1024;
|
|
const MAX_TOTAL: u64 = 2 * 1024 * 1024 * 1024;
|
|
const MAX_ENTRIES: usize = 50_000;
|
|
const MARKER: &str = "native-profile.json";
|
|
const STAGING_OWNER: &str = ".teamspeach-import-owner.json";
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct StagingOwner { version: u32, owner: String, destination: PathBuf }
|
|
|
|
// Resolve existing ancestors without creating anything. This also resolves path aliases before
|
|
// comparing a selected source with the not-yet-created destination and its sibling staging tree.
|
|
fn resolved_path(path: &Path) -> Result<PathBuf> {
|
|
require_absolute(path)?;
|
|
let mut existing = path;
|
|
while !exists(existing)? {
|
|
existing = existing.parent().ok_or_else(|| err("invalid_profile_path", "Missing path ancestor"))?;
|
|
}
|
|
Ok(fs::canonicalize(existing)?.join(path.strip_prefix(existing).map_err(|_| err("invalid_profile_path", "Invalid path ancestor"))?))
|
|
}
|
|
|
|
fn require_owned_staging(root: &Path, source: &ConfinedSource) -> Result<()> {
|
|
let collision = || err("staging_path_collision", "The staging path is not an import owned by this destination; it will not be deleted");
|
|
let bytes = source.read(Path::new(STAGING_OWNER))?.ok_or_else(collision)?;
|
|
let owner: StagingOwner = serde_json::from_slice(&bytes).map_err(|_| collision())?;
|
|
if owner.version != 1 || owner.owner != "teamspeach-native-profile-import" || owner.destination != resolved_path(root)? {
|
|
return Err(collision());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct RequiredPassword { pub bookmark_id: String, pub purpose: String, pub address: String }
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct UnmappedDevices { pub input: Vec<String>, pub output: Vec<String>, pub notification: Option<String> }
|
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct MigrationState {
|
|
pub version: u32,
|
|
pub source_root: PathBuf,
|
|
pub required_passwords: Vec<RequiredPassword>,
|
|
pub unmapped_devices: UnmappedDevices,
|
|
}
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub struct ImportReport { pub native_root: PathBuf, pub copied_files: usize, pub copied_bytes: u64, pub default_uid: String, pub identity_uids: Vec<String>, pub migration: MigrationState, pub warnings: Vec<String> }
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum ProfileRootState { Fresh, Native, Interrupted { staging: PathBuf } }
|
|
fn err(code: &str, message: &str) -> ServiceError { ServiceError::new(code, message) }
|
|
|
|
/// Mobile callers provide filesDir (Android) or Application Support (iOS), never an Activity.
|
|
pub fn resolve_profile_root(explicit: Option<&Path>, mobile_container: Option<&Path>) -> Result<PathBuf> {
|
|
let environment_override = std::env::var_os("TEAMSPEACH_PROFILE_DIR").map(PathBuf::from);
|
|
if let Some(path) = explicit.or(environment_override.as_deref()) {
|
|
require_absolute(path)?;
|
|
return Ok(path.to_path_buf());
|
|
}
|
|
if cfg!(any(target_os = "android", target_os = "ios")) {
|
|
let path = mobile_container.ok_or_else(|| err("profile_location_required", "The platform must supply its private application container"))?;
|
|
require_absolute(path)?;
|
|
return Ok(path.join("profile-v1"));
|
|
}
|
|
Ok(desktop_config_base()?.join("TeamsPeachNative"))
|
|
}
|
|
fn desktop_config_base() -> Result<PathBuf> {
|
|
let path = if cfg!(windows) { std::env::var_os("APPDATA").map(PathBuf::from) }
|
|
else if cfg!(target_os = "macos") { std::env::var_os("HOME").map(|p| PathBuf::from(p).join("Library/Application Support")) }
|
|
else { std::env::var_os("XDG_CONFIG_HOME").filter(|p| !p.is_empty()).map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|p| PathBuf::from(p).join(".config"))) };
|
|
let path = path.ok_or_else(|| err("profile_location_required", "The operating system profile directory is unavailable"))?;
|
|
require_absolute(&path)?;
|
|
Ok(path)
|
|
}
|
|
fn require_absolute(path: &Path) -> Result<()> {
|
|
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir | Component::CurDir)) { return Err(err("invalid_profile_path", "An absolute normalized profile path is required")); }
|
|
Ok(())
|
|
}
|
|
/// Returns every existing candidate; never selects a winner or examines key contents.
|
|
pub fn legacy_candidates() -> Result<Vec<PathBuf>> {
|
|
if cfg!(any(target_os = "android", target_os = "ios")) { return Ok(Vec::new()); }
|
|
discover_legacy_candidates(&desktop_config_base()?)
|
|
}
|
|
pub fn discover_legacy_candidates(base: &Path) -> Result<Vec<PathBuf>> {
|
|
let mut found = Vec::new();
|
|
for name in ["teamspeach", "TeamsPeach"] {
|
|
let path = base.join(name);
|
|
if !exists(&path)? { continue; }
|
|
let source = ConfinedSource::open(&path)?;
|
|
let mut contains_profile_file = false;
|
|
for name in FILES {
|
|
contains_profile_file |= source.metadata(Path::new(name))?.is_some_and(|m| m.is_file());
|
|
}
|
|
if contains_profile_file {
|
|
let canonical = fs::canonicalize(&path)?;
|
|
if !found.contains(&canonical) { found.push(canonical); }
|
|
}
|
|
}
|
|
Ok(found)
|
|
}
|
|
fn exists(path: &Path) -> Result<bool> { match fs::symlink_metadata(path) { Ok(_) => Ok(true), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), Err(e) => Err(e.into()) } }
|
|
pub fn staging_path(root: &Path) -> Result<PathBuf> {
|
|
require_absolute(root)?;
|
|
let name = root.file_name().ok_or_else(|| err("invalid_profile_path", "A profile cannot be a filesystem root"))?;
|
|
let mut staging = std::ffi::OsString::from("."); staging.push(name); staging.push(".import-staging");
|
|
Ok(root.with_file_name(staging))
|
|
}
|
|
pub fn inspect_native_root(root: &Path) -> Result<ProfileRootState> {
|
|
require_absolute(root)?;
|
|
if exists(root)? {
|
|
let source = ConfinedSource::open(root)?;
|
|
let marker = source.read(Path::new(MARKER))?;
|
|
if let Some(bytes) = marker {
|
|
if serde_json::from_slice::<Value>(&bytes)? == serde_json::json!({"version":1}) { return Ok(ProfileRootState::Native); }
|
|
return Err(err("invalid_native_profile", "Unsupported native profile marker"));
|
|
}
|
|
return Err(err("legacy_profile_requires_import", "Existing unmarked profiles must be imported into a new native directory"));
|
|
}
|
|
let staging = staging_path(root)?;
|
|
if exists(&staging)? {
|
|
require_owned_staging(root, &ConfinedSource::open(&staging)?)?;
|
|
return Ok(ProfileRootState::Interrupted { staging });
|
|
}
|
|
Ok(ProfileRootState::Fresh)
|
|
}
|
|
/// Used before account-free onboarding; never adopts an existing unmarked directory.
|
|
pub fn initialize_native_root(root: &Path) -> Result<()> {
|
|
match inspect_native_root(root)? {
|
|
ProfileRootState::Native => return Ok(()),
|
|
ProfileRootState::Interrupted { .. } => return Err(err("import_interrupted", "Retry or discard the interrupted import before creating a profile")),
|
|
ProfileRootState::Fresh => {}
|
|
}
|
|
let staging = create_staging(root)?;
|
|
write_private(&staging.join(MARKER), b"{\"version\":1}")?;
|
|
activate(&staging, root)
|
|
}
|
|
/// Explicit recovery action. This never deletes a source or an active profile.
|
|
pub fn discard_interrupted_import(root: &Path, confirmed: bool) -> Result<()> {
|
|
if !confirmed { return Err(err("confirmation_required", "Confirm discarding the incomplete import")); }
|
|
if exists(root)? { return Err(err("profile_exists", "An active destination profile already exists")); }
|
|
let staging = staging_path(root)?;
|
|
// Deny links at every descendant before deletion; only the fixed sibling is eligible.
|
|
let source = ConfinedSource::open(&staging)?;
|
|
require_owned_staging(root, &source)?;
|
|
let mut count = 0;
|
|
validate_tree(&source, Path::new(""), 0, &mut count)?;
|
|
drop(source);
|
|
fs::remove_dir_all(staging)?;
|
|
Ok(())
|
|
}
|
|
fn private_dir(path: &Path) -> Result<()> {
|
|
secure_fs::ensure_private_dir(path)?;
|
|
#[cfg(windows)] secure_fs::win::set_owner_only(path)?;
|
|
#[cfg(target_os = "ios")] protect_ios(path)?;
|
|
Ok(())
|
|
}
|
|
fn create_staging(root: &Path) -> Result<PathBuf> {
|
|
let parent = root.parent().ok_or_else(|| err("invalid_profile_path", "Missing profile parent"))?;
|
|
fs::create_dir_all(parent)?;
|
|
let _parent = ConfinedSource::open(parent)?;
|
|
let staging = staging_path(root)?;
|
|
match fs::create_dir(&staging) {
|
|
Ok(()) => {}
|
|
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
|
|
require_owned_staging(root, &ConfinedSource::open(&staging)?)?;
|
|
return Err(err("import_interrupted", "An owned incomplete import exists; explicitly discard it before retrying"));
|
|
}
|
|
Err(e) => return Err(e.into()),
|
|
}
|
|
private_dir(&staging)?;
|
|
let owner = StagingOwner { version: 1, owner: "teamspeach-native-profile-import".to_owned(), destination: resolved_path(root)? };
|
|
write_private(&staging.join(STAGING_OWNER), &serde_json::to_vec(&owner)?)?;
|
|
Ok(staging)
|
|
}
|
|
fn write_private(path: &Path, data: &[u8]) -> Result<()> {
|
|
if let Some(parent) = path.parent() { private_dir(parent)?; }
|
|
secure_fs::write_atomic(path, data, true)?;
|
|
#[cfg(target_os = "ios")] protect_ios(path)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn load_migration(root: &Path) -> Result<Option<MigrationState>> {
|
|
let source = ConfinedSource::open(root)?;
|
|
let Some(bytes) = source.read(Path::new("migration.json"))? else { return Ok(None) };
|
|
let state: MigrationState = serde_json::from_slice(&bytes)?;
|
|
if state.version != 1 || !state.source_root.is_absolute() || state.required_passwords.iter().any(|m| !matches!(m.purpose.as_str(), "server" | "channel") || m.bookmark_id.is_empty() || m.address != m.address.trim()) {
|
|
return Err(err("invalid_migration", "Invalid migration metadata"));
|
|
}
|
|
Ok(Some(state))
|
|
}
|
|
pub fn save_migration(root: &Path, state: &MigrationState) -> Result<()> {
|
|
if state.version != 1 { return Err(err("invalid_migration", "Unsupported migration version")); }
|
|
write_private(&root.join("migration.json"), &serde_json::to_vec_pretty(state)?)
|
|
}
|
|
/// Caller persists the OS secret first. Failure leaves the re-entry requirement in place.
|
|
pub fn clear_required_password(root: &Path, bookmark_id: &str, purpose: &str, address: &str) -> Result<()> {
|
|
let file = OpenOptions::new().write(true).create(true).truncate(false).open(root.join("migration.lock"))?;
|
|
teamspeach_core::file_lock::lock(&file, false)?;
|
|
if let Some(mut state) = load_migration(root)? {
|
|
let before = state.required_passwords.len();
|
|
state.required_passwords.retain(|m| !(m.bookmark_id == bookmark_id && m.purpose == purpose && m.address == address.trim()));
|
|
if before != state.required_passwords.len() { save_migration(root, &state)?; }
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn import_profile(source_root: &Path, native_root: &Path) -> Result<ImportReport> {
|
|
import_with_hook(source_root, native_root, || Ok(()))
|
|
}
|
|
fn import_with_hook(source_root: &Path, native_root: &Path, after_copy: impl FnOnce() -> Result<()>) -> Result<ImportReport> {
|
|
require_absolute(source_root)?; require_absolute(native_root)?;
|
|
let source = ConfinedSource::open(source_root)?;
|
|
let canonical_source = fs::canonicalize(source_root)?;
|
|
// Resolve the destination parent before writing, including aliases/case on Windows.
|
|
if exists(native_root)? { return Err(err("profile_exists", "Import is only available before creating the native profile")); }
|
|
let destination = resolved_path(native_root)?;
|
|
let staging = resolved_path(&staging_path(native_root)?)?;
|
|
for target in [&destination, &staging] {
|
|
if canonical_source.starts_with(target) || target.starts_with(&canonical_source) {
|
|
return Err(err("profile_path_collision", "Source, destination and staging profile trees must not overlap"));
|
|
}
|
|
}
|
|
let _locks = source.lock_existing()?;
|
|
let before = snapshot(&source)?;
|
|
if !before.contains_key(Path::new("core/identity.json")) && !before.contains_key(Path::new("core/identities.json")) {
|
|
return Err(err("identity_missing", "No identity exists in the selected legacy profile"));
|
|
}
|
|
let staging = create_staging(native_root)?;
|
|
let mut copied_bytes = 0;
|
|
let mut copied_files = 0;
|
|
for (relative, stamp) in &before {
|
|
if stamp.directory { if !relative.as_os_str().is_empty() { private_dir(&staging.join(relative))?; } continue; }
|
|
let bytes = source.read(relative)?.ok_or_else(|| err("source_changed", "Close the legacy client and retry: a source file disappeared"))?;
|
|
if Sha256::digest(&bytes).as_slice() != stamp.hash.as_slice() { return Err(err("source_changed", "Close the legacy client and retry: a source file changed")); }
|
|
write_private(&staging.join(relative), &bytes)?;
|
|
copied_bytes += bytes.len() as u64; copied_files += 1;
|
|
}
|
|
// All Store reads run against staging, never the user's source profile.
|
|
let store = Store::new(staging.join("core"));
|
|
let vault = store.list().map_err(|_| err("identity_corrupt", "The legacy identity vault is invalid; no identity was generated"))?;
|
|
let default_uid = vault.default_id.clone().ok_or_else(|| err("identity_missing", "The legacy vault has no default identity"))?;
|
|
// Validate an extant legacy key even when every indexed key is embedded in the vault.
|
|
if exists(&staging.join("core/identity.json"))? {
|
|
let validation = staging.join(".legacy-validation"); private_dir(&validation)?;
|
|
for name in ["identity.json", "profile.json"] {
|
|
let file = staging.join("core").join(name);
|
|
if exists(&file)? { write_private(&validation.join(name), &fs::read(file)?)?; }
|
|
}
|
|
Store::new(&validation).load_identity().map_err(|_| err("identity_corrupt", "The legacy identity or nickname is invalid"))?.ok_or_else(|| err("identity_missing", "Missing legacy key"))?;
|
|
fs::remove_dir_all(validation)?;
|
|
}
|
|
let mut migration = MigrationState { version: 1, source_root: canonical_source, required_passwords: Vec::new(), unmapped_devices: UnmappedDevices::default() };
|
|
let mut warnings = Vec::new();
|
|
let prefs_path = staging.join("prefs.json");
|
|
if exists(&prefs_path)? {
|
|
let bytes = fs::read(&prefs_path)?;
|
|
match serde_json::from_slice::<Value>(&bytes) {
|
|
Ok(mut prefs) if prefs.is_object() => {
|
|
if prefs.get("nativeDeviceMappings").is_some() {
|
|
return Err(err("invalid_migration", "A legacy import cannot carry native device authorization"));
|
|
}
|
|
strip_electron_secrets(&mut prefs, &mut migration)?;
|
|
let normalized = super::prefs::normalize_loaded(&prefs);
|
|
let known_uids: Vec<String> = vault.identities.iter().map(|identity| identity.uid.clone()).collect();
|
|
super::bookmarks::validate_identity_references(&normalized.0, &known_uids)?;
|
|
warnings.extend(normalized.1);
|
|
migration.unmapped_devices = collect_devices(&prefs);
|
|
// Imported microphone remains disabled via the absent native confirmation ledger.
|
|
// No DSP/device identifiers or unrelated preferences are rewritten here.
|
|
write_private(&prefs_path, &serde_json::to_vec_pretty(&prefs)?)?;
|
|
}
|
|
_ => {
|
|
// Keep the malformed original for diagnosis, not as a live password-bearing prefs file.
|
|
fs::rename(&prefs_path, staging.join("prefs.corrupt.json"))?;
|
|
warnings.push("Corrupt preferences preserved as prefs.corrupt.json; defaults require an explicit save".to_owned());
|
|
}
|
|
}
|
|
}
|
|
save_migration(&staging, &migration)?;
|
|
write_private(&staging.join(MARKER), b"{\"version\":1}")?;
|
|
after_copy()?;
|
|
if before != snapshot(&source)? { return Err(err("source_changed", "Close the legacy client and retry: source files changed during import")); }
|
|
sync_tree(&staging)?;
|
|
activate(&staging, native_root)?;
|
|
Ok(ImportReport { native_root: native_root.to_path_buf(), copied_files, copied_bytes, default_uid, identity_uids: vault.identities.into_iter().map(|i| i.uid).collect(), migration, warnings })
|
|
}
|
|
fn strip_electron_secrets(prefs: &mut Value, migration: &mut MigrationState) -> Result<()> {
|
|
let Some(bookmarks) = prefs.get_mut("savedServers").and_then(Value::as_array_mut) else { return Ok(()) };
|
|
for bookmark in bookmarks {
|
|
let Some(object) = bookmark.as_object_mut() else { continue };
|
|
for (purpose, field) in [("server", "server_password_encrypted"), ("channel", "channel_password_encrypted")] {
|
|
if let Some(ciphertext) = object.remove(field) {
|
|
if ciphertext.as_str().is_some_and(str::is_empty) || ciphertext.is_null() { continue; }
|
|
let bookmark_id = object.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).ok_or_else(|| err("invalid_bookmark", "A password-bearing bookmark is missing its identity"))?;
|
|
let address = object.get("address").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).ok_or_else(|| err("invalid_bookmark", "A password-bearing bookmark is missing its address"))?;
|
|
migration.required_passwords.push(RequiredPassword { bookmark_id: bookmark_id.to_owned(), purpose: purpose.to_owned(), address: address.trim().to_owned() });
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
fn collect_devices(prefs: &Value) -> UnmappedDevices {
|
|
fn ids(prefs: &Value, selected: &str, dsp: &str) -> Vec<String> {
|
|
let mut ids = BTreeSet::new();
|
|
if let Some(id) = prefs.get(selected).and_then(Value::as_str).filter(|s| !s.is_empty() && *s != "default") { ids.insert(id.to_owned()); }
|
|
if let Some(devices) = prefs.get(dsp).and_then(|d| d.get("devices")).and_then(Value::as_object) { ids.extend(devices.keys().filter(|id| !id.is_empty() && id.as_str() != "default").cloned()); }
|
|
ids.into_iter().collect()
|
|
}
|
|
UnmappedDevices { input: ids(prefs, "inputDeviceId", "inputDsp"), output: ids(prefs, "outputDeviceId", "outputDsp"), notification: prefs.get("notificationDeviceId").and_then(Value::as_str).filter(|s| !matches!(*s, "" | "voice" | "none")).map(str::to_owned) }
|
|
}
|
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
struct Stamp { directory: bool, length: u64, modified: Option<SystemTime>, created: Option<SystemTime>, readonly: bool, hash: Vec<u8>, identity: [u64; 5] }
|
|
fn stamp(metadata: &Metadata, hash: Vec<u8>) -> Stamp {
|
|
#[cfg(unix)] let identity = { use std::os::unix::fs::MetadataExt; [metadata.dev(), metadata.ino(), metadata.mode() as u64, metadata.ctime() as u64, metadata.ctime_nsec() as u64] };
|
|
#[cfg(windows)] let identity = { use std::os::windows::fs::MetadataExt; [metadata.file_attributes() as u64, metadata.creation_time(), metadata.last_write_time(), metadata.file_size(), 0] };
|
|
Stamp { directory: metadata.is_dir(), length: metadata.len(), modified: metadata.modified().ok(), created: metadata.created().ok(), readonly: metadata.permissions().readonly(), hash, identity }
|
|
}
|
|
fn snapshot(source: &ConfinedSource) -> Result<BTreeMap<PathBuf, Stamp>> {
|
|
let mut result = BTreeMap::new(); let mut total = 0;
|
|
add_entry(source, Path::new(""), false, 0, &mut total, &mut result)?;
|
|
for name in ["core", "chat-history"] { add_entry(source, Path::new(name), false, 0, &mut total, &mut result)?; }
|
|
for name in FILES { add_entry(source, Path::new(name), false, 0, &mut total, &mut result)?; }
|
|
for name in TREES { add_entry(source, Path::new(name), true, 0, &mut total, &mut result)?; }
|
|
Ok(result)
|
|
}
|
|
fn add_entry(source: &ConfinedSource, relative: &Path, recurse: bool, depth: usize, total: &mut u64, result: &mut BTreeMap<PathBuf, Stamp>) -> Result<()> {
|
|
if depth > 32 || result.len() >= MAX_ENTRIES { return Err(err("import_limit", "Legacy profile exceeds traversal limits")); }
|
|
let Some(metadata) = source.metadata(relative)? else { return Ok(()) };
|
|
let hash = if metadata.is_file() {
|
|
*total = total.checked_add(metadata.len()).ok_or_else(|| err("import_limit", "Profile size overflow"))?;
|
|
if *total > MAX_TOTAL { return Err(err("import_limit", "Legacy profile exceeds the import size limit")); }
|
|
let mut file = source.open_file(relative)?;
|
|
let mut hash = Sha256::new(); let mut buffer = [0u8; 64 * 1024]; let mut count = 0;
|
|
loop { let n = file.read(&mut buffer)?; if n == 0 { break; } count += n as u64; if count > MAX_FILE { return Err(err("import_limit", "Source file exceeds the import size limit")); } hash.update(&buffer[..n]); }
|
|
if count != metadata.len() || stamp(&file.metadata()?, Vec::new()) != stamp(&metadata, Vec::new()) { return Err(err("source_changed", "Source changed while reading")); }
|
|
hash.finalize().to_vec()
|
|
} else { Vec::new() };
|
|
result.insert(relative.to_path_buf(), stamp(&metadata, hash));
|
|
if metadata.is_dir() && recurse {
|
|
for child in fs::read_dir(source.path.join(relative))? { let child = child?; add_entry(source, &relative.join(child.file_name()), true, depth + 1, total, result)?; }
|
|
}
|
|
Ok(())
|
|
}
|
|
fn validate_tree(source: &ConfinedSource, relative: &Path, depth: usize, count: &mut usize) -> Result<()> {
|
|
*count += 1;
|
|
if depth > 32 || *count > MAX_ENTRIES { return Err(err("import_limit", "Staging traversal limit exceeded")); }
|
|
if source.metadata(relative)?.is_some_and(|m| m.is_dir()) { for child in fs::read_dir(source.path.join(relative))? { validate_tree(source, &relative.join(child?.file_name()), depth + 1, count)?; } }
|
|
Ok(())
|
|
}
|
|
fn deny_link(metadata: &Metadata) -> Result<()> {
|
|
#[cfg(windows)] { use std::os::windows::fs::MetadataExt; if metadata.file_attributes() & 0x400 != 0 { return Err(err("profile_symlink", "Reparse points are not allowed in profile imports")); } }
|
|
if metadata.file_type().is_symlink() { return Err(err("profile_symlink", "Symbolic links are not allowed in profile imports")); }
|
|
if !metadata.is_dir() && !metadata.is_file() { return Err(err("profile_file_type", "Only regular files and directories can be imported")); }
|
|
Ok(())
|
|
}
|
|
struct ConfinedSource { path: PathBuf, root: File, _pins: Vec<File> }
|
|
impl ConfinedSource {
|
|
fn open(path: &Path) -> Result<Self> {
|
|
require_absolute(path)?;
|
|
let mut pins = Vec::new(); let mut current = PathBuf::new();
|
|
for component in path.components() {
|
|
current.push(component.as_os_str());
|
|
if matches!(component, Component::Prefix(_)) { continue; }
|
|
let metadata = fs::symlink_metadata(¤t)?; deny_link(&metadata)?;
|
|
if !metadata.is_dir() { return Err(err("invalid_profile_path", "Profile path is not a directory")); }
|
|
#[cfg(windows)] {
|
|
use std::os::windows::fs::OpenOptionsExt;
|
|
let file = OpenOptions::new().read(true).share_mode(3).custom_flags(0x02000000 | 0x00200000).open(¤t)?;
|
|
deny_link(&file.metadata()?)?; pins.push(file);
|
|
}
|
|
}
|
|
#[cfg(unix)] let root = open_unix_absolute(path)?;
|
|
#[cfg(windows)] let root = pins.last().ok_or_else(|| err("invalid_profile_path", "Missing directory handle"))?.try_clone()?;
|
|
Ok(Self { path: path.to_path_buf(), root, _pins: pins })
|
|
}
|
|
fn open_file(&self, relative: &Path) -> Result<File> {
|
|
if relative.components().any(|c| !matches!(c, Component::Normal(_))) { return Err(err("invalid_profile_path", "Unconfined relative path")); }
|
|
#[cfg(unix)] let file = open_unix_relative(&self.root, relative)?;
|
|
#[cfg(windows)] let file = {
|
|
use std::os::windows::fs::OpenOptionsExt;
|
|
let mut directory = self.path.clone(); let mut pins = Vec::new();
|
|
if let Some(parent) = relative.parent() { for component in parent.components() { directory.push(component.as_os_str()); let pin = OpenOptions::new().read(true).share_mode(3).custom_flags(0x02000000 | 0x00200000).open(&directory)?; deny_link(&pin.metadata()?)?; pins.push(pin); } }
|
|
let file = OpenOptions::new().read(true).share_mode(3).custom_flags(0x02000000 | 0x00200000).open(self.path.join(relative))?;
|
|
deny_link(&file.metadata()?)?;
|
|
file
|
|
};
|
|
deny_link(&file.metadata()?)?;
|
|
Ok(file)
|
|
}
|
|
fn metadata(&self, relative: &Path) -> Result<Option<Metadata>> {
|
|
if relative.as_os_str().is_empty() { return Ok(Some(self.root.metadata()?)); }
|
|
match self.open_file(relative) {
|
|
Ok(file) => Ok(Some(file.metadata()?)),
|
|
Err(_) if !exists(&self.path.join(relative))? => Ok(None),
|
|
Err(error) => Err(error),
|
|
}
|
|
}
|
|
fn read(&self, relative: &Path) -> Result<Option<Vec<u8>>> {
|
|
let Some(before) = self.metadata(relative)? else { return Ok(None) };
|
|
if !before.is_file() || before.len() > MAX_FILE { return Err(err("import_limit", "Expected a bounded regular file")); }
|
|
let file = self.open_file(relative)?;
|
|
let mut bytes = Vec::with_capacity(before.len() as usize);
|
|
(&file).take(MAX_FILE + 1).read_to_end(&mut bytes)?;
|
|
if bytes.len() as u64 != before.len() || stamp(&before, Vec::new()) != stamp(&file.metadata()?, Vec::new()) { return Err(err("source_changed", "Source file changed during reading")); }
|
|
Ok(Some(bytes))
|
|
}
|
|
fn lock_existing(&self) -> Result<Vec<File>> {
|
|
let mut locks = Vec::new();
|
|
for name in ["core/core.lock", "core/profile.lock"] {
|
|
let relative = Path::new(name);
|
|
if self.metadata(relative)?.is_none() { continue; }
|
|
let file = self.open_file(relative)?;
|
|
teamspeach_core::file_lock::try_lock(&file, false).map_err(|error| match error {
|
|
std::fs::TryLockError::WouldBlock => err("profile_occupied", "Close the legacy client before importing its profile"),
|
|
std::fs::TryLockError::Error(error) => error.into(),
|
|
})?;
|
|
locks.push(file);
|
|
}
|
|
Ok(locks)
|
|
}
|
|
}
|
|
#[cfg(unix)]
|
|
fn open_unix_absolute(path: &Path) -> Result<File> {
|
|
// Android grants search, not directory-read access, above the app sandbox.
|
|
#[cfg(target_os = "android")]
|
|
let root = {
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
OpenOptions::new().read(true).custom_flags(libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC).open("/")?
|
|
};
|
|
#[cfg(not(target_os = "android"))]
|
|
let root = File::open("/")?;
|
|
open_unix_relative(&root, path.strip_prefix("/").map_err(|_| err("invalid_profile_path", "Invalid absolute path"))?)
|
|
}
|
|
#[cfg(unix)]
|
|
fn open_unix_relative(root: &File, path: &Path) -> Result<File> {
|
|
use std::{ffi::CString, os::{fd::{AsRawFd, FromRawFd}, unix::ffi::OsStrExt}};
|
|
unsafe extern "C" { fn openat(fd: i32, path: *const std::ffi::c_char, flags: i32, ...) -> i32; }
|
|
// Android arm64 assigns O_NOFOLLOW a different bit than desktop Linux.
|
|
#[cfg(target_os = "android")]
|
|
use libc::{O_NOFOLLOW as NOFOLLOW, O_CLOEXEC as CLOEXEC, O_NONBLOCK as NONBLOCK};
|
|
#[cfg(any(target_os = "macos", target_os = "ios"))] const NOFOLLOW: i32 = 0x100;
|
|
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] const NOFOLLOW: i32 = 0x20000;
|
|
#[cfg(any(target_os = "macos", target_os = "ios"))] const CLOEXEC: i32 = 0x1000000;
|
|
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] const CLOEXEC: i32 = 0x80000;
|
|
#[cfg(any(target_os = "macos", target_os = "ios"))] const NONBLOCK: i32 = 4;
|
|
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] const NONBLOCK: i32 = 0x800;
|
|
let mut file = root.try_clone()?;
|
|
let mut components = path.components().peekable();
|
|
while let Some(component) = components.next() {
|
|
let Component::Normal(name) = component else { return Err(err("invalid_profile_path", "Invalid path component")) };
|
|
let name = CString::new(name.as_bytes()).map_err(|_| err("invalid_profile_path", "Invalid path byte"))?;
|
|
let flags = NOFOLLOW | CLOEXEC | NONBLOCK;
|
|
// Pin ancestors without requesting read/list permission. The final entry
|
|
// still needs normal read access; O_DIRECTORY + NOFOLLOW reject links.
|
|
#[cfg(target_os = "android")]
|
|
let flags = if components.peek().is_some() { flags | libc::O_PATH | libc::O_DIRECTORY } else { flags };
|
|
let fd = unsafe { openat(file.as_raw_fd(), name.as_ptr(), flags) }; // nonblocking prevents FIFO hangs; regular files unaffected
|
|
if fd < 0 { return Err(std::io::Error::last_os_error().into()); }
|
|
file = unsafe { File::from_raw_fd(fd) };
|
|
deny_link(&file.metadata()?)?;
|
|
}
|
|
Ok(file)
|
|
}
|
|
fn sync_tree(path: &Path) -> Result<()> {
|
|
for entry in fs::read_dir(path)? { let entry = entry?; if entry.file_type()?.is_dir() { sync_tree(&entry.path())?; } else { OpenOptions::new().write(true).open(entry.path())?.sync_all()?; } }
|
|
#[cfg(unix)] File::open(path)?.sync_all()?;
|
|
Ok(())
|
|
}
|
|
fn activate(staging: &Path, root: &Path) -> Result<()> {
|
|
// Unlike std::fs::rename on Unix, these primitives never replace even an empty destination.
|
|
#[cfg(unix)] {
|
|
use std::{ffi::CString, os::unix::ffi::OsStrExt};
|
|
let from = CString::new(staging.as_os_str().as_bytes()).map_err(|_| err("invalid_profile_path", "Invalid path"))?;
|
|
let to = CString::new(root.as_os_str().as_bytes()).map_err(|_| err("invalid_profile_path", "Invalid path"))?;
|
|
#[cfg(target_os = "linux")]
|
|
let status = { unsafe extern "C" { fn renameat2(oldfd: i32, old: *const std::ffi::c_char, newfd: i32, new: *const std::ffi::c_char, flags: u32) -> i32; } unsafe { renameat2(-100, from.as_ptr(), -100, to.as_ptr(), 1) } };
|
|
#[cfg(target_os = "android")]
|
|
let status = {
|
|
unsafe extern "C" { fn syscall(number: std::ffi::c_long, ...) -> std::ffi::c_long; }
|
|
#[cfg(target_arch = "aarch64")] const RENAMEAT2: std::ffi::c_long = 276;
|
|
#[cfg(target_arch = "x86_64")] const RENAMEAT2: std::ffi::c_long = 316;
|
|
// Bionic only exports renameat2 from API 30; the syscall is available at minSdk 26.
|
|
unsafe { syscall(RENAMEAT2, -100i32, from.as_ptr(), -100i32, to.as_ptr(), 1u32) as i32 }
|
|
};
|
|
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
|
let status = { unsafe extern "C" { fn renamex_np(old: *const std::ffi::c_char, new: *const std::ffi::c_char, flags: u32) -> i32; } unsafe { renamex_np(from.as_ptr(), to.as_ptr(), 4) } };
|
|
if status != 0 { return Err(std::io::Error::last_os_error().into()); }
|
|
File::open(root.parent().ok_or_else(|| err("invalid_profile_path", "Missing parent"))?)?.sync_all()?;
|
|
}
|
|
#[cfg(windows)] {
|
|
use std::os::windows::ffi::OsStrExt;
|
|
#[link(name = "kernel32")] unsafe extern "system" { fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32; }
|
|
let from: Vec<u16> = staging.as_os_str().encode_wide().chain(Some(0)).collect();
|
|
let to: Vec<u16> = root.as_os_str().encode_wide().chain(Some(0)).collect();
|
|
if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), 8) } == 0 { return Err(std::io::Error::last_os_error().into()); }
|
|
}
|
|
Ok(())
|
|
}
|
|
#[cfg(target_os = "ios")]
|
|
fn protect_ios(path: &Path) -> Result<()> {
|
|
use std::{ffi::CString, os::unix::ffi::OsStrExt};
|
|
unsafe extern "C" { fn fcntl(fd: i32, command: i32, ...) -> i32; }
|
|
use std::os::fd::AsRawFd;
|
|
let _ = CString::new(path.as_os_str().as_bytes()).map_err(|_| err("invalid_profile_path", "Invalid path"))?;
|
|
let file = File::open(path)?;
|
|
// Darwin F_SETPROTECTIONCLASS / PROTECTION_CLASS_C: available after first device unlock.
|
|
if unsafe { fcntl(file.as_raw_fd(), 64, 3) } == -1 { return Err(std::io::Error::last_os_error().into()); }
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "profile_import_tests.rs"]
|
|
mod tests;
|