1 #[cfg(target_os = "windows")]
5 use std::path::PathBuf;
6 use std::io::BufWriter;
8 #[cfg(not(target_os = "windows"))]
9 use std::os::unix::io::AsRawFd;
11 use lightning::util::ser::Writeable;
13 #[cfg(target_os = "windows")]
16 std::os::windows::ffi::OsStrExt
19 #[cfg(target_os = "windows")]
25 return Err(std::io::Error::last_os_error())
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()
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");
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)
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()?;
54 // Fsync the parent directory on Unix.
55 #[cfg(not(target_os = "windows"))]
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()); }
61 #[cfg(target_os = "windows")]
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
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
82 use lightning::util::ser::{Writer, Writeable};
84 use super::{write_to_file};
88 use std::path::PathBuf;
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])
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
100 #[cfg(not(target_os = "windows"))]
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")
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
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"))]
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(())")
139 fs::remove_dir_all(path).unwrap();
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"))
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) {
158 assert_eq!(e.kind(), std::io::ErrorKind::Other);
159 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
161 _ => panic!("unexpected result")
163 fs::remove_dir_all(path).unwrap();
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
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) {
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);
186 _ => panic!("Unexpected error message")