rebecca-core 0.2.0

Core planning, safety, scanning, and history models for Rebecca.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use std::collections::BTreeSet;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::error::{RebeccaError, Result};

pub trait ApplicationDiscovery {
    fn steam_installation(&self) -> Result<Option<SteamInstallation>>;

    fn installed_applications(&self) -> Result<Vec<InstalledApplication>> {
        Ok(Vec::new())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InstalledApplication {
    pub stable_id: String,
    pub display_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publisher: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub install_locations: Vec<PathBuf>,
}

impl InstalledApplication {
    pub fn new(
        stable_id: impl Into<String>,
        display_name: impl Into<String>,
        install_locations: impl IntoIterator<Item = PathBuf>,
    ) -> Self {
        Self {
            stable_id: stable_id.into(),
            display_name: display_name.into(),
            publisher: None,
            install_locations: dedupe_paths(install_locations),
        }
    }

    pub fn with_publisher(mut self, publisher: impl Into<String>) -> Self {
        let publisher = publisher.into();
        if !publisher.trim().is_empty() {
            self.publisher = Some(publisher);
        }
        self
    }

    pub fn with_install_location(mut self, install_location: impl Into<PathBuf>) -> Self {
        push_deduped_path(&mut self.install_locations, install_location.into());
        self
    }

    pub fn stable_id(&self) -> &str {
        &self.stable_id
    }

    pub fn display_name(&self) -> &str {
        &self.display_name
    }

    pub fn install_locations(&self) -> &[PathBuf] {
        &self.install_locations
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct NoopApplicationDiscovery;

impl NoopApplicationDiscovery {
    pub fn new() -> Self {
        Self
    }
}

impl ApplicationDiscovery for NoopApplicationDiscovery {
    fn steam_installation(&self) -> Result<Option<SteamInstallation>> {
        Ok(None)
    }

    fn installed_applications(&self) -> Result<Vec<InstalledApplication>> {
        Ok(Vec::new())
    }
}

#[derive(Debug, Clone, Default)]
pub struct StaticApplicationDiscovery {
    steam_installation: Option<SteamInstallation>,
    installed_applications: Vec<InstalledApplication>,
}

impl StaticApplicationDiscovery {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_steam_installation(mut self, installation: SteamInstallation) -> Self {
        self.steam_installation = Some(installation);
        self
    }

    pub fn with_installed_applications(
        mut self,
        applications: impl IntoIterator<Item = InstalledApplication>,
    ) -> Self {
        self.installed_applications = dedupe_applications(applications);
        self
    }
}

impl ApplicationDiscovery for StaticApplicationDiscovery {
    fn steam_installation(&self) -> Result<Option<SteamInstallation>> {
        Ok(self.steam_installation.clone())
    }

    fn installed_applications(&self) -> Result<Vec<InstalledApplication>> {
        Ok(self.installed_applications.clone())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SteamInstallation {
    install_path: PathBuf,
    library_paths: Vec<PathBuf>,
}

impl SteamInstallation {
    pub fn new(
        install_path: impl Into<PathBuf>,
        library_paths: impl IntoIterator<Item = PathBuf>,
    ) -> Self {
        let install_path = install_path.into();
        let paths = library_paths
            .into_iter()
            .filter(|path| !same_path_ignore_case(path, &install_path))
            .collect::<Vec<_>>();
        Self {
            install_path,
            library_paths: dedupe_paths(paths),
        }
    }

    pub fn from_install_path(install_path: impl Into<PathBuf>) -> Result<Self> {
        let install_path = install_path.into();
        let library_paths = read_steam_libraryfolders(&install_path)?;

        Ok(Self::new(install_path, library_paths))
    }

    pub fn from_install_path_best_effort(install_path: impl Into<PathBuf>) -> Self {
        let install_path = install_path.into();

        Self::from_install_path(&install_path)
            .unwrap_or_else(|_| Self::new(install_path, Vec::new()))
    }

    pub fn install_path(&self) -> &Path {
        &self.install_path
    }

    pub fn library_paths(&self) -> &[PathBuf] {
        &self.library_paths
    }
}

pub fn parse_steam_libraryfolders(raw: &str) -> Result<Vec<PathBuf>> {
    let tokens = tokenize_vdf(raw)?;
    let mut paths = Vec::new();
    let mut index = 0usize;

    while index + 1 < tokens.len() {
        let is_libraryfolders = match &tokens[index] {
            VdfToken::String(value) => value.eq_ignore_ascii_case("libraryfolders"),
            _ => false,
        };

        if is_libraryfolders && matches!(tokens.get(index + 1), Some(VdfToken::OpenBrace)) {
            index += 2;
            parse_steam_libraryfolders_object(&tokens, &mut index, &mut paths)?;
            return Ok(dedupe_paths(paths));
        }
        index += 1;
    }

    Ok(dedupe_paths(paths))
}

const STEAM_LIBRARYFOLDERS_CANDIDATES: [&str; 2] =
    ["config/libraryfolders.vdf", "steamapps/libraryfolders.vdf"];

fn read_steam_libraryfolders(install_path: &Path) -> Result<Vec<PathBuf>> {
    let candidates = STEAM_LIBRARYFOLDERS_CANDIDATES
        .iter()
        .map(|relative_path| install_path.join(relative_path));

    let mut paths = Vec::new();
    let mut first_error = None;

    for library_file in candidates {
        match read_steam_libraryfolders_file(&library_file) {
            Ok(Some(mut discovered)) => paths.append(&mut discovered),
            Ok(None) => {}
            Err(err) if first_error.is_none() => first_error = Some(err),
            Err(_) => {}
        }
    }

    if paths.is_empty() {
        if let Some(err) = first_error {
            return Err(err);
        }
    }

    Ok(dedupe_paths(paths))
}

fn read_steam_libraryfolders_file(library_file: &Path) -> Result<Option<Vec<PathBuf>>> {
    let raw = match fs::read_to_string(library_file) {
        Ok(raw) => raw,
        Err(err) if err.kind() == ErrorKind::NotFound => return Ok(None),
        Err(err) => {
            return Err(RebeccaError::ApplicationDiscoveryFailed(format!(
                "could not read Steam library folders at {}: {err}",
                library_file.display()
            )));
        }
    };

    parse_steam_libraryfolders(&raw).map(Some)
}

fn parse_steam_libraryfolders_object(
    tokens: &[VdfToken],
    index: &mut usize,
    paths: &mut Vec<PathBuf>,
) -> Result<()> {
    while *index < tokens.len() {
        match tokens.get(*index) {
            Some(VdfToken::CloseBrace) => {
                *index += 1;
                return Ok(());
            }
            Some(VdfToken::OpenBrace) => {
                *index += 1;
            }
            Some(VdfToken::String(key)) => {
                let key = key.clone();
                *index += 1;

                match tokens.get(*index) {
                    Some(VdfToken::OpenBrace) => {
                        *index += 1;
                        parse_steam_libraryfolders_object(tokens, index, paths)?;
                    }
                    Some(VdfToken::String(value)) => {
                        if let Some(path) = steam_library_path_value(&key, value) {
                            paths.push(path);
                        }
                        *index += 1;
                    }
                    Some(VdfToken::CloseBrace) => return Ok(()),
                    None => return Ok(()),
                }
            }
            None => return Ok(()),
        }
    }

    Ok(())
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum VdfToken {
    String(String),
    OpenBrace,
    CloseBrace,
}

fn tokenize_vdf(raw: &str) -> Result<Vec<VdfToken>> {
    let mut tokens = Vec::new();
    let mut chars = raw.chars().peekable();

    while let Some(ch) = chars.next() {
        match ch {
            '"' => tokens.push(VdfToken::String(read_vdf_string(&mut chars)?)),
            '{' => tokens.push(VdfToken::OpenBrace),
            '}' => tokens.push(VdfToken::CloseBrace),
            '/' if chars.peek() == Some(&'/') => {
                for comment_ch in chars.by_ref() {
                    if comment_ch == '\n' {
                        break;
                    }
                }
            }
            ch if ch.is_whitespace() => {}
            _ => {}
        }
    }

    Ok(tokens)
}

fn read_vdf_string<I>(chars: &mut std::iter::Peekable<I>) -> Result<String>
where
    I: Iterator<Item = char>,
{
    let mut value = String::new();

    while let Some(ch) = chars.next() {
        match ch {
            '"' => return Ok(value),
            '\\' => {
                if let Some(escaped) = chars.next() {
                    match escaped {
                        '\\' | '"' => value.push(escaped),
                        'n' => value.push('\n'),
                        't' => value.push('\t'),
                        other => {
                            value.push('\\');
                            value.push(other);
                        }
                    }
                } else {
                    value.push('\\');
                }
            }
            other => value.push(other),
        }
    }

    Err(RebeccaError::ApplicationDiscoveryFailed(
        "unterminated string in Steam libraryfolders.vdf".to_string(),
    ))
}

fn is_legacy_library_key(value: &str) -> bool {
    !value.is_empty() && value.chars().all(|ch| ch.is_ascii_digit())
}

fn looks_like_path_value(value: &str) -> bool {
    value.contains(':') || value.contains('\\') || value.contains('/')
}

fn steam_library_path_value(key: &str, value: &str) -> Option<PathBuf> {
    if key.eq_ignore_ascii_case("path")
        || (is_legacy_library_key(key) && looks_like_path_value(value))
    {
        let trimmed = value.trim();
        if trimmed.is_empty() || !looks_like_windows_absolute_path(trimmed) {
            return None;
        }

        Some(PathBuf::from(trimmed))
    } else {
        None
    }
}

fn dedupe_paths(paths: impl IntoIterator<Item = PathBuf>) -> Vec<PathBuf> {
    let mut seen = BTreeSet::new();
    let mut deduped = Vec::new();

    for path in paths {
        if seen.insert(path_key(&path)) {
            deduped.push(path);
        }
    }

    deduped
}

fn dedupe_applications(
    applications: impl IntoIterator<Item = InstalledApplication>,
) -> Vec<InstalledApplication> {
    let mut seen = BTreeSet::new();
    let mut deduped = Vec::new();

    for application in applications {
        if seen.insert(application_key(&application)) {
            deduped.push(application);
        }
    }

    deduped
}

fn application_key(application: &InstalledApplication) -> String {
    let mut key = application.stable_id.trim().to_ascii_lowercase();
    key.push('|');
    key.push_str(&application.display_name.trim().to_ascii_lowercase());
    key.push('|');
    key.push_str(
        &application
            .install_locations
            .iter()
            .map(|path| path_key(path))
            .collect::<Vec<_>>()
            .join(";"),
    );
    key
}

fn push_deduped_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
    if paths
        .iter()
        .all(|existing| !same_path_ignore_case(existing, &path))
    {
        paths.push(path);
    }
}

fn path_key(path: &Path) -> String {
    let mut normalized = path
        .as_os_str()
        .to_string_lossy()
        .replace('\\', "/")
        .to_ascii_lowercase();

    while normalized.ends_with('/') && normalized.len() > 3 {
        normalized.pop();
    }

    normalized
}

fn same_path_ignore_case(left: &Path, right: &Path) -> bool {
    path_key(left) == path_key(right)
}

fn looks_like_windows_absolute_path(value: &str) -> bool {
    let normalized = value.replace('/', "\\");

    if normalized.starts_with("\\\\") {
        return true;
    }

    let bytes = normalized.as_bytes();
    bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'\\'
}