1use std::{
8 fmt::Display,
9 fs::{
10 File,
11 OpenOptions,
12 Permissions,
13 copy,
14 create_dir,
15 create_dir_all,
16 remove_dir_all,
17 remove_file,
18 rename,
19 set_permissions,
20 },
21 io::Write,
22 os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt, chown},
23 path::{Path, PathBuf},
24};
25
26use alpm_types::EntryName;
27use fluent_i18n::t;
28use log::debug;
29use nix::unistd::{getegid, geteuid};
30use serde::{Deserialize, Serialize};
31use uuid::Uuid;
32
33use crate::db::{
34 DIR_MODE,
35 DatabaseConfig,
36 EntrySource,
37 Error,
38 entry::{EntryComponent, EntryComponentType},
39};
40
41#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
52#[serde(rename_all = "lowercase")]
53enum ActionItem {
54 Add(EntryName),
56
57 Remove(EntryName),
59}
60
61impl From<&Action> for ActionItem {
62 fn from(value: &Action) -> Self {
63 match value {
64 Action::Add(entry) => Self::Add(entry.entry_name()),
65 Action::Remove(entry) => Self::Remove(entry.clone()),
66 }
67 }
68}
69
70#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
77struct TransactionPlan {
78 uuid: Uuid,
79 actions: Vec<ActionItem>,
80 #[serde(skip)]
81 data_dir: PathBuf,
82}
83
84impl TransactionPlan {
85 pub fn uuid(&self) -> Uuid {
87 self.uuid
88 }
89
90 pub fn file_name(&self) -> String {
92 format!("{}.json", self.uuid)
93 }
94
95 pub fn write_to_current_dir(&self) -> Result<(), crate::Error> {
105 let path = self
106 .data_dir
107 .join(Transaction::CURRENT_DIR)
108 .join(self.file_name());
109 let data = serde_json::to_string(&self).map_err(|source| crate::Error::Json {
110 context: t!("error-json-transaction-plan", { "uuid" => self.uuid.to_string() }),
111 source,
112 })?;
113
114 let mut file = OpenOptions::new()
115 .create_new(true)
116 .write(true)
117 .mode(0o644)
118 .open(&path)
119 .map_err(|source| crate::Error::IoPath {
120 path: path.clone(),
121 context: t!("error-io-path-open-writable"),
122 source,
123 })?;
124
125 file.write_all(&data.into_bytes()).map_err(|source|
126 crate::Error::IoPath {
127 path: path.clone(),
128 context: t!("error-io-path-write-transaction-plan", { "uuid" => self.uuid.to_string() }),
129 source
130 })?;
131
132 Ok(())
133 }
134
135 pub fn move_to_past_transaction_dir(&self) -> Result<(), crate::Error> {
142 rename(
144 self.data_dir
145 .join(Transaction::CURRENT_DIR)
146 .join(self.file_name()),
147 self.data_dir
148 .join(Transaction::PAST_DIR)
149 .join(self.file_name()),
150 )
151 .map_err(|source| crate::Error::IoPath {
152 path: self
153 .data_dir
154 .join(Transaction::CURRENT_DIR)
155 .join(self.file_name()),
156 context: t!("error-io-path-move-transaction-plan", { "uuid" => self.uuid().to_string() }),
157 source,
158 })
159 }
160}
161
162impl From<&Transaction> for TransactionPlan {
163 fn from(value: &Transaction) -> Self {
164 Self {
165 uuid: value.uuid,
166 actions: value.actions.iter().map(Into::into).collect(),
167 data_dir: value.data_dir.clone(),
168 }
169 }
170}
171
172#[derive(Debug)]
174pub(crate) struct WriteLock {
175 path: PathBuf,
177
178 file: File,
180}
181
182impl WriteLock {
183 const DEFAULT_FILE_MODE: u32 = 0o100000;
185
186 pub fn new(path: impl AsRef<Path>) -> Result<Self, crate::Error> {
195 let path = path.as_ref();
196 debug!("Create an alpm-db lock file at {path:?}");
197
198 let file = OpenOptions::new()
199 .write(true)
200 .create_new(true)
201 .mode(Self::DEFAULT_FILE_MODE)
202 .open(path)
203 .map_err(|source| crate::Error::IoPath {
204 path: path.to_path_buf(),
205 context: t!("error-io-path-db-lock-create"),
206 source,
207 })?;
208 file.try_lock()
209 .map_err(|source| Error::DatabaseFailedExclusiveLockFile {
210 path: path.to_path_buf(),
211 source,
212 })?;
213
214 Ok(Self {
215 path: path.to_path_buf(),
216 file,
217 })
218 }
219
220 pub fn remove(self) -> Result<(), crate::Error> {
229 self.file.unlock().map_err(|source| crate::Error::IoPath {
230 path: self.path.clone(),
231 context: t!("error-io-path-db-lock-release"),
232 source,
233 })?;
234
235 remove_file(&self.path).map_err(|source| crate::Error::IoPath {
236 path: self.path.clone(),
237 context: t!("error-io-path-db-lock-delete"),
238 source,
239 })?;
240
241 Ok(())
242 }
243}
244
245impl AsRef<Path> for WriteLock {
246 fn as_ref(&self) -> &Path {
247 &self.path
248 }
249}
250
251fn create_entry_component(path: impl AsRef<Path>) -> Result<File, crate::Error> {
259 let path = path.as_ref();
260 debug!("Creating alpm-db entry component {path:?}");
261
262 OpenOptions::new()
263 .create_new(true)
264 .write(true)
265 .mode(EntryComponent::FILE_MODE)
266 .open(path)
267 .map_err(|source| crate::Error::IoPath {
268 path: path.to_path_buf(),
269 context: t!("error-io-path-db-create-component"),
270 source,
271 })
272}
273
274fn write_entry_to_dir(
293 entry: Box<dyn EntrySource>,
294 path: impl AsRef<Path>,
295) -> Result<(), crate::Error> {
296 let alpm_db_desc = entry.alpm_db_desc()?;
297 let alpm_db_files = entry.alpm_db_files()?;
298 let alpm_install_scriptlet = entry.alpm_install_scriptlet()?;
299 let alpm_mtree = entry.alpm_mtree()?;
300
301 let entry_dir = path.as_ref().join(entry.entry_name().to_string());
302 if entry_dir.exists() {
303 return Err(Error::EntryExists {
304 name: entry.entry_name().clone(),
305 }
306 .into());
307 }
308 create_dir(&entry_dir).map_err(|source| crate::Error::IoPath {
309 path: entry_dir.clone(),
310 context: t!("error-io-path-entry-dir-create"),
311 source,
312 })?;
313 set_permissions(&entry_dir, Permissions::from_mode(DIR_MODE)).map_err(|source| {
314 crate::Error::IoPath {
315 path: entry_dir.clone(),
316 context: t!("error-io-path-db-set-permissions-on-dir"),
317 source,
318 }
319 })?;
320
321 let components = {
322 let mut components = vec![
323 (
324 EntryComponentType::DbDesc,
325 create_entry_component(entry_dir.join(EntryComponentType::DbDesc.as_ref()))?,
326 alpm_db_desc.to_string().into_bytes(),
327 ),
328 (
329 EntryComponentType::DbFiles,
330 create_entry_component(entry_dir.join(EntryComponentType::DbFiles.as_ref()))?,
331 alpm_db_files.to_string().into_bytes(),
332 ),
333 (
334 EntryComponentType::Mtree,
335 create_entry_component(entry_dir.join(EntryComponentType::Mtree.as_ref()))?,
336 alpm_mtree.data_ensure_gzip()?,
337 ),
338 ];
339
340 if let Some(alpm_install_scriptlet) = alpm_install_scriptlet {
341 components.push((
342 EntryComponentType::InstallScriptlet,
343 create_entry_component(
344 entry_dir.join(EntryComponentType::InstallScriptlet.as_ref()),
345 )?,
346 alpm_install_scriptlet.into_bytes(),
347 ))
348 }
349
350 components
351 };
352
353 for (component_type, mut file, data) in components {
354 file.write_all(&data)
355 .map_err(|source| crate::Error::IoPath {
356 path: entry_dir.clone(),
357 context: t!(
358 "error-io-path-db-write-component",
359 { "file_type" => component_type.file_type_name().to_string()}
360 ),
361 source,
362 })?
363 }
364
365 Ok(())
366}
367
368#[derive(Debug)]
374pub enum Action {
375 Add(Box<dyn EntrySource>),
379
380 Remove(EntryName),
382}
383
384impl Display for Action {
385 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386 let (action, entry) = match self {
387 Self::Add(entry) => ("Add", &entry.entry_name()),
388 Self::Remove(entry) => ("Remove", entry),
389 };
390
391 write!(f, "{action} {entry}")
392 }
393}
394
395fn create_transaction_dirs(path: impl AsRef<Path>) -> Result<PathBuf, crate::Error> {
420 let path = path.as_ref();
421
422 let path = if path.exists() {
423 let path = path.canonicalize().map_err(|source| crate::Error::IoPath {
428 path: path.to_path_buf(),
429 context: t!("error-io-path-db-transaction-data-dir-canonicalize"),
430 source,
431 })?;
432
433 if !&path.is_dir() {
435 return Err(Error::TransactionDataDirIsNotADirectory { path }.into());
436 }
437
438 let euid = geteuid().as_raw();
439 let egid = getegid().as_raw();
440 let metadata = path
441 .symlink_metadata()
442 .map_err(|source| crate::Error::IoPath {
443 path: path.clone(),
444 context: t!("error-io-path-metadata"),
445 source,
446 })?;
447
448 if !(metadata.uid() == euid && metadata.gid() == egid) {
450 chown(&path, Some(euid), Some(egid)).map_err(|source| crate::Error::IoPath {
451 path: path.clone(),
452 context: t!("error-io-path-chown"),
453 source,
454 })?;
455 }
456
457 if metadata.permissions().mode() != DIR_MODE {
459 set_permissions(&path, PermissionsExt::from_mode(DIR_MODE)).map_err(|source| {
460 crate::Error::IoPath {
461 path: path.clone(),
462 context: t!("error-io-path-db-transaction-data-dir-set-permissions"),
463 source,
464 }
465 })?;
466 }
467
468 path
469 } else {
470 create_dir_all(path).map_err(|source| crate::Error::IoPath {
474 path: path.to_path_buf(),
475 context: t!("error-io-path-db-transaction-data-dir-create"),
476 source,
477 })?;
478 let path = path.canonicalize().map_err(|source| crate::Error::IoPath {
479 path: path.to_path_buf(),
480 context: t!("error-io-path-db-transaction-data-dir-canonicalize"),
481 source,
482 })?;
483
484 set_permissions(&path, PermissionsExt::from_mode(DIR_MODE)).map_err(|source| {
485 crate::Error::IoPath {
486 path: path.clone(),
487 context: t!("error-io-path-db-transaction-data-dir-set-permissions"),
488 source,
489 }
490 })?;
491
492 path
493 };
494
495 for subdir in [
498 Transaction::CURRENT_DIR,
499 Transaction::PAST_DIR,
500 Transaction::TEMP_DIR,
501 ] {
502 let subdir = path.join(subdir);
503
504 if subdir.is_dir() {
505 let euid = geteuid().as_raw();
506 let egid = getegid().as_raw();
507 let metadata = subdir
508 .symlink_metadata()
509 .map_err(|source| crate::Error::IoPath {
510 path: subdir.clone(),
511 context: t!("error-io-path-metadata"),
512 source,
513 })?;
514
515 if !(metadata.uid() == euid && metadata.gid() == egid) {
517 chown(&subdir, Some(euid), Some(egid)).map_err(|source| crate::Error::IoPath {
518 path: subdir.clone(),
519 context: t!("error-io-path-chown"),
520 source,
521 })?;
522 }
523
524 if metadata.permissions().mode() != DIR_MODE {
526 set_permissions(&subdir, PermissionsExt::from_mode(DIR_MODE)).map_err(
527 |source| crate::Error::IoPath {
528 path: subdir.clone(),
529 context: t!("error-io-path-db-transaction-data-dir-set-permissions"),
530 source,
531 },
532 )?;
533 }
534
535 continue;
536 }
537
538 create_dir(&subdir).map_err(|source| crate::Error::IoPath {
539 path: subdir.to_path_buf(),
540 context: t!("error-io-path-db-base-create"),
541 source,
542 })?;
543 set_permissions(&subdir, PermissionsExt::from_mode(DIR_MODE)).map_err(|source| {
544 crate::Error::IoPath {
545 path: subdir.clone(),
546 context: t!("error-io-path-db-transaction-data-dir-set-permissions"),
547 source,
548 }
549 })?;
550 }
551
552 Ok(path)
553}
554
555fn remove_temp_transaction_dir(path: impl AsRef<Path>) -> Result<(), crate::Error> {
562 let path = path.as_ref();
563
564 remove_dir_all(path).map_err(|source| crate::Error::IoPath {
565 path: path.to_path_buf(),
566 context: t!("error-io-path-db-transaction-temp-dir-remove"),
567 source,
568 })
569}
570
571fn paths_on_same_device(
577 path1: impl AsRef<Path>,
578 path2: impl AsRef<Path>,
579) -> Result<bool, crate::Error> {
580 let path1 = path1.as_ref();
581 let path2 = path2.as_ref();
582
583 Ok(path1
584 .symlink_metadata()
585 .map_err(|source| crate::Error::IoPath {
586 path: path1.to_path_buf(),
587 context: t!("error-io-path-metadata"),
588 source,
589 })?
590 .dev()
591 == path2
592 .symlink_metadata()
593 .map_err(|source| crate::Error::IoPath {
594 path: path2.to_path_buf(),
595 context: t!("error-io-path-metadata"),
596 source,
597 })?
598 .dev())
599}
600
601#[derive(Debug)]
609pub(crate) struct Transaction {
610 uuid: Uuid,
611 actions: Vec<Action>,
612 database_dir: PathBuf,
613 data_dir: PathBuf,
614 write_lock: WriteLock,
615}
616
617impl Transaction {
618 const CURRENT_DIR: &str = "current";
621
622 const PAST_DIR: &str = "past";
625
626 const TEMP_DIR: &str = "temp";
629
630 pub fn new(config: &DatabaseConfig) -> Result<Self, crate::Error> {
636 let database_dir = config.database_dir().to_path_buf();
637 let data_dir = config.transaction_data_dir();
638 let lock_file = config.lock_file();
639 let uuid = Uuid::now_v7();
640 debug!(
641 "Create transaction {uuid} for alpm-db {database_dir:?}, using data dir {data_dir:?} and lock file {lock_file:?}"
642 );
643
644 let write_lock = WriteLock::new(lock_file)?;
645 let data_dir = create_transaction_dirs(data_dir)?;
646
647 Ok(Self {
648 uuid,
649 actions: Vec::new(),
650 database_dir,
651 data_dir,
652 write_lock,
653 })
654 }
655
656 pub fn add_action(&mut self, action: Action) {
658 self.actions.push(action);
659 }
660
661 pub fn uuid(&self) -> &Uuid {
663 &self.uuid
664 }
665
666 pub fn database_dir(&self) -> &Path {
668 &self.database_dir
669 }
670
671 pub fn data_dir(&self) -> &Path {
673 &self.data_dir
674 }
675
676 pub fn lock_file(&self) -> &Path {
678 self.write_lock.as_ref()
679 }
680
681 fn create_temp_dir(&self) -> Result<PathBuf, crate::Error> {
687 let temp_dir = self
688 .data_dir
689 .join(Transaction::TEMP_DIR)
690 .join(self.uuid().to_string());
691
692 create_dir(&temp_dir).map_err(|source| crate::Error::IoPath {
694 path: temp_dir.clone(),
695 context: t!("error-io-path-db-transaction-temp-dir-create"),
696 source,
697 })?;
698
699 Ok(temp_dir)
700 }
701
702 pub fn commit(self) -> Result<(), crate::Error> {
739 debug!(
740 "Committing transaction {} for alpm-db {:?} using data dir {:?}",
741 self.uuid(),
742 self.database_dir(),
743 self.data_dir(),
744 );
745
746 if self.actions.is_empty() {
748 debug!(
749 "The transaction {} for alpm-db {:?} has no actions to perform.",
750 self.uuid, self.database_dir
751 );
752
753 self.write_lock.remove()?;
754
755 return Ok(());
756 }
757
758 let transaction_plan = TransactionPlan::from(&self);
761 transaction_plan.write_to_current_dir()?;
762
763 let temp_dir = self.create_temp_dir()?;
764 let path = self.database_dir().to_path_buf();
765 let uuid = *self.uuid();
766 let same_device = paths_on_same_device(&path, &temp_dir)?;
768
769 let (removals, errors) = {
772 let mut removals = Vec::new();
773 let mut errors = Vec::new();
774 for action in self.actions {
775 match action {
776 Action::Add(entry) => {
777 if let Err(error) = write_entry_to_dir(entry, &temp_dir) {
778 errors.push(error);
779 }
780 }
781 Action::Remove(entry_name) => {
782 if !path.join(entry_name.to_string()).exists() {
783 errors.push(
784 Error::EntryDoesNotExist {
785 name: entry_name.clone(),
786 }
787 .into(),
788 );
789 }
790 removals.push(entry_name)
791 }
792 }
793 }
794 (removals, errors)
795 };
796
797 if !errors.is_empty() {
800 remove_temp_transaction_dir(&temp_dir)?;
801
802 return Err(Error::TransactionTemporaryDataErrors {
803 path: path.to_path_buf(),
804 uuid,
805 errors: errors.iter().map(ToString::to_string).collect(),
806 }
807 .into());
808 }
809
810 for removal in removals {
812 remove_dir_all(path.join(removal.to_string())).map_err(|source| {
813 crate::Error::IoPath {
814 path: path.join(removal.to_string()),
815 context: t!("error-io-path-db-entry-remove"),
816 source,
817 }
818 })?
819 }
820
821 if same_device {
823 debug!(
824 "Temporary transaction data and database are on the same device: Moving entries..."
825 );
826 } else {
827 debug!(
828 "Temporary transaction data and database are on separate devices: Copying entries..."
829 );
830 }
831
832 for entry in temp_dir.read_dir().map_err(|source| crate::Error::IoPath {
833 path: temp_dir.clone(),
834 context: t!("error-io-path-db-transaction-temp-dir-read"),
835 source,
836 })? {
837 let entry = entry.map_err(|source| crate::Error::IoPath {
838 path: temp_dir.clone(),
839 context: t!("error-io-path-db-transaction-temp-dir-entry-read"),
840 source,
841 })?;
842 let entry_from = entry.path();
843 let entry_to = path.join(entry.file_name());
844 if same_device {
845 rename(&entry_from, &entry_to).map_err(|source| crate::Error::IoPath {
846 path: entry_from.clone(),
847 context: t!("error-io-path-db-transaction-temp-dir-entry-move"),
848 source,
849 })?;
850 } else {
851 copy(&entry_from, &entry_to).map_err(|source| crate::Error::IoPath {
852 path: entry_from.clone(),
853 context: t!("error-io-path-db-transaction-temp-dir-entry-copy"),
854 source,
855 })?;
856 }
857 }
858
859 remove_temp_transaction_dir(&temp_dir)?;
861
862 transaction_plan.move_to_past_transaction_dir()?;
864
865 self.write_lock.remove()?;
866
867 Ok(())
868 }
869}
870
871#[cfg(test)]
872mod tests {
873 use insta::{assert_snapshot, with_settings};
874 use log::LevelFilter;
875 use simplelog::{ColorChoice, Config, TermLogger, TerminalMode};
876 use tempfile::{NamedTempFile, TempDir};
877 use testresult::TestResult;
878
879 use super::*;
880
881 fn init_logger() {
883 if TermLogger::init(
884 LevelFilter::Trace,
885 Config::default(),
886 TerminalMode::Stderr,
887 ColorChoice::Auto,
888 )
889 .is_err()
890 {
891 debug!("Not initializing another logger, as one is initialized already.");
892 }
893 }
894
895 #[test]
899 fn write_lock_new_succeeds() -> TestResult {
900 init_logger();
901 let temp_dir = TempDir::new()?;
902 let lock_file_path = temp_dir.path().join(PathBuf::from("db.lck"));
903
904 let lock = WriteLock::new(&lock_file_path)?;
905 let metadata = lock_file_path.metadata()?;
906 assert_eq!(metadata.permissions().mode(), WriteLock::DEFAULT_FILE_MODE);
907
908 lock.remove()?;
909
910 assert!(!lock_file_path.exists());
911
912 Ok(())
913 }
914
915 #[test]
918 fn write_lock_new_fails_on_existing_file() -> TestResult {
919 init_logger();
920 let temp_file = NamedTempFile::new()?;
921
922 let Err(error) = WriteLock::new(temp_file.path()) else {
923 panic!("Expected to fail with crate::Error::IoPath");
924 };
925
926 debug!("{error}");
927 assert!(matches!(error, crate::Error::IoPath { .. }));
928
929 Ok(())
930 }
931
932 #[test]
934 fn transaction_plan_stable_serialization() -> TestResult {
935 init_logger();
936
937 let temp_dir = TempDir::new()?;
938 let path = temp_dir.path();
939
940 let plan = TransactionPlan {
941 uuid: "01a17815-fe9d-77f6-9bb1-387d74e07195".parse()?,
942 actions: vec![
943 ActionItem::Add("example-1.0.0-1".parse()?),
944 ActionItem::Remove("other-example-2.0.0-1".parse()?),
945 ],
946 data_dir: path.to_path_buf(),
947 };
948
949 let json_plan = serde_json::to_string(&plan)?;
950
951 debug!("{json_plan}");
952 with_settings!({ description => "Simple, serialized transaction plan example", snapshot_path => "snapshots" }, {
953 assert_snapshot!("transaction_plan_stable_serialize_example", json_plan);
954 });
955
956 Ok(())
957 }
958}