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