Debian Codegraph @

examples/demonstrate_fd_reuse_bug.rs

raw symbols SCIP
1 #![allow(clippy::expect_used)]
2 #![allow(clippy::unwrap_used)]
3 #![allow(clippy::panic)]
4 #![allow(clippy::uninlined_format_args)]
5 #![allow(clippy::match_wild_err_arm)]
6 #![allow(clippy::cast_ptr_alignment)]
7 #![allow(clippy::doc_markdown)]
8 #![allow(clippy::ptr_as_ptr)]
9
10 /// Educational demonstration of the file descriptor reuse bug
11 ///
12 /// This example shows:
13 /// 1. The BUG: How close_fd() causes fd reuse
14 /// 2. The FIX: How redirect_stdio() prevents fd reuse
15 ///
16 /// Run with: cargo run --example demonstrate_fd_reuse_bug
17 use std::{fs::File, io::Write, os::unix::io::AsRawFd, process::exit};
18
19 use fork::{Fork, close_fd, fork, redirect_stdio, waitpid};
20
21 fn main() {
22 println!("\n╔═══════════════════════════════════════════════════════════════╗");
23 println!("║ DEMONSTRATION: File Descriptor Reuse Bug ║");
24 println!("╚═══════════════════════════════════════════════════════════════╝\n");
25
26 demonstrate_bug();
27 demonstrate_fix();
28
29 println!("\n╔═══════════════════════════════════════════════════════════════╗");
30 println!("║ SUMMARY ║");
31 println!("╚═══════════════════════════════════════════════════════════════╝");
32 println!("\nBUG: close_fd() frees fd 0,1,2 → files reuse them → corruption!");
33 println!("FIX: redirect_stdio() keeps fd 0,1,2 busy → files get fd >= 3\n");
34 }
35
36 fn demonstrate_bug() {
37 println!("═══════════════════════════════════════════════════════════════");
38 println!("PART 1: THE BUG (using close_fd)");
39 println!("═══════════════════════════════════════════════════════════════\n");
40
41 match fork() {
42 Ok(Fork::Parent(child)) => {
43 waitpid(child).unwrap();
44
45 // Read what the child wrote
46 let content = std::fs::read_to_string("/tmp/demo_bug.txt").unwrap_or_default();
47
48 println!("\nResult with close_fd():");
49 println!(" File content: '{}'", content.trim());
50
51 if content.contains("This is debug output") {
52 println!(" ⚠️ BUG DETECTED: Debug output corrupted the file!");
53 } else {
54 println!(" File only contains: {}", content.trim());
55 }
56
57 // Cleanup
58 let _ = std::fs::remove_file("/tmp/demo_bug.txt");
59 }
60 Ok(Fork::Child) => {
61 // Close stdio - THIS CAUSES THE BUG
62 close_fd().unwrap();
63
64 // Open a file - it will get a low fd (0, 1, or 2)
65 let mut file = File::create("/tmp/demo_bug.txt").unwrap();
66 let fd = file.as_raw_fd();
67
68 println!("After close_fd():");
69 println!(" File got fd = {}", fd);
70
71 if fd < 3 {
72 println!(" ⚠️ WARNING: File got fd < 3!");
73 println!(" Any println! or panic will write to this file!\n");
74
75 // Simulate what might happen with debug output
76 // We'll write directly to fd=2 (stderr) to show the problem
77 let debug_msg = b"This is debug output that should NOT be in the file!\n";
78 unsafe {
79 // If another file got fd=2, this write goes to that file!
80 libc::write(2, debug_msg.as_ptr() as *const _, debug_msg.len());
81 }
82 }
83
84 // Write intended data
85 file.write_all(b"Expected data\n").unwrap();
86 exit(0);
87 }
88 Err(_) => panic!("Fork failed"),
89 }
90 }
91
92 fn demonstrate_fix() {
93 println!("\n═══════════════════════════════════════════════════════════════");
94 println!("PART 2: THE FIX (using redirect_stdio)");
95 println!("═══════════════════════════════════════════════════════════════\n");
96
97 match fork() {
98 Ok(Fork::Parent(child)) => {
99 waitpid(child).unwrap();
100
101 // Read what the child wrote
102 let content = std::fs::read_to_string("/tmp/demo_fix.txt").unwrap_or_default();
103
104 println!("\nResult with redirect_stdio():");
105 println!(" File content: '{}'", content.trim());
106
107 if content.contains("debug output") {
108 println!(" ❌ UNEXPECTED: Debug leaked to file");
109 } else {
110 println!(" ✅ SUCCESS: File only contains intended data!");
111 println!(" Debug output went to /dev/null (discarded safely)");
112 }
113
114 // Cleanup
115 let _ = std::fs::remove_file("/tmp/demo_fix.txt");
116 }
117 Ok(Fork::Child) => {
118 // Redirect stdio to /dev/null - THIS FIXES THE BUG
119 redirect_stdio().unwrap();
120
121 // Open a file - it will get fd >= 3
122 let mut file = File::create("/tmp/demo_fix.txt").unwrap();
123 let fd = file.as_raw_fd();
124
125 println!("After redirect_stdio():");
126 println!(" File got fd = {}", fd);
127 println!(" fd 0,1,2 are now occupied by /dev/null");
128
129 if fd >= 3 {
130 println!(" ✅ GOOD: File got fd >= 3");
131 println!(" Any println! or panic goes to /dev/null (safe)\n");
132
133 // Try to write debug output - it goes to /dev/null!
134 let debug_msg = b"This is debug output that goes to /dev/null\n";
135 unsafe {
136 // This write goes to /dev/null, not to our file!
137 libc::write(2, debug_msg.as_ptr() as *const _, debug_msg.len());
138 }
139 }
140
141 // Write intended data
142 file.write_all(b"Expected data\n").unwrap();
143 exit(0);
144 }
145 Err(_) => panic!("Fork failed"),
146 }
147 }