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