Debian Codegraph @

tests/stdio_redirect_tests.rs

raw symbols SCIP
1 #![allow(clippy::expect_used)]
2 #![allow(clippy::unwrap_used)]
3 #![allow(clippy::panic)]
4 #![allow(clippy::match_wild_err_arm)]
5 #![allow(clippy::similar_names)]
6 #![allow(clippy::uninlined_format_args)]
7 #![allow(clippy::cast_ptr_alignment)]
8 #![allow(clippy::ptr_as_ptr)]
9 #![allow(clippy::doc_markdown)]
10
11 /// Tests for stdio redirection to /dev/null
12 /// These tests verify that file descriptors 0,1,2 are not reused after closing stdio
13 use std::{fs::File, io::Write, os::unix::io::AsRawFd, process::exit};
14
15 use fork::{Fork, close_fd, fork, waitpid};
16
17 /// Test that demonstrates the fd reuse bug with close_fd()
18 ///
19 /// This test SHOULD FAIL with current implementation because:
20 /// - close_fd() closes fd 0,1,2
21 /// - Next File::create() will get fd=0, then fd=1, then fd=2
22 /// - This test expects fd >= 3
23 #[test]
24 #[should_panic(expected = "File descriptors were reused")]
25 fn test_close_fd_allows_fd_reuse() {
26 match fork() {
27 Ok(Fork::Parent(child)) => {
28 let result = waitpid(child);
29 // If child exited with error, the bug exists
30 if result.is_err()
31 || std::fs::read_to_string("/tmp/fork_test_fd_marker.txt")
32 .unwrap_or_default()
33 .contains("REUSED")
34 {
35 // Cleanup
36 let _ = std::fs::remove_file("/tmp/fork_test_fd_marker.txt");
37 panic!("File descriptors were reused (bug exists)");
38 }
39 }
40 Ok(Fork::Child) => {
41 // Close stdio
42 close_fd().unwrap();
43
44 // Open files - with current implementation, they WILL get fd 0,1,2
45 let f1 = File::create("/tmp/fork_test_fd1.txt").unwrap();
46 let f2 = File::create("/tmp/fork_test_fd2.txt").unwrap();
47 let f3 = File::create("/tmp/fork_test_fd3.txt").unwrap();
48
49 let fd1 = f1.as_raw_fd();
50 let fd2 = f2.as_raw_fd();
51 let fd3 = f3.as_raw_fd();
52
53 // Check if any fd is < 3 (the bug)
54 if fd1 < 3 || fd2 < 3 || fd3 < 3 {
55 // Write marker file to signal bug to parent
56 std::fs::write("/tmp/fork_test_fd_marker.txt", "REUSED").ok();
57 exit(1);
58 }
59
60 // If we get here, fds are >= 3 (the fix is working)
61 exit(0);
62 }
63 Err(_) => panic!("Fork failed"),
64 }
65 }
66
67 /// Test file descriptor reuse scenario
68 ///
69 /// This test demonstrates that println! would write to wrong file
70 #[test]
71 fn test_fd_reuse_corruption_scenario() {
72 match fork() {
73 Ok(Fork::Parent(child)) => {
74 waitpid(child).unwrap();
75
76 // Check what was written to the files
77 let content1 = std::fs::read_to_string("/tmp/fork_test_corruption1.txt").ok();
78 let content2 = std::fs::read_to_string("/tmp/fork_test_corruption2.txt").ok();
79
80 if let (Some(c1), Some(c2)) = (content1, content2) {
81 // With close_fd(), these files will contain the debug output!
82 // With redirect_stdio(), they will only contain intended data
83 if c1.contains("This should NOT") || c2.contains("This should NOT") {
84 eprintln!("BUG DETECTED: Debug output leaked to data files!");
85 eprintln!("File 1: {}", c1);
86 eprintln!("File 2: {}", c2);
87 // Don't panic - this is expected with close_fd()
88 } else {
89 println!("GOOD: Files only contain intended data");
90 }
91 }
92
93 // Cleanup
94 let _ = std::fs::remove_file("/tmp/fork_test_corruption1.txt");
95 let _ = std::fs::remove_file("/tmp/fork_test_corruption2.txt");
96 }
97 Ok(Fork::Child) => {
98 // Close stdio
99 close_fd().unwrap();
100
101 // Open files - they will get fd 0,1,2 with current implementation
102 let mut f1 = File::create("/tmp/fork_test_corruption1.txt").unwrap();
103 let mut f2 = File::create("/tmp/fork_test_corruption2.txt").unwrap();
104
105 // Try to write debug output to stderr (fd=2)
106 // With close_fd(), this might go to one of the files above!
107 // We can't use eprintln! here because it might corrupt the files
108 // Instead, directly write to demonstrate the issue
109 let fd1 = f1.as_raw_fd();
110 let fd2 = f2.as_raw_fd();
111
112 // If files got fd 0 or 1, then fd=2 might be another file or free
113 // Write a marker to show potential corruption
114 if fd1 <= 2 || fd2 <= 2 {
115 // Simulate what eprintln! would do
116 let stderr_msg = b"This should NOT appear in data files\n";
117 unsafe {
118 libc::write(2, stderr_msg.as_ptr() as *const _, stderr_msg.len());
119 }
120 }
121
122 // Write intended data
123 f1.write_all(b"data1\n").unwrap();
124 f2.write_all(b"data2\n").unwrap();
125
126 exit(0);
127 }
128 Err(_) => panic!("Fork failed"),
129 }
130 }
131
132 #[test]
133 fn test_redirect_stdio_prevents_fd_reuse() {
134 match fork() {
135 Ok(Fork::Parent(child)) => {
136 waitpid(child).unwrap();
137 }
138 Ok(Fork::Child) => {
139 // Redirect stdio to /dev/null
140 fork::redirect_stdio().unwrap();
141
142 // Open files - should get fd >= 3
143 let f1 = File::create("/tmp/fork_test_redirect1.txt").unwrap();
144 let f2 = File::create("/tmp/fork_test_redirect2.txt").unwrap();
145 let f3 = File::create("/tmp/fork_test_redirect3.txt").unwrap();
146
147 let fd1 = f1.as_raw_fd();
148 let fd2 = f2.as_raw_fd();
149 let fd3 = f3.as_raw_fd();
150
151 // With redirect_stdio(), these should all be >= 3
152 assert!(fd1 >= 3, "File 1 got fd < 3: {}", fd1);
153 assert!(fd2 >= 3, "File 2 got fd < 3: {}", fd2);
154 assert!(fd3 >= 3, "File 3 got fd < 3: {}", fd3);
155
156 // Cleanup
157 drop(f1);
158 drop(f2);
159 drop(f3);
160 let _ = std::fs::remove_file("/tmp/fork_test_redirect1.txt");
161 let _ = std::fs::remove_file("/tmp/fork_test_redirect2.txt");
162 let _ = std::fs::remove_file("/tmp/fork_test_redirect3.txt");
163
164 exit(0);
165 }
166 Err(_) => panic!("Fork failed"),
167 }
168 }
169
170 #[test]
171 fn test_redirect_stdio_println_safety() {
172 match fork() {
173 Ok(Fork::Parent(child)) => {
174 waitpid(child).unwrap();
175
176 // Verify files only contain intended data
177 let content = std::fs::read_to_string("/tmp/fork_test_println_safe.txt").unwrap();
178 assert!(!content.contains("debug"), "Debug output leaked to file!");
179 assert_eq!(content, "data\n", "File content is correct");
180
181 // Cleanup
182 let _ = std::fs::remove_file("/tmp/fork_test_println_safe.txt");
183 }
184 Ok(Fork::Child) => {
185 // Redirect stdio to /dev/null
186 fork::redirect_stdio().unwrap();
187
188 // Open file - gets fd >= 3
189 let mut f = File::create("/tmp/fork_test_println_safe.txt").unwrap();
190
191 // This println! will go to /dev/null (fd=1), not to the file
192 println!("debug message that should not appear in file");
193
194 // Write intended data
195 f.write_all(b"data\n").unwrap();
196
197 exit(0);
198 }
199 Err(_) => panic!("Fork failed"),
200 }
201 }
202
203 #[test]
204 fn test_daemon_uses_redirect_stdio() {
205 // Test that daemon() correctly uses redirect_stdio() internally
206 // We do this by manually testing the double-fork pattern with redirect_stdio()
207 match fork() {
208 Ok(Fork::Parent(child)) => {
209 waitpid(child).unwrap();
210
211 // Give daemon time to write file
212 std::thread::sleep(std::time::Duration::from_millis(100));
213
214 // Check file was created and has correct content
215 let content = std::fs::read_to_string("/tmp/fork_test_daemon_redirect.txt")
216 .expect("Daemon should have created file");
217
218 assert!(
219 !content.contains("Should not appear"),
220 "println! should have gone to /dev/null, not to file"
221 );
222 assert_eq!(
223 content.trim(),
224 "daemon data",
225 "File should have correct data"
226 );
227
228 // Cleanup
229 let _ = std::fs::remove_file("/tmp/fork_test_daemon_redirect.txt");
230 }
231 Ok(Fork::Child) => {
232 // Simulate what daemon() does
233 fork::setsid().unwrap();
234 fork::redirect_stdio().unwrap(); // This is what daemon() now uses
235
236 match fork() {
237 Ok(Fork::Parent(_)) => exit(0), // First child exits
238 Ok(Fork::Child) => {
239 // Grandchild (daemon) continues
240 let mut f = File::create("/tmp/fork_test_daemon_redirect.txt").unwrap();
241
242 // Verify file got fd >= 3
243 assert!(f.as_raw_fd() >= 3, "File should get fd >= 3");
244
245 // This println! goes to /dev/null
246 println!("Should not appear in file");
247
248 // Write actual data
249 f.write_all(b"daemon data\n").unwrap();
250 f.flush().unwrap();
251
252 exit(0);
253 }
254 Err(_) => exit(1),
255 }
256 }
257 Err(_) => panic!("Fork failed"),
258 }
259 }
260
261 #[test]
262 fn test_redirect_stdio_error_handling() {
263 // Test that redirect_stdio returns proper io::Error
264 match fork() {
265 Ok(Fork::Parent(child)) => {
266 waitpid(child).unwrap();
267 }
268 Ok(Fork::Child) => {
269 // Call redirect_stdio - should succeed
270 let result = fork::redirect_stdio();
271 assert!(result.is_ok(), "redirect_stdio should succeed");
272
273 // Verify we can access errno if needed (though it won't be set on success)
274 if let Err(e) = result {
275 // If it somehow fails, verify it's a proper io::Error
276 let _os_error = e.raw_os_error();
277 let _error_msg = format!("{}", e);
278 }
279
280 exit(0);
281 }
282 Err(_) => panic!("Fork failed"),
283 }
284 }
285
286 #[test]
287 fn test_redirect_stdio_idempotent() {
288 // Test that calling redirect_stdio multiple times is safe
289 match fork() {
290 Ok(Fork::Parent(child)) => {
291 waitpid(child).unwrap();
292 }
293 Ok(Fork::Child) => {
294 // First call
295 fork::redirect_stdio().unwrap();
296
297 // Second call should also work
298 fork::redirect_stdio().unwrap();
299
300 // Files should still get fd >= 3
301 let f = File::create("/tmp/fork_test_idempotent.txt").unwrap();
302 assert!(f.as_raw_fd() >= 3, "File should get fd >= 3");
303
304 // Cleanup
305 drop(f);
306 let _ = std::fs::remove_file("/tmp/fork_test_idempotent.txt");
307
308 exit(0);
309 }
310 Err(_) => panic!("Fork failed"),
311 }
312 }