]> git.bitcoin.ninja Git - rust-lightning/blob - lightning-persister/src/util.rs
print readonly
[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: creating dir");
43         fs::create_dir_all(path.clone())?;
44         println!("VMW: created dir");
45
46         println!("VMW: entries in dir:");
47         let dir_perms = fs::metadata(path.clone()).unwrap().permissions();
48         println!("VMW: dir perms: {:?}, readonly: {}", dir_perms, dir_perms.readonly());
49         let dir = PathBuf::from(path.clone());
50         for entry in fs::read_dir(dir).unwrap() {
51                 let entry = entry.unwrap();
52                 let metadata = entry.metadata().unwrap();
53                 println!("VMW: entry in dir: {:?}, perms in entry: {:?}, readonly: {}", entry.path(), metadata.permissions(), metadata.permissions().readonly());
54         }
55         // Do a crazy dance with lots of fsync()s to be overly cautious here...
56         // We never want to end up in a state where we've lost the old data, or end up using the
57         // old data on power loss after we've returned.
58         // The way to atomically write a file on Unix platforms is:
59         // open(tmpname), write(tmpfile), fsync(tmpfile), close(tmpfile), rename(), fsync(dir)
60         let filename_with_path = get_full_filepath(path.clone(), filename);
61         let tmp_filename = format!("{}.tmp", filename_with_path);
62
63         {
64                 // Note that going by rust-lang/rust@d602a6b, on MacOS it is only safe to use
65                 // rust stdlib 1.36 or higher.
66                 println!("VMW: about to create file");
67                 let mut f = fs::File::create(&tmp_filename)?;
68                 println!("VMW: created file");
69                 data.write_to_file(&mut f)?;
70                 println!("VMW: about to sync all");
71                 f.sync_all()?;
72                 println!("VMW: sync'd all");
73         }
74         // Fsync the parent directory on Unix.
75         #[cfg(not(target_os = "windows"))]
76         {
77                 fs::rename(&tmp_filename, &filename_with_path)?;
78                 let path = Path::new(&filename_with_path).parent().unwrap();
79                 let dir_file = fs::OpenOptions::new().read(true).open(path)?;
80                 unsafe { libc::fsync(dir_file.as_raw_fd()); }
81         }
82         #[cfg(target_os = "windows")]
83         {
84                 let mut dir_perms = fs::metadata(path.clone()).unwrap().permissions();
85                 dir_perms.set_readonly(false);
86                 if let Ok(metadata) = fs::metadata(filename_with_path.clone()) {
87                         let mut perms = metadata.permissions();
88                         perms.set_readonly(false);
89                 }
90     // let mut perms = fs::metadata(filename_with_path.clone())?.permissions();
91     let mut tmp_perms = fs::metadata(tmp_filename.clone())?.permissions();
92                 tmp_perms.set_readonly(false);
93                 println!("VMW: about to rename");
94                 let src = PathBuf::from(tmp_filename);
95                 let dst = PathBuf::from(filename_with_path);
96                 call!(unsafe {winapi::um::winbase::MoveFileExW(
97                         path_to_windows_str(src).as_ptr(), path_to_windows_str(dst).as_ptr(),
98                         winapi::um::winbase::MOVEFILE_WRITE_THROUGH | winapi::um::winbase::MOVEFILE_REPLACE_EXISTING
99                 )});
100                 println!("VMW: renamed");
101         }
102         Ok(())
103 }
104
105 #[cfg(test)]
106 mod tests {
107         use super::{DiskWriteable, get_full_filepath, write_to_file};
108         use std::fs;
109         use std::io;
110         use std::io::Write;
111
112         struct TestWriteable{}
113         impl DiskWriteable for TestWriteable {
114                 fn write_to_file(&self, writer: &mut fs::File) -> Result<(), io::Error> {
115                         writer.write_all(&[42; 1])
116                 }
117         }
118
119         // Test that if the persister's path to channel data is read-only, writing
120         // data to it fails. Windows ignores the read-only flag for folders, so this
121         // test is Unix-only.
122         #[cfg(not(target_os = "windows"))]
123         #[test]
124         fn test_readonly_dir() {
125                 let test_writeable = TestWriteable{};
126                 let filename = "test_readonly_dir_persister_filename".to_string();
127                 let path = "test_readonly_dir_persister_dir";
128                 fs::create_dir_all(path.to_string()).unwrap();
129                 let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
130                 perms.set_readonly(true);
131                 fs::set_permissions(path.to_string(), perms).unwrap();
132                 match write_to_file(path.to_string(), filename, &test_writeable) {
133                         Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
134                         _ => panic!("Unexpected error message")
135                 }
136         }
137
138         // Test failure to rename in the process of atomically creating a channel
139         // monitor's file. We induce this failure by making the `tmp` file a
140         // directory.
141         // Explanation: given "from" = the file being renamed, "to" = the
142         // renamee that already exists: Windows should fail because it'll fail
143         // whenever "to" is a directory, and Unix should fail because if "from" is a
144         // file, then "to" is also required to be a file.
145         #[test]
146         fn test_rename_failure() {
147                 let test_writeable = TestWriteable{};
148                 let filename = "test_rename_failure_filename";
149                 let path = "test_rename_failure_dir";
150                 // Create the channel data file and make it a directory.
151                 fs::create_dir_all(get_full_filepath(path.to_string(), filename.to_string())).unwrap();
152                 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
153                         Err(e) => {
154                                 #[cfg(not(target_os = "windows"))]
155                                 assert_eq!(e.kind(), io::ErrorKind::Other);
156                                 #[cfg(target_os = "windows")]
157                                 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
158                         }
159                         _ => panic!("Unexpected error message")
160                 }
161                 fs::remove_dir_all(path).unwrap();
162         }
163
164         #[test]
165         fn test_diskwriteable_failure() {
166                 struct FailingWriteable {}
167                 impl DiskWriteable for FailingWriteable {
168                         fn write_to_file(&self, _writer: &mut fs::File) -> Result<(), std::io::Error> {
169                                 Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
170                         }
171                 }
172
173                 let filename = "test_diskwriteable_failure";
174                 let path = "test_diskwriteable_failure_dir";
175                 let test_writeable = FailingWriteable{};
176                 match write_to_file(path.to_string(), filename.to_string(), &test_writeable) {
177                         Err(e) => {
178                                 assert_eq!(e.kind(), std::io::ErrorKind::Other);
179                                 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
180                         },
181                         _ => panic!("unexpected result")
182                 }
183                 fs::remove_dir_all(path).unwrap();
184         }
185
186         // Test failure to create the temporary file in the persistence process.
187         // We induce this failure by having the temp file already exist and be a
188         // directory.
189         #[test]
190         fn test_tmp_file_creation_failure() {
191                 let test_writeable = TestWriteable{};
192                 let filename = "test_tmp_file_creation_failure_filename".to_string();
193                 let path = "test_tmp_file_creation_failure_dir".to_string();
194
195                 // Create the tmp file and make it a directory.
196                 let tmp_path = get_full_filepath(path.clone(), format!("{}.tmp", filename.clone()));
197                 fs::create_dir_all(tmp_path).unwrap();
198                 match write_to_file(path, filename, &test_writeable) {
199                         Err(e) => {
200                                 #[cfg(not(target_os = "windows"))]
201                                 assert_eq!(e.kind(), io::ErrorKind::Other);
202                                 #[cfg(target_os = "windows")]
203                                 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
204                         }
205                         _ => panic!("Unexpected error message")
206                 }
207         }
208 }