Check IO errors in test using `raw_os_error()` instead of `kind()`
[rust-lightning] / lightning-persister / src / util.rs
1 #[cfg(target_os = "windows")]
2 extern crate winapi;
3
4 use std::fs;
5 use std::path::{Path, PathBuf};
6
7 #[cfg(not(target_os = "windows"))]
8 use std::os::unix::io::AsRawFd;
9
10 #[cfg(target_os = "windows")]
11 use {
12         std::ffi::OsStr,
13         std::os::windows::ffi::OsStrExt
14 };
15
16 pub(crate) trait DiskWriteable {
17         fn write_to_file(&self, writer: &mut fs::File) -> Result<(), std::io::Error>;
18 }
19
20 pub(crate) fn get_full_filepath(mut filepath: PathBuf, filename: String) -> String {
21         filepath.push(filename);
22         filepath.to_str().unwrap().to_string()
23 }
24
25 #[cfg(target_os = "windows")]
26 macro_rules! call {
27         ($e: expr) => (
28                 if $e != 0 {
29                         return Ok(())
30                 } else {
31                         return Err(std::io::Error::last_os_error())
32                 }
33         )
34 }
35
36 #[cfg(target_os = "windows")]
37 fn path_to_windows_str<T: AsRef<OsStr>>(path: T) -> Vec<winapi::shared::ntdef::WCHAR> {
38         path.as_ref().encode_wide().chain(Some(0)).collect()
39 }
40
41 #[allow(bare_trait_objects)]
42 pub(crate) fn write_to_file<D: DiskWriteable>(path: PathBuf, filename: String, data: &D) -> std::io::Result<()> {
43         fs::create_dir_all(path.clone())?;
44         // Do a crazy dance with lots of fsync()s to be overly cautious here...
45         // We never want to end up in a state where we've lost the old data, or end up using the
46         // old data on power loss after we've returned.
47         // The way to atomically write a file on Unix platforms is:
48         // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
49         let filename_with_path = get_full_filepath(path, filename);
50         let tmp_filename = format!("{}.tmp", filename_with_path.clone());
51
52         {
53                 // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
54                 // rust stdlib 1.36 or higher.
55                 let mut f = fs::File::create(&tmp_filename)?;
56                 data.write_to_file(&mut f)?;
57                 f.sync_all()?;
58         }
59         // Fsync the parent directory on Unix.
60         #[cfg(not(target_os = "windows"))]
61         {
62                 fs::rename(&tmp_filename, &filename_with_path)?;
63                 let path = Path::new(&filename_with_path).parent().unwrap();
64                 let dir_file = fs::OpenOptions::new().read(true).open(path)?;
65                 unsafe { libc::fsync(dir_file.as_raw_fd()); }
66         }
67         #[cfg(target_os = "windows")]
68         {
69                 let src = PathBuf::from(tmp_filename.clone());
70                 let dst = PathBuf::from(filename_with_path.clone());
71                 if Path::new(&filename_with_path.clone()).exists() {
72                         unsafe {winapi::um::winbase::ReplaceFileW(
73                                 path_to_windows_str(dst).as_ptr(), path_to_windows_str(src).as_ptr(), std::ptr::null(),
74                                 winapi::um::winbase::REPLACEFILE_IGNORE_MERGE_ERRORS,
75                                 std::ptr::null_mut() as *mut winapi::ctypes::c_void,
76                                 std::ptr::null_mut() as *mut winapi::ctypes::c_void
77                         )};
78                 } else {
79                         call!(unsafe {winapi::um::winbase::MoveFileExW(
80                                 path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(),
81                                 winapi::um::winbase::MOVEFILE_WRITE_THROUGH | winapi::um::winbase::MOVEFILE_REPLACE_EXISTING
82                         )});
83                 }
84         }
85         Ok(())
86 }
87
88 #[cfg(test)]
89 mod tests {
90         use super::{DiskWriteable, get_full_filepath, write_to_file};
91         use std::fs;
92         use std::io;
93         use std::io::Write;
94         use std::path::PathBuf;
95
96         struct TestWriteable{}
97         impl DiskWriteable for TestWriteable {
98                 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), io::Error> {
99                         writer.write_all(&[42; 1])
100                 }
101         }
102
103         // Test that if the persister's path to channel data is read-only, writing
104         // data to it fails. Windows ignores the read-only flag for folders, so this
105         // test is Unix-only.
106         #[cfg(not(target_os = "windows"))]
107         #[test]
108         fn test_readonly_dir() {
109                 let test_writeable = TestWriteable{};
110                 let filename = "test_readonly_dir_persister_filename".to_string();
111                 let path = "test_readonly_dir_persister_dir";
112                 fs::create_dir_all(path.to_string()).unwrap();
113                 let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
114                 perms.set_readonly(true);
115                 fs::set_permissions(path.to_string(), perms).unwrap();
116                 match write_to_file(PathBuf::from(path.to_string()), filename, &test_writeable) {
117                         Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
118                         _ => panic!("Unexpected error message")
119                 }
120         }
121
122         // Test failure to rename in the process of atomically creating a channel
123         // monitor's file. We induce this failure by making the `tmp` file a
124         // directory.
125         // Explanation: given "from" = the file being renamed, "to" = the destination
126         // file that already exists: Unix should fail because if "from" is a file,
127         // then "to" is also required to be a file.
128         // TODO: ideally try to make this work on Windows again
129         #[cfg(not(target_os = "windows"))]
130         #[test]
131         fn test_rename_failure() {
132                 let test_writeable = TestWriteable{};
133                 let filename = "test_rename_failure_filename";
134                 let path = PathBuf::from("test_rename_failure_dir");
135                 // Create the channel data file and make it a directory.
136                 fs::create_dir_all(get_full_filepath(path.clone(), filename.to_string())).unwrap();
137                 match write_to_file(path.clone(), filename.to_string(), &test_writeable) {
138                         Err(e) => assert_eq!(e.raw_os_error(), Some(libc::EISDIR)),
139                         _ => panic!("Unexpected Ok(())")
140                 }
141                 fs::remove_dir_all(path).unwrap();
142         }
143
144         #[test]
145         fn test_diskwriteable_failure() {
146                 struct FailingWriteable {}
147                 impl DiskWriteable for FailingWriteable {
148                         fn write_to_file(&self, _writer: &mut fs::File) -> Result<(), std::io::Error> {
149                                 Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
150                         }
151                 }
152
153                 let filename = "test_diskwriteable_failure";
154                 let path = PathBuf::from("test_diskwriteable_failure_dir");
155                 let test_writeable = FailingWriteable{};
156                 match write_to_file(path.clone(), filename.to_string(), &test_writeable) {
157                         Err(e) => {
158                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
159                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
160                         },
161                         _ => panic!("unexpected result")
162                 }
163                 fs::remove_dir_all(path).unwrap();
164         }
165
166         // Test failure to create the temporary file in the persistence process.
167         // We induce this failure by having the temp file already exist and be a
168         // directory.
169         #[test]
170         fn test_tmp_file_creation_failure() {
171                 let test_writeable = TestWriteable{};
172                 let filename = "test_tmp_file_creation_failure_filename".to_string();
173                 let path = PathBuf::from("test_tmp_file_creation_failure_dir");
174
175                 // Create the tmp file and make it a directory.
176                 let tmp_path = get_full_filepath(path.clone(), format!("{}.tmp", filename.clone()));
177                 fs::create_dir_all(tmp_path).unwrap();
178                 match write_to_file(path, filename, &test_writeable) {
179                         Err(e) => {
180                                 #[cfg(not(target_os = "windows"))]
181                                 assert_eq!(e.raw_os_error(), Some(libc::EISDIR));
182                                 #[cfg(target_os = "windows")]
183                                 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
184                         }
185                         _ => panic!("Unexpected error message")
186                 }
187         }
188 }