1use std::{
6 fmt::Display,
7 fs::{File, OpenOptions},
8 io::{Seek, read_to_string},
9 os::unix::fs::PermissionsExt,
10 path::{Path, PathBuf},
11};
12
13use alpm_common::MetadataFile;
14use alpm_mtree::Mtree;
15use alpm_types::{EntryName, FullVersion, Name};
16use fluent_i18n::t;
17use log::warn;
18use strum::AsRefStr;
19
20use crate::{
21 db::{Error, permissions_world_writable},
22 desc::DbDescFile,
23 files::DbFiles,
24};
25
26#[derive(AsRefStr, Clone, Copy, Debug, strum::Display, Eq, Ord, PartialEq, PartialOrd)]
28pub enum EntryComponentType {
29 #[strum(serialize = "desc")]
33 DbDesc,
34
35 #[strum(serialize = "files")]
39 DbFiles,
40
41 #[strum(serialize = "install")]
45 InstallScriptlet,
46
47 #[strum(serialize = "mtree")]
51 Mtree,
52}
53
54impl EntryComponentType {
55 pub fn file_type_name(&self) -> &str {
57 match self {
58 Self::DbDesc => "alpm-desc-desc",
59 Self::DbFiles => "alpm-db-files",
60 Self::Mtree => "ALPM-MTREE",
61 Self::InstallScriptlet => "alpm-install-scriptlet",
62 }
63 }
64}
65
66#[derive(Debug)]
71pub(crate) struct EntryComponent {
72 file: File,
74
75 path: PathBuf,
77}
78
79impl EntryComponent {
80 pub const FILE_MODE: u32 = 0o100644;
84
85 pub fn new(
96 entry_dir: impl AsRef<Path>,
97 name: EntryComponentType,
98 ) -> Result<Self, crate::Error> {
99 let path = entry_dir.as_ref().join(name.as_ref());
100
101 let metadata = path
102 .symlink_metadata()
103 .map_err(|source| crate::Error::IoPath {
104 path: path.clone(),
105 context: t!("error-io-path-metadata"),
106 source,
107 })?;
108
109 if !metadata.is_file() {
110 return Err(Error::EntryComponentIsNotAFile { path: path.clone() }.into());
111 }
112
113 if permissions_world_writable(metadata.permissions().mode()) {
115 warn!(
116 "{}",
117 t!("warn-database-entry-component-world-writable", { "path" => path.display().to_string() })
118 );
119 }
120
121 let file = OpenOptions::new()
122 .read(true)
123 .open(&path)
124 .map_err(|source| crate::Error::IoPath {
125 path: path.clone(),
126 context: t!("error-io-path-open-read-only"),
127 source,
128 })?;
129
130 Ok(Self {
131 file,
132 path: path.to_path_buf(),
133 })
134 }
135}
136
137#[derive(Debug)]
149pub struct Entry {
150 name: EntryName,
152
153 alpm_db_desc: EntryComponent,
155
156 alpm_db_files: EntryComponent,
158
159 alpm_install_scriptlet: Option<EntryComponent>,
161
162 alpm_mtree: EntryComponent,
164}
165
166impl Entry {
167 pub fn new(path: impl AsRef<Path>) -> Result<Self, crate::Error> {
190 let path = {
191 let path = path.as_ref();
192 let path = path.canonicalize().map_err(|source| crate::Error::IoPath {
193 path: path.to_path_buf(),
194 context: t!("error-io-path-canonicalize-entry-dir"),
195 source,
196 })?;
197 let metadata = path.metadata().map_err(|source| crate::Error::IoPath {
198 path: path.clone(),
199 context: t!("error-io-path-metadata"),
200 source,
201 })?;
202 if !metadata.is_dir() {
203 return Err(Error::EntryIsNotADirectory { path }.into());
204 }
205
206 if permissions_world_writable(metadata.permissions().mode()) {
208 warn!(
209 "{}",
210 t!("warn-database-entry-world-writable", { "path" => path.display().to_string() })
211 );
212 }
213
214 path
215 };
216
217 let name = EntryName::try_from(path.as_path())?;
218 let alpm_db_desc = EntryComponent::new(&path, EntryComponentType::DbDesc)?;
219 let alpm_db_files = EntryComponent::new(&path, EntryComponentType::DbFiles)?;
220 let alpm_mtree = EntryComponent::new(&path, EntryComponentType::Mtree)?;
221
222 let alpm_install_scriptlet = if path
225 .join(EntryComponentType::InstallScriptlet.as_ref())
226 .try_exists()
227 .map_err(|source| crate::Error::IoPath {
228 path: path.to_path_buf(),
229 context: t!("error-io-path-check-existence"),
230 source,
231 })? {
232 Some(EntryComponent::new(
233 &path,
234 EntryComponentType::InstallScriptlet,
235 )?)
236 } else {
237 None
238 };
239
240 Ok(Self {
241 name,
242 alpm_db_desc,
243 alpm_db_files,
244 alpm_install_scriptlet,
245 alpm_mtree,
246 })
247 }
248
249 pub fn name(&self) -> &Name {
251 self.name.name()
252 }
253
254 pub fn version(&self) -> &FullVersion {
256 self.name.version()
257 }
258
259 pub fn db_desc(&mut self) -> Result<DbDescFile, crate::Error> {
274 let mut file = &self.alpm_db_desc.file;
275 let output = DbDescFile::from_reader(file)?;
276 file.rewind().map_err(|source| crate::Error::IoPath {
277 path: self.alpm_db_desc.path.clone(),
278 context: t!("error-io-path-rewind"),
279 source,
280 })?;
281
282 if output.name() != self.name.name() || output.version() != self.name.version() {
283 return Err(Error::EntryComponentNameMismatch {
284 entry_name: self.name.to_string(),
285 component_entry_name: EntryName::new(
286 output.name().clone(),
287 output.version().clone(),
288 )
289 .to_string(),
290 }
291 .into());
292 }
293
294 Ok(output)
295 }
296
297 pub fn db_files(&mut self) -> Result<DbFiles, crate::Error> {
310 let mut file = &self.alpm_db_files.file;
311 let output = DbFiles::from_reader(file)?;
312 file.rewind().map_err(|source| crate::Error::IoPath {
313 path: self.alpm_db_files.path.clone(),
314 context: t!("error-io-path-rewind"),
315 source,
316 })?;
317
318 Ok(output)
319 }
320
321 pub fn install_scriptlet(&mut self) -> Result<Option<String>, crate::Error> {
338 let Some(install_scriptlet) = self.alpm_install_scriptlet.as_ref() else {
339 return Ok(None);
340 };
341
342 let mut file = &install_scriptlet.file;
343 let output = read_to_string(file).map_err(|source| crate::Error::IoPath {
344 path: install_scriptlet.path.to_path_buf(),
345 context: t!("error-io-path-read-file-to-string"),
346 source,
347 })?;
348 file.rewind().map_err(|source| crate::Error::IoPath {
349 path: install_scriptlet.path.clone(),
350 context: t!("error-io-path-rewind"),
351 source,
352 })?;
353
354 Ok(Some(output))
355 }
356
357 pub fn mtree(&mut self) -> Result<Mtree, crate::Error> {
370 let mut file = &self.alpm_mtree.file;
371 let output = Mtree::from_reader(file)?;
372 file.rewind().map_err(|source| crate::Error::IoPath {
373 path: self.alpm_mtree.path.clone(),
374 context: t!("error-io-path-rewind"),
375 source,
376 })?;
377
378 Ok(output)
379 }
380}
381
382impl Display for Entry {
383 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384 write!(f, "{}", self.name)
385 }
386}
387
388impl PartialEq for Entry {
389 fn eq(&self, other: &Self) -> bool {
390 self.name.eq(&other.name)
391 }
392}
393
394impl PartialOrd for Entry {
395 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
396 self.name.partial_cmp(&other.name)
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use std::{
403 fs::{create_dir, create_dir_all},
404 io::Write,
405 };
406
407 use alpm_types::{
408 Architecture,
409 ExtraData,
410 ExtraDataEntry,
411 PackageInstallReason,
412 PackageValidation,
413 RelativeFilePath,
414 SystemArchitecture,
415 };
416 use log::{LevelFilter, debug};
417 use rstest::{fixture, rstest};
418 use simplelog::{ColorChoice, Config, TermLogger, TerminalMode};
419 use tempfile::TempDir;
420 use testresult::TestResult;
421
422 use super::*;
423 use crate::{
424 desc::DbDescFileV2,
425 files::{BackupEntry, DbFilesV1},
426 };
427
428 fn init_logger() {
430 if TermLogger::init(
431 LevelFilter::Trace,
432 Config::default(),
433 TerminalMode::Stderr,
434 ColorChoice::Auto,
435 )
436 .is_err()
437 {
438 debug!("Not initializing another logger, as one is initialized already.");
439 }
440 }
441
442 #[rstest]
444 #[case::with_install_file(true)]
445 #[case::without_install_file(false)]
446 fn entry_new_succeeds(#[case] with_install: bool) -> TestResult {
447 init_logger();
448
449 let temp_dir = TempDir::new()?;
450 let entry_dir = temp_dir.path().join("example-1.0.0-1");
451 create_dir_all(&entry_dir)?;
452 let mut file_names: Vec<&str> = vec!["desc", "files", "mtree"];
453 if with_install {
454 file_names.push("install");
455 }
456
457 for file_name in file_names {
458 File::create(entry_dir.join(file_name))?;
459 }
460
461 Entry::new(&entry_dir)?;
462
463 Ok(())
464 }
465
466 #[rstest]
468 fn entry_new_fails_on_path_not_a_dir() -> TestResult {
469 init_logger();
470
471 let temp_dir = TempDir::new()?;
472 let entry = temp_dir.path().join("example-1.0.0-1");
473 File::create(&entry)?;
474
475 let Err(error) = Entry::new(&entry) else {
476 panic!("Expected to fail on Error::EntryIsNotADirectory");
477 };
478
479 debug!("{error}");
480 assert!(matches!(
481 error,
482 crate::Error::Database(Error::EntryIsNotADirectory { .. })
483 ));
484
485 Ok(())
486 }
487
488 #[rstest]
490 #[case::no_desc(vec!["files", "mtree"])]
491 #[case::no_files(vec!["desc", "mtree"])]
492 #[case::no_mtree(vec!["desc", "files"])]
493 #[case::no_files_no_mtree(vec!["desc"])]
494 #[case::no_desc_no_mtree(vec!["files"])]
495 #[case::no_desc_no_files(vec!["mtree"])]
496 #[case::none(Vec::new())]
497 fn entry_new_fails_on_missing_component(#[case] components: Vec<&str>) -> TestResult {
498 init_logger();
499
500 let temp_dir = TempDir::new()?;
501 let entry_dir = temp_dir.path().join("example-1.0.0-1");
502 create_dir_all(&entry_dir)?;
503
504 for component in components {
505 File::create(entry_dir.join(component))?;
506 }
507
508 let Err(error) = Entry::new(&entry_dir) else {
509 panic!("Expected to fail with Error::EntryComponentIsNotAFile");
510 };
511
512 debug!("{error}");
513 assert!(matches!(error, crate::Error::IoPath { .. }));
514
515 Ok(())
516 }
517
518 #[rstest]
520 #[case::no_desc(vec!["files", "mtree"], vec!["desc"])]
521 #[case::no_files(vec!["desc", "mtree"], vec!["files"])]
522 #[case::no_mtree(vec!["desc", "files"], vec!["mtree"])]
523 #[case::no_files_no_mtree(vec!["desc"], vec!["files", "mtree"])]
524 #[case::no_desc_no_mtree(vec!["files"], vec!["desc", "mtree"])]
525 #[case::no_desc_no_files(vec!["mtree"], vec!["desc", "files"])]
526 #[case::none(Vec::new(), vec!["desc", "files", "mtree"])]
527 fn entry_new_fails_on_component_is_not_a_file(
528 #[case] file_components: Vec<&str>,
529 #[case] dir_components: Vec<&str>,
530 ) -> TestResult {
531 init_logger();
532
533 let temp_dir = TempDir::new()?;
534 let entry_dir = temp_dir.path().join("example-1.0.0-1");
535 create_dir_all(&entry_dir)?;
536
537 for component in file_components {
538 File::create(entry_dir.join(component))?;
539 }
540 for component in dir_components {
541 create_dir(entry_dir.join(component))?;
542 }
543
544 let Err(error) = Entry::new(&entry_dir) else {
545 panic!("Expected to fail with Error::EntryComponentIsNotAFile");
546 };
547
548 debug!("{error}");
549 assert!(matches!(
550 error,
551 crate::Error::Database(Error::EntryComponentIsNotAFile { .. })
552 ));
553
554 Ok(())
555 }
556
557 #[fixture]
558 fn db_desc() -> Result<DbDescFile, crate::Error> {
559 Ok(DbDescFile::V2(DbDescFileV2 {
560 name: "example".parse()?,
561 version: "1.0.0-1".parse()?,
562 base: "example".parse()?,
563 description: "An example package".into(),
564 url: Some("https://example.org".parse()?),
565 arch: Architecture::Some(SystemArchitecture::X86_64),
566 builddate: 1,
567 installdate: 2,
568 packager: "Foobar McFooface <foobar@mcfooface.org>".parse()?,
569 size: 10,
570 groups: Vec::new(),
571 reason: PackageInstallReason::Explicit,
572 license: vec!["0BSD".parse()?],
573 validation: vec![PackageValidation::None],
574 replaces: Vec::new(),
575 depends: Vec::new(),
576 optdepends: Vec::new(),
577 conflicts: Vec::new(),
578 provides: Vec::new(),
579 xdata: ExtraData::try_from(ExtraDataEntry::new(
580 "pkgtype".to_string(),
581 "pkg".to_string(),
582 ))?,
583 }))
584 }
585
586 #[fixture]
587 fn db_files() -> Result<DbFiles, crate::Error> {
588 Ok(DbFiles::V1(DbFilesV1::try_from((
589 vec![
590 PathBuf::from("etc/"),
591 PathBuf::from("etc/example"),
592 PathBuf::from("etc/example/conf"),
593 PathBuf::from("usr"),
594 PathBuf::from("usr/bin"),
595 PathBuf::from("usr/bin/foo"),
596 ],
597 vec![BackupEntry {
598 path: RelativeFilePath::new(PathBuf::from("etc/example/conf"))?,
599 md5: "d3b07384d113edec49eaa6238ad5ff00".parse()?,
600 }],
601 ))?))
602 }
603
604 const INSTALL_SCRIPTLET: &str = r#"!/usr/bin/env bash
605
606post_install() {
607 printf 'YOLO\n'
608}
609"#;
610
611 const MTREE_DATA: &str = r#"#mtree
612/set mode=644 uid=0 gid=0 type=file
613./etc mode=755 type=dir time=1700000000.0
614./etc/example mode=755 type=dir time=1700000000.0
615./etc/example/conf time=1700000000.0 size=1337 sha256digest=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
616./some_dir type=dir time=1700000000.0
617./usr mode=755 type=dir time=1700000000.0
618./usr/bin mode=755 type=dir time=1700000000.0
619./usr/bin/foo time=1700000000.0 size=1337 sha256digest=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
620"#;
621
622 #[rstest]
627 fn entry_return_component_data(
628 db_desc: Result<DbDescFile, crate::Error>,
629 db_files: Result<DbFiles, crate::Error>,
630 ) -> TestResult {
631 init_logger();
632
633 let temp_dir = TempDir::new()?;
634 let entry_dir = temp_dir.path().join("example-1.0.0-1");
635 create_dir_all(&entry_dir)?;
636
637 let db_desc = db_desc?.to_string();
638 let db_files = db_files?.to_string();
639 let install_script = INSTALL_SCRIPTLET.to_string();
640 let mtree_data = MTREE_DATA.to_string();
641
642 for (file_name, data) in [
643 ("desc", db_desc),
644 ("files", db_files),
645 ("install", install_script),
646 ("mtree", mtree_data),
647 ] {
648 let mut file = File::create(entry_dir.join(file_name))?;
649 file.write_all(&data.into_bytes())?;
650 }
651
652 let mut entry = Entry::new(&entry_dir)?;
653
654 let db_desc = entry.db_desc()?;
655 debug!("alpm-db-desc:\n{db_desc}");
656
657 let db_files = entry.db_files()?;
658 debug!("alpm-db-files:\n{db_files}");
659
660 let mtree = entry.mtree()?;
661 debug!("ALPM-MTREE:\n{mtree}");
662
663 if let Some(install_scriptlet) = entry.install_scriptlet()? {
664 debug!("alpm-install-scriptlet:\n{install_scriptlet}");
665 }
666
667 Ok(())
668 }
669
670 #[rstest]
672 fn entry_db_desc_fails_on_mismatching_entry_name(
673 db_desc: Result<DbDescFile, crate::Error>,
674 db_files: Result<DbFiles, crate::Error>,
675 ) -> TestResult {
676 init_logger();
677
678 let temp_dir = TempDir::new()?;
679 let entry_dir = temp_dir.path().join("example-foo-1.0.0-1");
680 create_dir_all(&entry_dir)?;
681
682 let db_desc = db_desc?.to_string();
683 let db_files = db_files?.to_string();
684 let install_script = INSTALL_SCRIPTLET.to_string();
685 let mtree_data = MTREE_DATA.to_string();
686
687 for (file_name, data) in [
688 ("desc", db_desc),
689 ("files", db_files),
690 ("install", install_script),
691 ("mtree", mtree_data),
692 ] {
693 let mut file = File::create(entry_dir.join(file_name))?;
694 file.write_all(&data.into_bytes())?;
695 }
696
697 let mut entry = Entry::new(&entry_dir)?;
698
699 let Err(error) = entry.db_desc() else {
700 panic!("Expected to return Error::EntryComponentNameMismatch");
701 };
702
703 debug!("{error}");
704 assert!(matches!(
705 error,
706 crate::Error::Database(Error::EntryComponentNameMismatch { .. })
707 ));
708
709 Ok(())
710 }
711}