Skip to main content

libobs_bootstrapper/
lib.rs

1#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
2#![allow(unknown_lints, require_safety_comments_on_unsafe)]
3
4use std::{env, fs, path::PathBuf};
5
6use cargo_obs_build::{
7    ObsBuildConfig, build_obs_binaries_verified, resolve_latest_compatible_release,
8};
9use semver::Version;
10
11pub mod build;
12mod error;
13mod options;
14pub mod status_handler;
15mod version;
16
17#[cfg(test)]
18mod options_tests;
19#[cfg(test)]
20mod version_tests;
21
22pub use error::ObsBootstrapError;
23pub use options::{DEFAULT_OBS_VERSION, GITHUB_REPO, ObsBootstrapperOptions, UpdateTargetMode};
24
25use crate::status_handler::{ObsBootstrapConsoleHandler, ObsBootstrapStatusHandler};
26
27/// Progress states retained for callers that model bootstrap UI separately.
28pub enum BootstrapStatus {
29    Downloading(f32, String),
30    Extracting(f32, String),
31    Error(ObsBootstrapError),
32    /// Legacy state from the old PowerShell updater flow. The current
33    /// bootstrapper prepares OBS before it is loaded and never emits this.
34    RestartRequired,
35}
36
37/// Explicit OBS runtime provisioning and local-installation inspection.
38///
39/// Calling [`ObsBootstrapper::bootstrap`] is the opt-in operation that may use
40/// the network. Merely depending on this crate or inspecting an installation
41/// never downloads or executes anything.
42pub struct ObsBootstrapper {}
43
44#[derive(Debug)]
45struct BootstrapPlan {
46    install_dir: PathBuf,
47    cache_dir: PathBuf,
48    repository: String,
49    target_version: Version,
50}
51
52fn default_install_dir() -> Result<PathBuf, ObsBootstrapError> {
53    let executable =
54        env::current_exe().map_err(|e| ObsBootstrapError::IoError("Getting current exe", e))?;
55    executable.parent().map(PathBuf::from).ok_or_else(|| {
56        ObsBootstrapError::IoError(
57            "Failed to get executable parent directory",
58            std::io::Error::from(std::io::ErrorKind::InvalidInput),
59        )
60    })
61}
62
63fn resolve_install_dir(options: &ObsBootstrapperOptions) -> Result<PathBuf, ObsBootstrapError> {
64    options
65        .get_install_dir()
66        .cloned()
67        .map(Ok)
68        .unwrap_or_else(default_install_dir)
69}
70
71fn resolve_cache_dir(options: &ObsBootstrapperOptions, install_dir: &std::path::Path) -> PathBuf {
72    options
73        .get_cache_dir()
74        .cloned()
75        .unwrap_or_else(|| install_dir.join(".libobs-bootstrap-cache"))
76}
77
78fn get_obs_library_path(install_dir: &std::path::Path) -> Result<PathBuf, ObsBootstrapError> {
79    match env::consts::OS {
80        "windows" => Ok(install_dir.join("obs.dll")),
81        "macos" => Ok(install_dir.join("libobs.framework/Versions/A/libobs")),
82        "linux" => Err(ObsBootstrapError::UnsupportedPlatform(
83            "Linux uses the system/source libobs integration rather than a portable runtime"
84                .to_string(),
85        )),
86        other => Err(ObsBootstrapError::UnsupportedPlatform(other.to_string())),
87    }
88}
89
90fn get_obs_library_path_with_options(
91    options: &ObsBootstrapperOptions,
92) -> Result<PathBuf, ObsBootstrapError> {
93    get_obs_library_path(&resolve_install_dir(options)?)
94}
95
96#[cfg(target_os = "windows")]
97fn ensure_obs_not_loaded() -> Result<(), ObsBootstrapError> {
98    if libloading::os::windows::Library::open_already_loaded("obs.dll").is_ok() {
99        return Err(ObsBootstrapError::RuntimeAlreadyLoaded);
100    }
101    Ok(())
102}
103
104#[cfg(target_os = "macos")]
105fn ensure_obs_not_loaded() -> Result<(), ObsBootstrapError> {
106    use std::ffi::CStr;
107
108    unsafe extern "C" {
109        fn _dyld_image_count() -> u32;
110        fn _dyld_get_image_name(image_index: u32) -> *const std::ffi::c_char;
111    }
112
113    // A directly linked macOS executable has libobs.framework mapped by dyld
114    // before main(). Refuse to replace it in-process; a bootstrap launcher that
115    // does not link libobs will not contain this image and may proceed safely.
116    unsafe {
117        for index in 0.._dyld_image_count() {
118            let image = _dyld_get_image_name(index);
119            if image.is_null() {
120                continue;
121            }
122            let image = CStr::from_ptr(image).to_string_lossy();
123            if image.contains("/libobs.framework/") {
124                return Err(ObsBootstrapError::RuntimeAlreadyLoaded);
125            }
126        }
127    }
128    Ok(())
129}
130
131#[cfg(not(any(target_os = "windows", target_os = "macos")))]
132fn ensure_obs_not_loaded() -> Result<(), ObsBootstrapError> {
133    Ok(())
134}
135
136fn resolve_target_version(
137    options: &ObsBootstrapperOptions,
138    cache_dir: &std::path::Path,
139) -> Result<Version, ObsBootstrapError> {
140    let configured = options.get_target_version();
141    let resolved_tag = match options.get_update_target_mode() {
142        UpdateTargetMode::Exact => return Ok(configured.clone()),
143        UpdateTargetMode::LatestCompatibleSameMajor => resolve_latest_compatible_release(
144            options.get_repository(),
145            configured.major as u32,
146            None,
147            cache_dir,
148        ),
149        UpdateTargetMode::LatestCompatibleSameMajorMinor => resolve_latest_compatible_release(
150            options.get_repository(),
151            configured.major as u32,
152            Some(configured.minor as u32),
153            cache_dir,
154        ),
155    }
156    .map_err(|e| ObsBootstrapError::GeneralError(e.to_string()))?
157    .ok_or_else(|| {
158        ObsBootstrapError::VersionError(format!(
159            "No compatible OBS release found for {} using {:?}",
160            configured,
161            options.get_update_target_mode()
162        ))
163    })?;
164
165    let resolved = Version::parse(resolved_tag.trim_start_matches('v')).map_err(|e| {
166        ObsBootstrapError::VersionError(format!("Invalid OBS release tag {resolved_tag:?}: {e}"))
167    })?;
168    if resolved.major != configured.major
169        || matches!(
170            options.get_update_target_mode(),
171            UpdateTargetMode::LatestCompatibleSameMajorMinor
172        ) && resolved.minor != configured.minor
173    {
174        return Err(ObsBootstrapError::VersionError(format!(
175            "Resolved OBS release {resolved} is outside the requested compatibility line"
176        )));
177    }
178    Ok(resolved)
179}
180
181fn installation_satisfies_policy(
182    installed: &str,
183    target: &Version,
184    mode: UpdateTargetMode,
185) -> Result<bool, ObsBootstrapError> {
186    let installed_version = version::parse_version(installed)?;
187    Ok(match mode {
188        UpdateTargetMode::Exact => installed_version == *target,
189        UpdateTargetMode::LatestCompatibleSameMajor => {
190            installed_version.major == target.major && !version::should_update(installed, target)?
191        }
192        UpdateTargetMode::LatestCompatibleSameMajorMinor => {
193            installed_version.major == target.major
194                && installed_version.minor == target.minor
195                && !version::should_update(installed, target)?
196        }
197    })
198}
199
200fn needs_provision(
201    installed: Option<&str>,
202    target: &Version,
203    mode: UpdateTargetMode,
204    update_enabled: bool,
205) -> Result<bool, ObsBootstrapError> {
206    let Some(installed) = installed else {
207        return Ok(true);
208    };
209    if installation_satisfies_policy(installed, target, mode)? {
210        return Ok(false);
211    }
212    if !update_enabled {
213        return Err(ObsBootstrapError::VersionError(format!(
214            "Installed OBS {installed} does not satisfy target {target} under {mode:?}, and updates are disabled"
215        )));
216    }
217    Ok(true)
218}
219
220fn plan_bootstrap(
221    options: &ObsBootstrapperOptions,
222) -> Result<Option<BootstrapPlan>, ObsBootstrapError> {
223    match env::consts::OS {
224        "windows" | "macos" => {}
225        "linux" => {
226            return Err(ObsBootstrapError::UnsupportedPlatform(
227                "Linux should install a compatible system libobs instead of runtime bootstrapping"
228                    .to_string(),
229            ));
230        }
231        other => return Err(ObsBootstrapError::UnsupportedPlatform(other.to_string())),
232    }
233
234    ensure_obs_not_loaded()?;
235    let install_dir = resolve_install_dir(options)?;
236    let cache_dir = resolve_cache_dir(options, &install_dir);
237    let target_version = resolve_target_version(options, &cache_dir)?;
238    let library_path = get_obs_library_path(&install_dir)?;
239
240    let installed = match version::get_installed_version(&library_path) {
241        Ok(version) => version,
242        Err(error) if options.get_update() => {
243            log::warn!(
244                "Existing OBS runtime at {} could not be inspected ({error}); replacing it",
245                library_path.display()
246            );
247            None
248        }
249        Err(error) => return Err(error),
250    };
251
252    if !needs_provision(
253        installed.as_deref(),
254        &target_version,
255        options.get_update_target_mode(),
256        options.get_update(),
257    )? {
258        return Ok(None);
259    }
260
261    Ok(Some(BootstrapPlan {
262        install_dir,
263        cache_dir,
264        repository: options.get_repository().to_string(),
265        target_version,
266    }))
267}
268
269fn execute_bootstrap(plan: BootstrapPlan) -> Result<Version, ObsBootstrapError> {
270    fs::create_dir_all(&plan.install_dir)
271        .map_err(|e| ObsBootstrapError::IoError("Creating OBS install directory", e))?;
272    fs::create_dir_all(&plan.cache_dir)
273        .map_err(|e| ObsBootstrapError::IoError("Creating OBS cache directory", e))?;
274
275    let config = ObsBuildConfig {
276        out_dir: plan.install_dir.clone(),
277        target: None,
278        cache_dir: Some(plan.cache_dir),
279        repo_id: Some(plan.repository),
280        override_zip: None,
281        rebuild: false,
282        browser: false,
283        tag: Some(plan.target_version.to_string()),
284        // The bootstrapper itself owns the target version decision, and does
285        // not depend on the native libobs crate or Cargo metadata at runtime.
286        skip_compatibility_check: true,
287        remove_pdbs: true,
288    };
289    build_obs_binaries_verified(config)
290        .map_err(|e| ObsBootstrapError::GeneralError(e.to_string()))?;
291
292    let library_path = get_obs_library_path(&plan.install_dir)?;
293    let installed = version::get_installed_version(&library_path)?
294        .ok_or_else(|| ObsBootstrapError::InvalidState)?;
295    let installed = version::parse_version(&installed)?;
296    if installed != plan.target_version {
297        return Err(ObsBootstrapError::VersionError(format!(
298            "Prepared OBS runtime is {installed}, expected exactly {}",
299            plan.target_version
300        )));
301    }
302
303    Ok(installed)
304}
305
306pub enum ObsBootstrapperResult {
307    /// The already-installed runtime satisfied the configured requirement.
308    None,
309    /// A verified OBS runtime was installed or updated and the process may
310    /// proceed to its first OBS call.
311    Provisioned,
312    /// Legacy variant from the updater-script design. The current implementation
313    /// never emits this because files are prepared before OBS is loaded.
314    #[deprecated(note = "runtime provisioning no longer requires an automatic restart")]
315    Restart,
316}
317
318impl ObsBootstrapper {
319    /// Checks the default executable-adjacent installation location without
320    /// performing network I/O.
321    pub fn is_valid_installation() -> Result<bool, ObsBootstrapError> {
322        Self::is_valid_installation_with_options(&ObsBootstrapperOptions::default())
323    }
324
325    /// Checks the installation location selected by `options` without network I/O.
326    pub fn is_valid_installation_with_options(
327        options: &ObsBootstrapperOptions,
328    ) -> Result<bool, ObsBootstrapError> {
329        Ok(version::get_installed_version(&get_obs_library_path_with_options(options)?)?.is_some())
330    }
331
332    /// Compares the default local runtime with the configured default target.
333    /// This is local-only and does not query GitHub.
334    pub fn is_update_available() -> Result<bool, ObsBootstrapError> {
335        Self::is_update_available_with_options(&ObsBootstrapperOptions::default())
336    }
337
338    /// Compares a local runtime with `options.target_version` without network I/O.
339    pub fn is_update_available_with_options(
340        options: &ObsBootstrapperOptions,
341    ) -> Result<bool, ObsBootstrapError> {
342        let Some(installed) =
343            version::get_installed_version(&get_obs_library_path_with_options(options)?)?
344        else {
345            return Ok(true);
346        };
347        Ok(!installation_satisfies_policy(
348            &installed,
349            options.get_target_version(),
350            options.get_update_target_mode(),
351        )?)
352    }
353
354    /// Explicitly provisions OBS using the configured release policy.
355    ///
356    /// This is the operation that may access the network. Downloaded official
357    /// release assets must advertise a SHA-256 checksum/digest and are verified
358    /// before extraction. No helper process is spawned and the application is
359    /// never restarted automatically.
360    pub async fn bootstrap(
361        options: &ObsBootstrapperOptions,
362    ) -> Result<ObsBootstrapperResult, ObsBootstrapError> {
363        Self::bootstrap_with_handler(options, Box::new(ObsBootstrapConsoleHandler::default())).await
364    }
365
366    /// Same as [`Self::bootstrap`], with custom progress notifications.
367    pub async fn bootstrap_with_handler<E: Send + Sync + 'static + std::error::Error>(
368        options: &ObsBootstrapperOptions,
369        mut handler: Box<dyn ObsBootstrapStatusHandler<Error = E>>,
370    ) -> Result<ObsBootstrapperResult, ObsBootstrapError> {
371        let options_for_plan = options.clone();
372        let plan = tokio::task::spawn_blocking(move || plan_bootstrap(&options_for_plan))
373            .await
374            .map_err(|e| {
375                ObsBootstrapError::GeneralError(format!("Bootstrap planning task failed: {e}"))
376            })??;
377
378        let Some(plan) = plan else {
379            return Ok(ObsBootstrapperResult::None);
380        };
381
382        handler
383            .handle_downloading(0.0, "Preparing verified OBS release".to_string())
384            .map_err(|e| ObsBootstrapError::Abort(Box::new(e)))?;
385        handler
386            .handle_extraction(0.0, "Staging OBS runtime".to_string())
387            .map_err(|e| ObsBootstrapError::Abort(Box::new(e)))?;
388
389        let installed = tokio::task::spawn_blocking(move || execute_bootstrap(plan))
390            .await
391            .map_err(|e| {
392                ObsBootstrapError::GeneralError(format!("Bootstrap worker failed: {e}"))
393            })??;
394
395        handler
396            .handle_downloading(1.0, format!("Verified OBS {installed}"))
397            .map_err(|e| ObsBootstrapError::Abort(Box::new(e)))?;
398        handler
399            .handle_extraction(1.0, format!("OBS {installed} is ready"))
400            .map_err(|e| ObsBootstrapError::Abort(Box::new(e)))?;
401
402        Ok(ObsBootstrapperResult::Provisioned)
403    }
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409
410    #[test]
411    fn provisioning_decision_respects_version_policy() {
412        let target = Version::new(32, 1, 0);
413        assert!(!needs_provision(Some("32.1.0"), &target, UpdateTargetMode::Exact, false).unwrap());
414        assert!(needs_provision(None, &target, UpdateTargetMode::Exact, false).unwrap());
415        assert!(needs_provision(Some("32.2.0"), &target, UpdateTargetMode::Exact, true).unwrap());
416        assert!(
417            !needs_provision(
418                Some("32.2.0"),
419                &target,
420                UpdateTargetMode::LatestCompatibleSameMajor,
421                false
422            )
423            .unwrap()
424        );
425        assert!(
426            needs_provision(
427                Some("32.2.0"),
428                &target,
429                UpdateTargetMode::LatestCompatibleSameMajorMinor,
430                true
431            )
432            .unwrap()
433        );
434        assert!(needs_provision(Some("32.0.0"), &target, UpdateTargetMode::Exact, false).is_err());
435        assert!(needs_provision(Some("31.9.9"), &target, UpdateTargetMode::Exact, false).is_err());
436    }
437
438    #[test]
439    fn default_version_stays_in_sync_with_vendored_obs_headers() {
440        let header = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
441            .join("../libobs/headers/obs/obs-config.h");
442        if !header.is_file() {
443            return;
444        }
445        let text = std::fs::read_to_string(header).unwrap();
446        let number = |name: &str| -> u64 {
447            text.lines()
448                .find_map(|line| {
449                    line.strip_prefix(&format!("#define {name} "))
450                        .and_then(|value| value.trim().parse().ok())
451                })
452                .unwrap()
453        };
454        let expected = Version::new(
455            number("LIBOBS_API_MAJOR_VER"),
456            number("LIBOBS_API_MINOR_VER"),
457            number("LIBOBS_API_PATCH_VER"),
458        );
459        assert_eq!(Version::parse(DEFAULT_OBS_VERSION).unwrap(), expected);
460    }
461}