Merge pull request #1378 from ViktorTigerstrom/2022-03-include-htlc-min-max
[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::io::Write;
88         use std::path::PathBuf;
89
90         struct TestWriteable{}
91         impl Writeable for TestWriteable {
92                 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), std::io::Error> {
93                         writer.write_all(&[42; 1])
94                 }
95         }
96
97         // Test that if the persister's path to channel data is read-only, writing
98         // data to it fails. Windows ignores the read-only flag for folders, so this
99         // test is Unix-only.
100         #[cfg(not(target_os = "windows"))]
101         #[test]
102         fn test_readonly_dir() {
103                 let test_writeable = TestWriteable{};
104                 let filename = "test_readonly_dir_persister_filename".to_string();
105                 let path = "test_readonly_dir_persister_dir";
106                 fs::create_dir_all(path.to_string()).unwrap();
107                 let mut perms = fs::metadata(path.to_string()).unwrap().permissions();
108                 perms.set_readonly(true);
109                 fs::set_permissions(path.to_string(), perms).unwrap();
110                 let mut dest_file = PathBuf::from(path);
111                 dest_file.push(filename);
112                 match write_to_file(dest_file, &test_writeable) {
113                         Err(e) => assert_eq!(e.kind(), io::ErrorKind::PermissionDenied),
114                         _ => panic!("Unexpected error message")
115                 }
116         }
117
118         // Test failure to rename in the process of atomically creating a channel
119         // monitor's file. We induce this failure by making the `tmp` file a
120         // directory.
121         // Explanation: given "from" = the file being renamed, "to" = the destination
122         // file that already exists: Unix should fail because if "from" is a file,
123         // then "to" is also required to be a file.
124         // TODO: ideally try to make this work on Windows again
125         #[cfg(not(target_os = "windows"))]
126         #[test]
127         fn test_rename_failure() {
128                 let test_writeable = TestWriteable{};
129                 let filename = "test_rename_failure_filename";
130                 let path = "test_rename_failure_dir";
131                 let mut dest_file = PathBuf::from(path);
132                 dest_file.push(filename);
133                 // Create the channel data file and make it a directory.
134                 fs::create_dir_all(dest_file.clone()).unwrap();
135                 match write_to_file(dest_file, &test_writeable) {
136                         Err(e) => assert_eq!(e.raw_os_error(), Some(libc::EISDIR)),
137                         _ => panic!("Unexpected Ok(())")
138                 }
139                 fs::remove_dir_all(path).unwrap();
140         }
141
142         #[test]
143         fn test_diskwriteable_failure() {
144                 struct FailingWriteable {}
145                 impl Writeable for FailingWriteable {
146                         fn write<W: Writer>(&self, _writer: &mut W) -> Result<(), std::io::Error> {
147                                 Err(std::io::Error::new(std::io::ErrorKind::Other, "expected failure"))
148                         }
149                 }
150
151                 let filename = "test_diskwriteable_failure";
152                 let path = "test_diskwriteable_failure_dir";
153                 let test_writeable = FailingWriteable{};
154                 let mut dest_file = PathBuf::from(path);
155                 dest_file.push(filename);
156                 match write_to_file(dest_file, &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 = "test_tmp_file_creation_failure_dir";
174                 let mut dest_file = PathBuf::from(path);
175                 dest_file.push(filename);
176                 let mut tmp_file = dest_file.clone();
177                 tmp_file.set_extension("tmp");
178                 fs::create_dir_all(tmp_file).unwrap();
179                 match write_to_file(dest_file, &test_writeable) {
180                         Err(e) => {
181                                 #[cfg(not(target_os = "windows"))]
182                                 assert_eq!(e.raw_os_error(), Some(libc::EISDIR));
183                                 #[cfg(target_os = "windows")]
184                                 assert_eq!(e.kind(), io::ErrorKind::PermissionDenied);
185                         }
186                         _ => panic!("Unexpected error message")
187                 }
188         }
189 }