1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
// * This file is part of the uutils coreutils package.
// *
// * (c) Morten Olsen Lysgaard <morten@lysgaard.no>
// * (c) Alexander Batischev <eual.jp@gmail.com>
// * (c) Thomas Queiroz <thomasqueirozb@gmail.com>
// *
// * For the full copyright and license information, please view the LICENSE
// * file that was distributed with this source code.
// spell-checker:ignore (ToDO) seekable seek'd tail'ing ringbuffer ringbuf unwatch Uncategorized filehandle Signum
// spell-checker:ignore (libs) kqueue
// spell-checker:ignore (acronyms)
// spell-checker:ignore (env/flags)
// spell-checker:ignore (jargon) tailable untailable stdlib
// spell-checker:ignore (names)
// spell-checker:ignore (shell/tools)
// spell-checker:ignore (misc)
pub mod args;
pub mod chunks;
mod follow;
mod parse;
mod paths;
mod platform;
pub mod text;
pub use args::uu_app;
use args::{parse_args, FilterMode, Settings, Signum};
use chunks::ReverseChunks;
use follow::Observer;
use paths::{FileExtTail, HeaderPrinter, Input, InputKind, MetadataExtTail};
use same_file::Handle;
use std::cmp::Ordering;
use std::fs::File;
use std::io::{self, stdin, stdout, BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use uucore::display::Quotable;
use uucore::error::{get_exit_code, set_exit_code, FromIo, UError, UResult, USimpleError};
use uucore::{show, show_error};
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let settings = parse_args(args)?;
settings.check_warnings();
match settings.verify() {
args::VerificationResult::CannotFollowStdinByName => {
return Err(USimpleError::new(
1,
format!("cannot follow {} by name", text::DASH.quote()),
))
}
// Exit early if we do not output anything. Note, that this may break a pipe
// when tail is on the receiving side.
args::VerificationResult::NoOutput => return Ok(()),
args::VerificationResult::Ok => {}
}
uu_tail(&settings)
}
fn uu_tail(settings: &Settings) -> UResult<()> {
let mut printer = HeaderPrinter::new(settings.verbose, true);
let mut observer = Observer::from(settings);
observer.start(settings)?;
// Do an initial tail print of each path's content.
// Add `path` and `reader` to `files` map if `--follow` is selected.
for input in &settings.inputs.clone() {
match input.kind() {
InputKind::File(path) if cfg!(not(unix)) || path != &PathBuf::from(text::DEV_STDIN) => {
tail_file(settings, &mut printer, input, path, &mut observer, 0)?;
}
// File points to /dev/stdin here
InputKind::File(_) | InputKind::Stdin => {
tail_stdin(settings, &mut printer, input, &mut observer)?;
}
}
}
if settings.follow.is_some() {
/*
POSIX specification regarding tail -f
If the input file is a regular file or if the file operand specifies a FIFO, do not
terminate after the last line of the input file has been copied, but read and copy
further bytes from the input file when they become available. If no file operand is
specified and standard input is a pipe or FIFO, the -f option shall be ignored. If
the input file is not a FIFO, pipe, or regular file, it is unspecified whether or
not the -f option shall be ignored.
*/
if !settings.has_only_stdin() {
follow::follow(observer, settings)?;
}
}
if get_exit_code() > 0 && paths::stdin_is_bad_fd() {
show_error!("-: {}", text::BAD_FD);
}
Ok(())
}
fn tail_file(
settings: &Settings,
header_printer: &mut HeaderPrinter,
input: &Input,
path: &Path,
observer: &mut Observer,
offset: u64,
) -> UResult<()> {
if !path.exists() {
set_exit_code(1);
show_error!(
"cannot open '{}' for reading: {}",
input.display_name,
text::NO_SUCH_FILE
);
observer.add_bad_path(path, input.display_name.as_str(), false)?;
} else if path.is_dir() {
set_exit_code(1);
header_printer.print_input(input);
let err_msg = "Is a directory".to_string();
show_error!("error reading '{}': {}", input.display_name, err_msg);
if settings.follow.is_some() {
let msg = if settings.retry {
""
} else {
"; giving up on this name"
};
show_error!(
"{}: cannot follow end of this type of file{}",
input.display_name,
msg
);
}
if !(observer.follow_name_retry()) {
// skip directory if not retry
return Ok(());
}
observer.add_bad_path(path, input.display_name.as_str(), false)?;
} else if input.is_tailable() {
let metadata = path.metadata().ok();
match File::open(path) {
Ok(mut file) => {
header_printer.print_input(input);
let mut reader;
if !settings.presume_input_pipe
&& file.is_seekable(if input.is_stdin() { offset } else { 0 })
&& metadata.as_ref().unwrap().get_block_size() > 0
{
bounded_tail(&mut file, settings);
reader = BufReader::new(file);
} else {
reader = BufReader::new(file);
unbounded_tail(&mut reader, settings)?;
}
observer.add_path(
path,
input.display_name.as_str(),
Some(Box::new(reader)),
true,
)?;
}
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
observer.add_bad_path(path, input.display_name.as_str(), false)?;
show!(e.map_err_context(|| {
format!("cannot open '{}' for reading", input.display_name)
}));
}
Err(e) => {
observer.add_bad_path(path, input.display_name.as_str(), false)?;
return Err(e.map_err_context(|| {
format!("cannot open '{}' for reading", input.display_name)
}));
}
}
} else {
observer.add_bad_path(path, input.display_name.as_str(), false)?;
}
Ok(())
}
fn tail_stdin(
settings: &Settings,
header_printer: &mut HeaderPrinter,
input: &Input,
observer: &mut Observer,
) -> UResult<()> {
match input.resolve() {
// fifo
Some(path) => {
let mut stdin_offset = 0;
if cfg!(unix) {
// Save the current seek position/offset of a stdin redirected file.
// This is needed to pass "gnu/tests/tail-2/start-middle.sh"
if let Ok(mut stdin_handle) = Handle::stdin() {
if let Ok(offset) = stdin_handle.as_file_mut().stream_position() {
stdin_offset = offset;
}
}
}
tail_file(
settings,
header_printer,
input,
&path,
observer,
stdin_offset,
)?;
}
// pipe
None => {
header_printer.print_input(input);
if paths::stdin_is_bad_fd() {
set_exit_code(1);
show_error!(
"cannot fstat {}: {}",
text::STDIN_HEADER.quote(),
text::BAD_FD
);
if settings.follow.is_some() {
show_error!(
"error reading {}: {}",
text::STDIN_HEADER.quote(),
text::BAD_FD
);
}
} else {
let mut reader = BufReader::new(stdin());
unbounded_tail(&mut reader, settings)?;
observer.add_stdin(input.display_name.as_str(), Some(Box::new(reader)), true)?;
}
}
};
Ok(())
}
/// Find the index after the given number of instances of a given byte.
///
/// This function reads through a given reader until `num_delimiters`
/// instances of `delimiter` have been seen, returning the index of
/// the byte immediately following that delimiter. If there are fewer
/// than `num_delimiters` instances of `delimiter`, this returns the
/// total number of bytes read from the `reader` until EOF.
///
/// # Errors
///
/// This function returns an error if there is an error during reading
/// from `reader`.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust,ignore
/// use std::io::Cursor;
///
/// let mut reader = Cursor::new("a\nb\nc\nd\ne\n");
/// let i = forwards_thru_file(&mut reader, 2, b'\n').unwrap();
/// assert_eq!(i, 4);
/// ```
///
/// If `num_delimiters` is zero, then this function always returns
/// zero:
///
/// ```rust,ignore
/// use std::io::Cursor;
///
/// let mut reader = Cursor::new("a\n");
/// let i = forwards_thru_file(&mut reader, 0, b'\n').unwrap();
/// assert_eq!(i, 0);
/// ```
///
/// If there are fewer than `num_delimiters` instances of `delimiter`
/// in the reader, then this function returns the total number of
/// bytes read:
///
/// ```rust,ignore
/// use std::io::Cursor;
///
/// let mut reader = Cursor::new("a\n");
/// let i = forwards_thru_file(&mut reader, 2, b'\n').unwrap();
/// assert_eq!(i, 2);
/// ```
fn forwards_thru_file<R>(
reader: &mut R,
num_delimiters: u64,
delimiter: u8,
) -> std::io::Result<usize>
where
R: Read,
{
let mut reader = BufReader::new(reader);
let mut buf = vec![];
let mut total = 0;
for _ in 0..num_delimiters {
match reader.read_until(delimiter, &mut buf) {
Ok(0) => {
return Ok(total);
}
Ok(n) => {
total += n;
buf.clear();
continue;
}
Err(e) => {
return Err(e);
}
}
}
Ok(total)
}
/// Iterate over bytes in the file, in reverse, until we find the
/// `num_delimiters` instance of `delimiter`. The `file` is left seek'd to the
/// position just after that delimiter.
fn backwards_thru_file(file: &mut File, num_delimiters: u64, delimiter: u8) {
// This variable counts the number of delimiters found in the file
// so far (reading from the end of the file toward the beginning).
let mut counter = 0;
for (block_idx, slice) in ReverseChunks::new(file).enumerate() {
// Iterate over each byte in the slice in reverse order.
let mut iter = slice.iter().enumerate().rev();
// Ignore a trailing newline in the last block, if there is one.
if block_idx == 0 {
if let Some(c) = slice.last() {
if *c == delimiter {
iter.next();
}
}
}
// For each byte, increment the count of the number of
// delimiters found. If we have found more than the specified
// number of delimiters, terminate the search and seek to the
// appropriate location in the file.
for (i, ch) in iter {
if *ch == delimiter {
counter += 1;
if counter >= num_delimiters {
// After each iteration of the outer loop, the
// cursor in the file is at the *beginning* of the
// block, so seeking forward by `i + 1` bytes puts
// us right after the found delimiter.
file.seek(SeekFrom::Current((i + 1) as i64)).unwrap();
return;
}
}
}
}
}
/// When tail'ing a file, we do not need to read the whole file from start to
/// finish just to find the last n lines or bytes. Instead, we can seek to the
/// end of the file, and then read the file "backwards" in blocks of size
/// `BLOCK_SIZE` until we find the location of the first line/byte. This ends up
/// being a nice performance win for very large files.
fn bounded_tail(file: &mut File, settings: &Settings) {
debug_assert!(!settings.presume_input_pipe);
// Find the position in the file to start printing from.
match &settings.mode {
FilterMode::Lines(Signum::Negative(count), delimiter) => {
backwards_thru_file(file, *count, *delimiter);
}
FilterMode::Lines(Signum::Positive(count), delimiter) if count > &1 => {
let i = forwards_thru_file(file, *count - 1, *delimiter).unwrap();
file.seek(SeekFrom::Start(i as u64)).unwrap();
}
FilterMode::Lines(Signum::MinusZero, _) => {
return;
}
FilterMode::Bytes(Signum::Negative(count)) => {
let len = file.seek(SeekFrom::End(0)).unwrap();
file.seek(SeekFrom::End(-((*count).min(len) as i64)))
.unwrap();
}
FilterMode::Bytes(Signum::Positive(count)) if count > &1 => {
// GNU `tail` seems to index bytes and lines starting at 1, not
// at 0. It seems to treat `+0` and `+1` as the same thing.
file.seek(SeekFrom::Start(*count - 1)).unwrap();
}
FilterMode::Bytes(Signum::MinusZero) => {
return;
}
_ => {}
}
// Print the target section of the file.
let stdout = stdout();
let mut stdout = stdout.lock();
std::io::copy(file, &mut stdout).unwrap();
}
fn unbounded_tail<T: Read>(reader: &mut BufReader<T>, settings: &Settings) -> UResult<()> {
let stdout = stdout();
let mut writer = BufWriter::new(stdout.lock());
match &settings.mode {
FilterMode::Lines(Signum::Negative(count), sep) => {
let mut chunks = chunks::LinesChunkBuffer::new(*sep, *count);
chunks.fill(reader)?;
chunks.print(&mut writer)?;
}
FilterMode::Lines(Signum::PlusZero | Signum::Positive(1), _) => {
io::copy(reader, &mut writer)?;
}
FilterMode::Lines(Signum::Positive(count), sep) => {
let mut num_skip = *count - 1;
let mut chunk = chunks::LinesChunk::new(*sep);
while chunk.fill(reader)?.is_some() {
let lines = chunk.get_lines() as u64;
if lines < num_skip {
num_skip -= lines;
} else {
break;
}
}
if chunk.has_data() {
chunk.print_lines(&mut writer, num_skip as usize)?;
io::copy(reader, &mut writer)?;
}
}
FilterMode::Bytes(Signum::Negative(count)) => {
let mut chunks = chunks::BytesChunkBuffer::new(*count);
chunks.fill(reader)?;
chunks.print(&mut writer)?;
}
FilterMode::Bytes(Signum::PlusZero | Signum::Positive(1)) => {
io::copy(reader, &mut writer)?;
}
FilterMode::Bytes(Signum::Positive(count)) => {
let mut num_skip = *count - 1;
let mut chunk = chunks::BytesChunk::new();
loop {
if let Some(bytes) = chunk.fill(reader)? {
let bytes: u64 = bytes as u64;
match bytes.cmp(&num_skip) {
Ordering::Less => num_skip -= bytes,
Ordering::Equal => {
break;
}
Ordering::Greater => {
writer.write_all(chunk.get_buffer_with(num_skip as usize))?;
break;
}
}
} else {
return Ok(());
}
}
io::copy(reader, &mut writer)?;
}
_ => {}
}
Ok(())
}
#[cfg(test)]
mod tests {
use crate::forwards_thru_file;
use std::io::Cursor;
#[test]
fn test_forwards_thru_file_zero() {
let mut reader = Cursor::new("a\n");
let i = forwards_thru_file(&mut reader, 0, b'\n').unwrap();
assert_eq!(i, 0);
}
#[test]
fn test_forwards_thru_file_basic() {
// 01 23 45 67 89
let mut reader = Cursor::new("a\nb\nc\nd\ne\n");
let i = forwards_thru_file(&mut reader, 2, b'\n').unwrap();
assert_eq!(i, 4);
}
#[test]
fn test_forwards_thru_file_past_end() {
let mut reader = Cursor::new("x\n");
let i = forwards_thru_file(&mut reader, 2, b'\n').unwrap();
assert_eq!(i, 2);
}
}