Abstract out disk-writing utilities from FilesystemPersister
[rust-lightning] / lightning-persister / src / util.rs
1 use std::fs;
2 use std::path::{Path, PathBuf};
3
4 #[cfg(not(target_os = "windows"))]
5 use std::os::unix::io::AsRawFd;
6
7 pub(crate) trait DiskWriteable {
8         fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error>;
9 }
10
11 pub fn get_full_filepath(filepath: String, filename: String) -> String {
12         let mut path = PathBuf::from(filepath);
13         path.push(filename);
14         path.to_str().unwrap().to_string()
15 }
16
17 #[allow(bare_trait_objects)]
18 pub(crate) fn write_to_file<D: DiskWriteable>(path: String, filename: String, data: &D) -> std::io::Result<()> {
19         fs::create_dir_all(path.clone())?;
20         // Do a crazy dance with lots of fsync()s to be overly cautious here...
21         // We never want to end up in a state where we've lost the old data, or end up using the
22         // old data on power loss after we've returned.
23         // The way to atomically write a file on Unix platforms is:
24         // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
25         let filename_with_path = get_full_filepath(path, filename);
26         let tmp_filename = format!("{}.tmp", filename_with_path);
27
28         {
29                 // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
30                 // rust stdlib 1.36 or higher.
31                 let mut f = fs::File::create(&tmp_filename)?;
32                 data.write_to_file(&mut f)?;
33                 f.sync_all()?;
34         }
35         fs::rename(&tmp_filename, &filename_with_path)?;
36         // Fsync the parent directory on Unix.
37         #[cfg(not(target_os = "windows"))]
38         {
39                 let path = Path::new(&filename_with_path).parent().unwrap();
40                 let dir_file = fs::OpenOptions::new().read(true).open(path)?;
41                 unsafe { libc::fsync(dir_file.as_raw_fd()); }
42         }
43         Ok(())
44 }
45
46 #[cfg(test)]
47 mod tests {
48         use super::{DiskWriteable, get_full_filepath, write_to_file};
49         use std::fs;
50         use std::io;
51         use std::io::Write;
52
53         struct TestWriteable{}
54         impl DiskWriteable for TestWriteable {
55                 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), io::Error> {
56                         writer.write_all(&[42; 1])
57                 }
58         }
59
60         // Test that if the persister's path to channel data is read-only, writing
61         // data to it fails. Windows ignores the read-only flag for folders, so this
62         // test is Unix-only.
63         #[cfg(not(target_os = "windows"))]
64         #[test]
65         fn test_readonly_dir() {
66                 let test_writeable = TestWriteable{};
67                 let filename = "test_readonly_dir_persister_filename".to_string();
68                 let path = "test_readonly_dir_persister_dir";
69                 fs::create_dir_all(path.to_string()).unwrap();
70                 let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
71                 perms.set_readonly(true);
72                 fs::set_permissions(path.to_string(), perms).unwrap();
73                 match write_to_file(path.to_string(), filename, &test_writeable) {
74                         Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
75                         _ => panic!("Unexpected error message")
76                 }
77         }
78
79         // Test failure to rename in the process of atomically creating a channel
80         // monitor's file. We induce this failure by making the `tmp` file a
81         // directory.
82         // Explanation: given "from" = the file being renamed, "to" = the
83         // renamee that already exists: Windows should fail because it'll fail
84         // whenever "to" is a directory, and Unix should fail because if "from" is a
85         // file, then "to" is also required to be a file.
86         #[test]
87         fn test_rename_failure() {
88                 let test_writeable = TestWriteable{};
89                 let filename = "test_rename_failure_filename";
90                 let path = "test_rename_failure_dir";
91                 // Create the channel data file and make it a directory.
92                 fs::create_dir_all(get_full_filepath(path.to_string(), filename.to_string())).unwrap();
93                 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
94                         Err(e) => {
95                                 #[cfg(not(target_os = "windows"))]
96                                 assert_eq!(e.kind(), io::ErrorKind::Other);
97                                 #[cfg(target_os = "windows")]
98                                 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
99                         }
100                         _ => panic!("Unexpected error message")
101                 }
102                 fs::remove_dir_all(path).unwrap();
103         }
104
105         #[test]
106         fn test_diskwriteable_failure() {
107                 struct FailingWriteable {}
108                 impl DiskWriteable for FailingWriteable {
109                         fn write_to_file(&self, _writer: &mut fs::File) -> Result<(), std::io::Error> {
110                                 Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
111                         }
112                 }
113
114                 let filename = "test_diskwriteable_failure";
115                 let path = "test_diskwriteable_failure_dir";
116                 let test_writeable = FailingWriteable{};
117                 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
118                         Err(e) => {
119                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
120                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
121                         },
122                         _ => panic!("unexpected result")
123                 }
124                 fs::remove_dir_all(path).unwrap();
125         }
126
127         // Test failure to create the temporary file in the persistence process.
128         // We induce this failure by having the temp file already exist and be a
129         // directory.
130         #[test]
131         fn test_tmp_file_creation_failure() {
132                 let test_writeable = TestWriteable{};
133                 let filename = "test_tmp_file_creation_failure_filename".to_string();
134                 let path = "test_tmp_file_creation_failure_dir".to_string();
135
136                 // Create the tmp file and make it a directory.
137                 let tmp_path = get_full_filepath(path.clone(), format!("{}.tmp", filename.clone()));
138                 fs::create_dir_all(tmp_path).unwrap();
139                 match write_to_file(path, filename, &test_writeable) {
140                         Err(e) => {
141                                 #[cfg(not(target_os = "windows"))]
142                                 assert_eq!(e.kind(), io::ErrorKind::Other);
143                                 #[cfg(target_os = "windows")]
144                                 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
145                         }
146                         _ => panic!("Unexpected error message")
147                 }
148         }
149 }