Skip to content

Commit 6f20759

Browse files
committed
tail: fix following files redirected to stdin
Track and watch redirected stdin files across supported platforms, preserving the descriptor position and reader during polling updates. Enable regression tests for redirected file following and directory errors.
1 parent 6b35c0b commit 6f20759

6 files changed

Lines changed: 211 additions & 112 deletions

File tree

‎src/uu/tail/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ uucore = { workspace = true, features = ["pipes"] }
4040

4141
[target.'cfg(windows)'.dependencies]
4242
windows-sys = { workspace = true, features = [
43+
"Win32_Storage_FileSystem",
4344
"Win32_System_Threading",
4445
"Win32_Foundation",
4546
] }

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ pub use watch::{Observer, follow};
1717
mod wasi_stubs {
1818
use crate::args::Settings;
1919
use std::io::BufRead;
20-
use std::path::Path;
20+
use std::path::{Path, PathBuf};
2121
use uucore::error::{UResult, USimpleError};
2222

2323
pub struct Observer {
@@ -29,6 +29,15 @@ mod wasi_stubs {
2929
Self { use_polling: false }
3030
}
3131

32+
pub fn stdin_is_tailable(&self) -> bool {
33+
false
34+
}
35+
36+
#[allow(clippy::unnecessary_wraps)]
37+
pub fn set_stdin_key<P: Into<PathBuf>>(&mut self, _path: P) -> UResult<()> {
38+
Ok(())
39+
}
40+
3241
#[allow(clippy::unnecessary_wraps)]
3342
pub fn start(&mut self, _settings: &Settings) -> UResult<()> {
3443
Ok(())

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

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ pub struct Observer {
100100
pub files: FileHandling,
101101

102102
pub pid: platform::Pid,
103+
/// The file key when stdin resolves to a tailable file that we should follow.
104+
stdin_key: Option<PathBuf>,
103105
}
104106

105107
impl Observer {
@@ -124,9 +126,24 @@ impl Observer {
124126
orphans: Vec::new(),
125127
files,
126128
pid,
129+
stdin_key: None,
127130
}
128131
}
129132

133+
pub fn stdin_is_tailable(&self) -> bool {
134+
self.stdin_key.is_some()
135+
}
136+
137+
pub fn set_stdin_key<P: Into<PathBuf>>(&mut self, path: P) -> UResult<()> {
138+
let path = path.into();
139+
if let Some(watcher_rx) = &mut self.watcher_rx {
140+
// Register the resolved stdin file so follow can rely on normal change events.
141+
watcher_rx.watch_with_parent(&path)?;
142+
}
143+
self.stdin_key = Some(path);
144+
Ok(())
145+
}
146+
130147
pub fn from(settings: &Settings) -> Self {
131148
Self::new(
132149
settings.retry,
@@ -145,11 +162,12 @@ impl Observer {
145162
update_last: bool,
146163
) -> UResult<()> {
147164
if self.follow.is_some() {
148-
let path = if path.is_relative() {
165+
let path = if path.is_relative() && !path.is_stdin() {
149166
std::env::current_dir()?.join(path)
150167
} else {
151168
path.to_owned()
152169
};
170+
153171
let metadata = path.metadata().ok();
154172
self.files.insert(
155173
&path,
@@ -342,8 +360,9 @@ impl Observer {
342360
translate!("tail-status-has-appeared-following-new-file", "file" => display_name.quote())
343361
);
344362
self.files.update_reader(event_path)?;
345-
} else if event.kind == EventKind::Modify(ModifyKind::Name(RenameMode::To))
346-
|| (self.use_polling && !old_md.file_id_eq(&new_md)) {
363+
} else if self.follow_name()
364+
&& (event.kind == EventKind::Modify(ModifyKind::Name(RenameMode::To))
365+
|| (self.use_polling && !old_md.file_id_eq(&new_md))) {
347366
show_error!(
348367
"{}",
349368
translate!("tail-status-has-been-replaced-following-new-file", "file" => display_name.quote())

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

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ use std::fs::{File, Metadata};
1111
use std::io::{Seek, SeekFrom};
1212
#[cfg(unix)]
1313
use std::os::unix::fs::{FileTypeExt, MetadataExt};
14-
use std::path::{Path, PathBuf};
14+
#[cfg(not(target_os = "wasi"))]
15+
use std::path::Path;
16+
use std::path::PathBuf;
1517
#[cfg(not(target_os = "wasi"))]
1618
use uucore::error::UResult;
1719
use uucore::quoting_style::locale_aware_shell_escape;
@@ -81,13 +83,15 @@ impl Input {
8183
path.canonicalize().ok()
8284
}
8385
InputKind::File(_) | InputKind::Stdin => {
84-
// on macOS, /dev/fd isn't backed by /proc and canonicalize()
85-
// on dev/fd/0 (or /dev/stdin) will fail (NotFound),
86-
// so we treat stdin as a pipe here
87-
// https://github.com/rust-lang/rust/issues/95239
8886
#[cfg(target_vendor = "apple")]
8987
{
90-
None
88+
use std::os::unix::ffi::OsStrExt;
89+
90+
// /dev/fd/0 cannot be canonicalized on macOS; query the descriptor instead.
91+
let path = rustix::fs::getpath(std::io::stdin()).ok()?;
92+
Path::new(OsStr::from_bytes(path.to_bytes()))
93+
.canonicalize()
94+
.ok()
9195
}
9296
#[cfg(not(target_vendor = "apple"))]
9397
{
@@ -96,13 +100,6 @@ impl Input {
96100
}
97101
}
98102
}
99-
100-
pub fn is_tailable(&self) -> bool {
101-
match &self.kind {
102-
InputKind::File(path) => path_is_tailable(path),
103-
InputKind::Stdin => self.resolve().is_some_and(|path| path_is_tailable(&path)),
104-
}
105-
}
106103
}
107104

108105
impl Default for Input {
@@ -234,6 +231,7 @@ impl PathExtTail for Path {
234231
}
235232
}
236233

234+
#[cfg(not(target_os = "wasi"))]
237235
pub fn path_is_tailable(path: &Path) -> bool {
238236
path.is_file() || path.exists() && path.metadata().is_ok_and(|meta| meta.is_tailable())
239237
}

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

Lines changed: 109 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use args::{FilterMode, Settings, Signum, parse_args};
2626
use chunks::ReverseChunks;
2727
use follow::Observer;
2828
use memchr::{memchr_iter, memrchr_iter};
29-
use paths::{FileExtTail, HeaderPrinter, Input, InputKind};
29+
use paths::{FileExtTail, HeaderPrinter, Input, InputKind, MetadataExtTail};
3030
use std::cmp::Ordering;
3131
use std::fs::File;
3232
use std::io::{self, BufReader, BufWriter, ErrorKind, Read, Seek, SeekFrom, Write, stdin, stdout};
@@ -102,7 +102,10 @@ fn uu_tail(settings: &Settings) -> UResult<()> {
102102
the input file is not a FIFO, pipe, or regular file, it is unspecified whether or
103103
not the -f option shall be ignored.
104104
*/
105-
if !settings.has_only_stdin() || settings.pid.is_some_and(|pid| pid != 0) {
105+
if !settings.has_only_stdin()
106+
|| settings.pid.is_some_and(|pid| pid != 0)
107+
|| observer.stdin_is_tailable()
108+
{
106109
follow::follow(observer, settings)?;
107110
}
108111
}
@@ -184,7 +187,8 @@ fn tail_file(
184187
reader = BufReader::new(file);
185188
unbounded_tail(&mut reader, settings)?;
186189
}
187-
if input.is_tailable() {
190+
// Use the opened file's metadata rather than resolving stdin again.
191+
if st.is_tailable() {
188192
observer.add_path(
189193
path,
190194
input.display_name.as_str(),
@@ -252,22 +256,6 @@ fn tail_stdin(
252256
input: &Input,
253257
observer: &mut Observer,
254258
) -> UResult<()> {
255-
// on macOS, resolve() will always return None for stdin,
256-
// we need to detect if stdin is a directory ourselves.
257-
// fstat-ing certain descriptors under /dev/fd fails with
258-
// bad file descriptor or might not catch directory cases
259-
// e.g. see the differences between running ls -l /dev/stdin /dev/fd/0
260-
// on macOS and Linux.
261-
#[cfg(target_vendor = "apple")]
262-
if uucore::fs::is_stdin_directory(&stdin()) {
263-
set_exit_code(1);
264-
show_error!(
265-
"{}",
266-
translate!("tail-error-cannot-open-no-such-file", "file" => input.display_name, "error" => translate!("tail-no-such-file-or-directory"))
267-
);
268-
return Ok(());
269-
}
270-
271259
// Check if stdin was closed before Rust reopened it as /dev/null
272260
if paths::stdin_is_bad_fd() {
273261
set_exit_code(1);
@@ -279,40 +267,80 @@ fn tail_stdin(
279267
return Ok(());
280268
}
281269

282-
if let Some(path) = input.resolve() {
283-
#[cfg(not(unix))]
284-
let stdin_offset = 0;
285-
// Save the current seek position/offset of a stdin redirected file.
286-
// This is needed to pass "gnu/tests/tail-2/start-middle.sh"
270+
let resolved_stdin = input.resolve().or_else(resolve_stdin_path);
271+
272+
if let Some(ref path) = resolved_stdin {
287273
#[cfg(unix)]
288-
let stdin_offset = rustix::fs::tell(stdin()).unwrap_or(0); // fifo
289-
tail_file(
290-
settings,
291-
header_printer,
292-
input,
293-
&path,
294-
observer,
295-
stdin_offset,
296-
)?;
297-
} else {
298-
// pipe
299-
header_printer.print_input(input);
300-
if paths::stdin_is_bad_fd() {
301-
set_exit_code(1);
274+
let (stdin_offset, stdin_is_seekable_file) = (
275+
rustix::fs::tell(stdin()).unwrap_or(0),
276+
rustix::fs::fstat(stdin()).ok().map(|stat| {
277+
rustix::fs::FileType::from_raw_mode(stat.st_mode)
278+
== rustix::fs::FileType::RegularFile
279+
}),
280+
);
281+
#[cfg(windows)]
282+
let (stdin_offset, stdin_is_seekable_file) = {
283+
use std::os::windows::io::AsHandle;
284+
285+
stdin()
286+
.as_handle()
287+
.try_clone_to_owned()
288+
.map_or((0, None), |handle| {
289+
let mut file = File::from(handle);
290+
(
291+
file.stream_position().unwrap_or(0),
292+
file.metadata().ok().map(|meta| meta.is_file()),
293+
)
294+
})
295+
};
296+
#[cfg(not(any(unix, windows)))]
297+
let (stdin_offset, stdin_is_seekable_file) = (0, None);
298+
299+
// Only fall back to the path if stdin's metadata could not be obtained.
300+
let stdin_is_seekable_file = stdin_is_seekable_file
301+
.unwrap_or_else(|| path.metadata().is_ok_and(|meta| meta.is_file()));
302+
303+
if stdin_is_seekable_file || path.is_dir() {
304+
tail_file(
305+
settings,
306+
header_printer,
307+
input,
308+
path,
309+
observer,
310+
stdin_offset,
311+
)?;
312+
313+
if stdin_is_seekable_file {
314+
observer.set_stdin_key(path.clone())?;
315+
}
316+
return Ok(());
317+
}
318+
}
319+
320+
header_printer.print_input(input);
321+
if paths::stdin_is_bad_fd() {
322+
set_exit_code(1);
323+
show_error!(
324+
"{}",
325+
translate!(
326+
"tail-error-cannot-fstat",
327+
"file" => translate!("tail-stdin-header"),
328+
"error" => translate!("tail-bad-fd")
329+
)
330+
);
331+
if settings.follow.is_some() {
302332
show_error!(
303333
"{}",
304-
translate!("tail-error-cannot-fstat", "file" => translate!("tail-stdin-header"), "error" => translate!("tail-bad-fd"))
334+
translate!(
335+
"tail-error-reading-file",
336+
"file" => translate!("tail-stdin-header"),
337+
"error" => translate!("tail-bad-fd")
338+
)
305339
);
306-
if settings.follow.is_some() {
307-
show_error!(
308-
"{}",
309-
translate!("tail-error-reading-file", "file" => translate!("tail-stdin-header"), "error" => translate!("tail-bad-fd"))
310-
);
311-
}
312-
} else {
313-
let mut reader = BufReader::new(stdin());
314-
unbounded_tail(&mut reader, settings)?;
315340
}
341+
} else {
342+
let mut reader = BufReader::new(stdin());
343+
unbounded_tail(&mut reader, settings)?;
316344
}
317345

318346
Ok(())
@@ -601,6 +629,39 @@ fn print_target_section<
601629
Ok(())
602630
}
603631

632+
#[cfg(windows)]
633+
fn resolve_stdin_path() -> Option<PathBuf> {
634+
use std::os::windows::io::AsRawHandle;
635+
use windows_sys::Win32::Foundation::MAX_PATH;
636+
use windows_sys::Win32::Storage::FileSystem::{FILE_NAME_OPENED, GetFinalPathNameByHandleW};
637+
638+
let handle = stdin().lock().as_raw_handle();
639+
if handle.is_null() {
640+
return None;
641+
}
642+
643+
let mut buffer = [0u16; MAX_PATH as usize];
644+
let len = unsafe {
645+
GetFinalPathNameByHandleW(
646+
handle,
647+
buffer.as_mut_ptr(),
648+
buffer.len() as u32,
649+
FILE_NAME_OPENED,
650+
)
651+
} as usize;
652+
653+
if len == 0 || len >= buffer.len() {
654+
return None;
655+
}
656+
657+
String::from_utf16(&buffer[..len]).ok().map(PathBuf::from)
658+
}
659+
660+
#[cfg(not(windows))]
661+
fn resolve_stdin_path() -> Option<PathBuf> {
662+
None
663+
}
664+
604665
#[cfg(test)]
605666
mod tests {
606667

0 commit comments

Comments
 (0)