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