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};
87 use std::path::PathBuf;
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])
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
99 #[cfg(not(target_os = "windows"))]
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")
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
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"))]
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(())")
138 fs::remove_dir_all(path).unwrap();
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"))
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) {
157 assert_eq!(e.kind(), std::io::ErrorKind::Other);
158 assert_eq!(e.get_ref().unwrap().to_string(), "expected failure");
160 _ => panic!("unexpected result")
162 fs::remove_dir_all(path).unwrap();
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
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) {
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);
185 _ => panic!("Unexpected error message")