Skip to content

Commit ffa06a1

Browse files
committed
tail: make device following portable and nonblocking
Watch device parents with native backends and keep independent device readers nonblocking after initial reads and on reopen. Preserve inherited stdin flags and compare device and inode when following names. Deduplicate event batches with one set and avoid scanning devices for ordinary updates to open inputs. Add regressions, assert output waits, and fix the Unix permissions and non-Unix stub lints. Signed-off-by: rleungx <rleungx@gmail.com>
1 parent ac42f8b commit ffa06a1

5 files changed

Lines changed: 295 additions & 68 deletions

File tree

‎src/uu/tail/src/follow/files.rs‎

Lines changed: 65 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
// file that was distributed with this source code.
55

66
// spell-checker:ignore tailable stdlib (stdlib)
7+
// spell-checker:ignore nonblocking POLLNVAL
78

89
use crate::args::Settings;
910
use crate::chunks::BytesChunkBuffer;
@@ -139,17 +140,7 @@ impl FileHandling {
139140

140141
/// Reopen the file at the monitored `path`
141142
pub fn update_reader(&mut self, path: &Path) -> UResult<()> {
142-
// A FIFO without a writer must not block the thread serving all files.
143-
let file = open_file(path, true)?;
144-
#[cfg(unix)]
145-
if !self.nonblocking {
146-
use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
147-
148-
// Without --pid, preserve blocking reads after the nonblocking open.
149-
let flags = fcntl_getfl(&file).map_err(io::Error::from)?;
150-
fcntl_setfl(&file, flags & !OFlags::NONBLOCK).map_err(io::Error::from)?;
151-
}
152-
let is_character_device = is_character_device(&file)?;
143+
let (file, is_character_device) = open_follow_file(path, self.nonblocking)?;
153144
let key = Self::canonicalize_path(path);
154145
let data = self.map.get_mut(&key).unwrap();
155146
data.reader.replace(BufReader::new(file));
@@ -261,7 +252,7 @@ impl PathData {
261252
let reader = if old_reader.is_some() {
262253
// Use old reader with the same file descriptor if there is one
263254
old_reader
264-
} else if let Ok(file) = open_file(path, nonblocking) {
255+
} else if let Ok((file, _)) = open_follow_file(path, nonblocking) {
265256
// Open new file tail from start
266257
Some(BufReader::new(file))
267258
} else {
@@ -278,13 +269,35 @@ impl PathData {
278269
}
279270
}
280271

272+
fn open_follow_file(
273+
path: &Path,
274+
#[cfg(unix)] nonblocking: bool,
275+
#[cfg(not(unix))] _: bool,
276+
) -> io::Result<(File, bool)> {
277+
// A FIFO without a writer must not block the thread serving all files.
278+
let file = open_file(path, true)?;
279+
let is_character_device = is_character_device(&file)?;
280+
#[cfg(unix)]
281+
if !nonblocking && !is_character_device {
282+
use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
283+
284+
// Devices must stay nonblocking even if another reader consumes their
285+
// input between the readiness check and the read. Preserve the existing
286+
// blocking behavior for other files when --pid is absent.
287+
let flags = fcntl_getfl(&file).map_err(io::Error::from)?;
288+
fcntl_setfl(&file, flags & !OFlags::NONBLOCK).map_err(io::Error::from)?;
289+
}
290+
Ok((file, is_character_device))
291+
}
292+
281293
/// Check the descriptor rather than a path that may already name another file.
282294
#[cfg(unix)]
283295
fn is_character_device(file: &File) -> io::Result<bool> {
284296
Ok(file.metadata()?.file_type().is_char_device())
285297
}
286298

287299
#[cfg(not(unix))]
300+
#[allow(clippy::unnecessary_wraps)] // Match the fallible Unix implementation.
288301
fn is_character_device(_file: &File) -> io::Result<bool> {
289302
Ok(false)
290303
}
@@ -333,6 +346,7 @@ fn device_is_readable(file: &File) -> io::Result<bool> {
333346
}
334347

335348
/// Check readiness before each refill without changing flags shared with stdin's owner.
349+
/// Owned devices are nonblocking; inherited stdin can still race with another reader.
336350
#[cfg(unix)]
337351
struct AvailableBytes<'a>(&'a mut BufReader<File>);
338352

@@ -368,6 +382,27 @@ mod tests {
368382
use std::sync::Barrier;
369383
use std::sync::atomic::{AtomicBool, Ordering};
370384

385+
#[test]
386+
fn reopened_device_stays_nonblocking() {
387+
let settings = Settings::default();
388+
let path = Path::new("/dev/null");
389+
let mut files = FileHandling::from(&settings);
390+
files.insert(
391+
path,
392+
PathData::new(None, None, "device", false).unwrap(),
393+
false,
394+
);
395+
396+
files.update_reader(path).unwrap();
397+
398+
let reader = files.get(path).reader.as_ref().unwrap();
399+
assert!(
400+
fcntl_getfl(reader.get_ref())
401+
.unwrap()
402+
.contains(OFlags::NONBLOCK)
403+
);
404+
}
405+
371406
#[test]
372407
fn device_reads_preserve_shared_flags() {
373408
let file = File::open("/dev/zero").unwrap();
@@ -416,4 +451,22 @@ mod tests {
416451
assert_eq!(bytes, b"ata");
417452
assert!(reader.buffer().is_empty());
418453
}
454+
455+
#[test]
456+
fn device_hangup_drains_data_without_busy_looping() {
457+
let (input, mut output) = UnixStream::pair().unwrap();
458+
let mut reader = BufReader::new(File::from(OwnedFd::from(input)));
459+
output.write_all(b"data").unwrap();
460+
drop(output);
461+
462+
let mut chunks = BytesChunkBuffer::new(u64::MAX);
463+
assert!(!read_device(&mut reader, &mut chunks).unwrap());
464+
let mut bytes = Vec::new();
465+
chunks.write(&mut bytes).unwrap();
466+
assert_eq!(bytes, b"data");
467+
468+
let mut chunks = BytesChunkBuffer::new(u64::MAX);
469+
assert!(!read_device(&mut reader, &mut chunks).unwrap());
470+
assert!(!chunks.has_data());
471+
}
419472
}

‎src/uu/tail/src/follow/watch.rs‎

Lines changed: 83 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
// file that was distributed with this source code.
55

66
// spell-checker:ignore (ToDO) tailable untailable stdlib kqueue Uncategorized unwatch
7+
// spell-checker:ignore nonblocking
78

89
use crate::args::{FollowMode, Settings};
910
use crate::follow::files::{FileHandling, PathData};
@@ -92,17 +93,21 @@ impl WatcherRx {
9293
{
9394
return Ok(false);
9495
}
95-
self.watch(path, RecursiveMode::NonRecursive)?;
96-
// Native events let us notice name replacements promptly. The polling
97-
// pass also checks device names, so an unreadable parent is harmless.
98-
// PollWatcher must not watch the parent: it would also hash siblings.
99-
if !use_polling && let Some(parent) = path.parent() {
96+
// kqueue opens watched paths in blocking mode, which can wait for a
97+
// carrier on serial devices. Native watchers only need the parent to
98+
// report name replacements; device input is polled separately.
99+
if use_polling {
100+
// Watching the parent would also hash unrelated siblings.
101+
self.watch(path, RecursiveMode::NonRecursive)?;
102+
} else if let Some(parent) = path.parent() {
103+
// The polling pass checks names even if the parent is unreadable.
100104
let _ = self.watcher.watch(parent, RecursiveMode::NonRecursive);
101105
}
102106
Ok(true)
103107
}
104108

105109
#[cfg(not(unix))]
110+
#[allow(clippy::unnecessary_wraps)] // Match the fallible Unix implementation.
106111
fn watch_character_device(&mut self, _path: &Path, _use_polling: bool) -> UResult<bool> {
107112
Ok(false)
108113
}
@@ -679,22 +684,34 @@ pub fn follow(mut observer: Observer, settings: &Settings) -> UResult<()> {
679684
}
680685

681686
let mut paths = vec![]; // Paths worth checking for new content to print
687+
let mut scheduled = HashSet::new();
682688

683689
// Helper closure to process a single event
684-
let process_event = |observer: &mut Observer,
685-
event: notify::Event,
686-
settings: &Settings,
687-
paths: &mut Vec<PathBuf>|
690+
let mut process_event = |observer: &mut Observer,
691+
event: notify::Event,
692+
settings: &Settings,
693+
paths: &mut Vec<PathBuf>|
688694
-> UResult<()> {
695+
// A content or metadata update to a tracked input cannot replace a
696+
// sibling device's name. Avoid scanning all devices for such events.
697+
let input_update = matches!(
698+
event.kind,
699+
notify::EventKind::Access(_)
700+
| notify::EventKind::Modify(
701+
notify::event::ModifyKind::Data(_) | notify::event::ModifyKind::Metadata(_)
702+
)
703+
) && event.paths.iter().all(|path| {
704+
observer.files.contains_key(path) && observer.files.get(path).reader.is_some()
705+
});
689706
// kqueue can report a directory change without the replaced child's
690707
// name. Recheck devices in that directory before reading their FDs.
691-
if observer.follow_name() {
708+
if observer.follow_name() && !input_update {
692709
for device in observer.files.character_devices() {
693710
if event.paths.iter().any(|path| {
694711
device
695712
.parent()
696713
.is_some_and(|parent| path == parent || path.parent() == Some(parent))
697-
}) && !paths.contains(device)
714+
}) && scheduled.insert(device.clone())
698715
{
699716
paths.push(device.clone());
700717
}
@@ -709,15 +726,15 @@ pub fn follow(mut observer: Observer, settings: &Settings) -> UResult<()> {
709726
if observer.files.character_devices().contains(path) {
710727
// Device events can describe the old target after a rename.
711728
// Check the current name in the print loop; -f keeps its FD.
712-
if !paths.contains(path) {
729+
if scheduled.insert(path.clone()) {
713730
paths.push(path.clone());
714731
}
715732
return Ok(());
716733
}
717734
// Handle Event if it is about a path that we are monitoring
718735
let new_paths = observer.handle_event(&event, settings)?;
719736
for p in new_paths {
720-
if !paths.contains(&p) {
737+
if scheduled.insert(p.clone()) {
721738
paths.push(p);
722739
}
723740
}
@@ -803,11 +820,14 @@ pub fn follow(mut observer: Observer, settings: &Settings) -> UResult<()> {
803820
{
804821
// The polling backend already includes every input above.
805822
if !observer.use_polling {
806-
let mut devices: HashSet<_> = observer.files.character_devices().iter().collect();
807-
for path in &paths {
808-
devices.remove(path);
809-
}
810-
paths.extend(devices.into_iter().cloned());
823+
paths.extend(
824+
observer
825+
.files
826+
.character_devices()
827+
.iter()
828+
.filter(|path| scheduled.insert((*path).clone()))
829+
.cloned(),
830+
);
811831
}
812832
last_device_poll = Instant::now();
813833
}
@@ -838,7 +858,52 @@ pub fn follow(mut observer: Observer, settings: &Settings) -> UResult<()> {
838858
mod tests {
839859
use super::*;
840860
use notify::event::{ModifyKind, RenameMode};
861+
use rstest::rstest;
841862
use std::io::{Seek, SeekFrom};
863+
use std::sync::{Arc, Mutex};
864+
865+
#[derive(Default)]
866+
struct RecordingWatcher(Arc<Mutex<Vec<PathBuf>>>);
867+
868+
impl Watcher for RecordingWatcher {
869+
fn new<F: notify::EventHandler>(_: F, _: notify::Config) -> notify::Result<Self> {
870+
Ok(Self::default())
871+
}
872+
873+
fn watch(&mut self, path: &Path, _: RecursiveMode) -> notify::Result<()> {
874+
self.0.lock().unwrap().push(path.to_owned());
875+
Ok(())
876+
}
877+
878+
fn unwatch(&mut self, _: &Path) -> notify::Result<()> {
879+
Ok(())
880+
}
881+
882+
fn kind() -> WatcherKind {
883+
WatcherKind::NullWatcher
884+
}
885+
}
886+
887+
#[rstest]
888+
#[case(false, "/dev")]
889+
#[case(true, "/dev/null")]
890+
fn device_watch_does_not_open_device_or_poll_siblings(
891+
#[case] use_polling: bool,
892+
#[case] expected: &str,
893+
) {
894+
let watcher = RecordingWatcher::default();
895+
let watched = Arc::clone(&watcher.0);
896+
let (_, receiver) = channel();
897+
let mut watcher_rx = WatcherRx::new(Box::new(watcher), receiver);
898+
899+
watcher_rx
900+
.watch_with_parent(Path::new("/dev/null"), use_polling)
901+
.unwrap();
902+
903+
// A native backend may open every registered path in blocking mode.
904+
// PollWatcher must not read siblings by registering the directory.
905+
assert_eq!(*watched.lock().unwrap(), [PathBuf::from(expected)]);
906+
}
842907

843908
#[test]
844909
fn duplicate_rename_event_preserves_reader_position() {

‎src/uu/tail/src/paths.rs‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ impl MetadataExtTail for Metadata {
193193
fn file_id_eq(&self, #[cfg(unix)] other: &Metadata, #[cfg(not(unix))] _: &Metadata) -> bool {
194194
#[cfg(unix)]
195195
{
196-
self.ino().eq(&other.ino())
196+
self.dev() == other.dev() && self.ino() == other.ino()
197197
}
198198
#[cfg(windows)]
199199
{
@@ -252,3 +252,28 @@ pub fn stdin_is_bad_fd() -> bool {
252252
pub fn stdin_is_bad_fd() -> bool {
253253
false
254254
}
255+
256+
#[cfg(all(test, unix))]
257+
mod tests {
258+
use super::*;
259+
260+
#[test]
261+
fn file_identity_matches_open_descriptor() {
262+
let file = File::open("/dev/null").unwrap();
263+
let opened = file.metadata().unwrap();
264+
assert!(opened.file_id_eq(&std::fs::metadata("/dev/null").unwrap()));
265+
assert!(!opened.file_id_eq(&std::fs::metadata("/dev/zero").unwrap()));
266+
}
267+
268+
#[cfg(target_os = "linux")]
269+
#[test]
270+
fn file_identity_includes_device() {
271+
// These filesystem roots have the same inode number on Linux.
272+
let proc = std::fs::metadata("/proc").unwrap();
273+
let pts = std::fs::metadata("/dev/pts").unwrap();
274+
assert_eq!(proc.ino(), pts.ino());
275+
assert_ne!(proc.dev(), pts.dev());
276+
assert!(proc.file_id_eq(&std::fs::metadata("/proc").unwrap()));
277+
assert!(!proc.file_id_eq(&pts));
278+
}
279+
}

‎src/uu/tail/src/tail.rs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
// spell-checker:ignore (names)
1313
// spell-checker:ignore (shell/tools)
1414
// spell-checker:ignore (misc)
15+
// spell-checker:ignore nonblocking
1516

1617
pub mod args;
1718
pub mod chunks;
@@ -200,6 +201,25 @@ fn tail_file(
200201
// Dropping this reader loses nothing: unbounded_tail reads to EOF or not at all.
201202
unbounded_tail(&mut BufReader::new((&file).take(remaining)), settings)?;
202203
}
204+
#[cfg(unix)]
205+
if settings.follow.is_some() && !input.is_stdin() {
206+
use std::os::unix::fs::FileTypeExt;
207+
208+
if st.file_type().is_char_device()
209+
&& !matches!(
210+
(FileInformation::from_file(&file), FileInformation::from_file(&stdin())),
211+
(Ok(file), Ok(stdin)) if file == stdin
212+
)
213+
{
214+
use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
215+
216+
// Another reader can consume data after our readiness
217+
// check. Keep stdin's flags, including named aliases:
218+
// opening /dev/fd/0 can duplicate stdin on BSD.
219+
let flags = fcntl_getfl(&file).map_err(io::Error::from)?;
220+
fcntl_setfl(&file, flags | OFlags::NONBLOCK).map_err(io::Error::from)?;
221+
}
222+
}
203223
let reader = BufReader::new(file);
204224
if input.is_tailable() {
205225
observer.add_path(path, input.display_name.as_str(), Some(reader), true)?;

0 commit comments

Comments
 (0)