pr: ensure the page header line is of the required format
[coreutils.git] / src / tail.c
blob02c4a1a1dc6005416892084c9cd9eb79c70f22f9
1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989-1991, 1995-2006, 2008-2010 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Can display any amount of data, unlike the Unix version, which uses
18 a fixed size buffer and therefore can only deliver a limited number
19 of lines.
21 Original version by Paul Rubin <phr@ocf.berkeley.edu>.
22 Extensions by David MacKenzie <djm@gnu.ai.mit.edu>.
23 tail -f for multiple files by Ian Lance Taylor <ian@airs.com>.
24 inotify back-end by Giuseppe Scrivano <gscrivano@gnu.org>. */
26 #include <config.h>
28 #include <stdio.h>
29 #include <assert.h>
30 #include <getopt.h>
31 #include <sys/types.h>
32 #include <signal.h>
34 #include "system.h"
35 #include "argmatch.h"
36 #include "c-strtod.h"
37 #include "error.h"
38 #include "fcntl--.h"
39 #include "isapipe.h"
40 #include "posixver.h"
41 #include "quote.h"
42 #include "safe-read.h"
43 #include "stat-time.h"
44 #include "xfreopen.h"
45 #include "xnanosleep.h"
46 #include "xstrtol.h"
47 #include "xstrtod.h"
49 #if HAVE_INOTIFY
50 # include "hash.h"
51 # include <sys/inotify.h>
52 /* `select' is used by tail_forever_inotify. */
53 # include <sys/select.h>
55 /* inotify needs to know if a file is local. */
56 # include "fs.h"
57 # if HAVE_SYS_STATFS_H
58 # include <sys/statfs.h>
59 # endif
60 #endif
62 /* The official name of this program (e.g., no `g' prefix). */
63 #define PROGRAM_NAME "tail"
65 #define AUTHORS \
66 proper_name ("Paul Rubin"), \
67 proper_name ("David MacKenzie"), \
68 proper_name ("Ian Lance Taylor"), \
69 proper_name ("Jim Meyering")
71 /* Number of items to tail. */
72 #define DEFAULT_N_LINES 10
74 /* Special values for dump_remainder's N_BYTES parameter. */
75 #define COPY_TO_EOF UINTMAX_MAX
76 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
78 /* FIXME: make Follow_name the default? */
79 #define DEFAULT_FOLLOW_MODE Follow_descriptor
81 enum Follow_mode
83 /* Follow the name of each file: if the file is renamed, try to reopen
84 that name and track the end of the new file if/when it's recreated.
85 This is useful for tracking logs that are occasionally rotated. */
86 Follow_name = 1,
88 /* Follow each descriptor obtained upon opening a file.
89 That means we'll continue to follow the end of a file even after
90 it has been renamed or unlinked. */
91 Follow_descriptor = 2
94 /* The types of files for which tail works. */
95 #define IS_TAILABLE_FILE_TYPE(Mode) \
96 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
98 static char const *const follow_mode_string[] =
100 "descriptor", "name", NULL
103 static enum Follow_mode const follow_mode_map[] =
105 Follow_descriptor, Follow_name,
108 struct File_spec
110 /* The actual file name, or "-" for stdin. */
111 char *name;
113 /* Attributes of the file the last time we checked. */
114 off_t size;
115 struct timespec mtime;
116 dev_t dev;
117 ino_t ino;
118 mode_t mode;
120 /* The specified name initially referred to a directory or some other
121 type for which tail isn't meaningful. Unlike for a permission problem
122 (tailable, below) once this is set, the name is not checked ever again. */
123 bool ignore;
125 /* See the description of fremote. */
126 bool remote;
128 /* A file is tailable if it exists, is readable, and is of type
129 IS_TAILABLE_FILE_TYPE. */
130 bool tailable;
132 /* File descriptor on which the file is open; -1 if it's not open. */
133 int fd;
135 /* The value of errno seen last time we checked this file. */
136 int errnum;
138 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
139 int blocking;
141 #if HAVE_INOTIFY
142 /* The watch descriptor used by inotify. */
143 int wd;
145 /* The parent directory watch descriptor. It is used only
146 * when Follow_name is used. */
147 int parent_wd;
149 /* Offset in NAME of the basename part. */
150 size_t basename_start;
151 #endif
153 /* See description of DEFAULT_MAX_N_... below. */
154 uintmax_t n_unchanged_stats;
157 #if HAVE_INOTIFY
158 /* The events mask used with inotify on files. This mask is not used on
159 directories. */
160 const uint32_t inotify_wd_mask = (IN_MODIFY | IN_ATTRIB | IN_DELETE_SELF
161 | IN_MOVE_SELF);
162 #endif
164 /* Keep trying to open a file even if it is inaccessible when tail starts
165 or if it becomes inaccessible later -- useful only with -f. */
166 static bool reopen_inaccessible_files;
168 /* If true, interpret the numeric argument as the number of lines.
169 Otherwise, interpret it as the number of bytes. */
170 static bool count_lines;
172 /* Whether we follow the name of each file or the file descriptor
173 that is initially associated with each name. */
174 static enum Follow_mode follow_mode = Follow_descriptor;
176 /* If true, read from the ends of all specified files until killed. */
177 static bool forever;
179 /* If true, count from start of file instead of end. */
180 static bool from_start;
182 /* If true, print filename headers. */
183 static bool print_headers;
185 /* When to print the filename banners. */
186 enum header_mode
188 multiple_files, always, never
191 /* When tailing a file by name, if there have been this many consecutive
192 iterations for which the file has not changed, then open/fstat
193 the file to determine if that file name is still associated with the
194 same device/inode-number pair as before. This option is meaningful only
195 when following by name. --max-unchanged-stats=N */
196 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
197 static uintmax_t max_n_unchanged_stats_between_opens =
198 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
200 /* The process ID of the process (presumably on the current host)
201 that is writing to all followed files. */
202 static pid_t pid;
204 /* True if we have ever read standard input. */
205 static bool have_read_stdin;
207 /* If nonzero, skip the is-regular-file test used to determine whether
208 to use the lseek optimization. Instead, use the more general (and
209 more expensive) code unconditionally. Intended solely for testing. */
210 static bool presume_input_pipe;
212 /* If nonzero then don't use inotify even if available. */
213 static bool disable_inotify;
215 /* For long options that have no equivalent short option, use a
216 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
217 enum
219 RETRY_OPTION = CHAR_MAX + 1,
220 MAX_UNCHANGED_STATS_OPTION,
221 PID_OPTION,
222 PRESUME_INPUT_PIPE_OPTION,
223 LONG_FOLLOW_OPTION,
224 DISABLE_INOTIFY_OPTION
227 static struct option const long_options[] =
229 {"bytes", required_argument, NULL, 'c'},
230 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
231 {"lines", required_argument, NULL, 'n'},
232 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
233 {"-disable-inotify", no_argument, NULL,
234 DISABLE_INOTIFY_OPTION}, /* do not document */
235 {"pid", required_argument, NULL, PID_OPTION},
236 {"-presume-input-pipe", no_argument, NULL,
237 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
238 {"quiet", no_argument, NULL, 'q'},
239 {"retry", no_argument, NULL, RETRY_OPTION},
240 {"silent", no_argument, NULL, 'q'},
241 {"sleep-interval", required_argument, NULL, 's'},
242 {"verbose", no_argument, NULL, 'v'},
243 {GETOPT_HELP_OPTION_DECL},
244 {GETOPT_VERSION_OPTION_DECL},
245 {NULL, 0, NULL, 0}
248 void
249 usage (int status)
251 if (status != EXIT_SUCCESS)
252 fprintf (stderr, _("Try `%s --help' for more information.\n"),
253 program_name);
254 else
256 printf (_("\
257 Usage: %s [OPTION]... [FILE]...\n\
259 program_name);
260 printf (_("\
261 Print the last %d lines of each FILE to standard output.\n\
262 With more than one FILE, precede each with a header giving the file name.\n\
263 With no FILE, or when FILE is -, read standard input.\n\
265 "), DEFAULT_N_LINES);
266 fputs (_("\
267 Mandatory arguments to long options are mandatory for short options too.\n\
268 "), stdout);
269 fputs (_("\
270 -c, --bytes=K output the last K bytes; alternatively, use -c +K\n\
271 to output bytes starting with the Kth of each file\n\
272 "), stdout);
273 fputs (_("\
274 -f, --follow[={name|descriptor}]\n\
275 output appended data as the file grows;\n\
276 -f, --follow, and --follow=descriptor are\n\
277 equivalent\n\
278 -F same as --follow=name --retry\n\
279 "), stdout);
280 printf (_("\
281 -n, --lines=K output the last K lines, instead of the last %d;\n\
282 or use -n +K to output lines starting with the Kth\n\
283 --max-unchanged-stats=N\n\
284 with --follow=name, reopen a FILE which has not\n\
285 changed size after N (default %d) iterations\n\
286 to see if it has been unlinked or renamed\n\
287 (this is the usual case of rotated log files)\n\
289 DEFAULT_N_LINES,
290 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
292 fputs (_("\
293 --pid=PID with -f, terminate after process ID, PID dies\n\
294 -q, --quiet, --silent never output headers giving file names\n\
295 --retry keep trying to open a file even when it is or\n\
296 becomes inaccessible; useful when following by\n\
297 name, i.e., with --follow=name\n\
298 "), stdout);
299 fputs (_("\
300 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
301 (default 1.0) between iterations\n\
302 -v, --verbose always output headers giving file names\n\
303 "), stdout);
304 fputs (HELP_OPTION_DESCRIPTION, stdout);
305 fputs (VERSION_OPTION_DESCRIPTION, stdout);
306 fputs (_("\
308 If the first character of K (the number of bytes or lines) is a `+',\n\
309 print beginning with the Kth item from the start of each file, otherwise,\n\
310 print the last K items in the file. K may have a multiplier suffix:\n\
311 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
312 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
314 "), stdout);
315 fputs (_("\
316 With --follow (-f), tail defaults to following the file descriptor, which\n\
317 means that even if a tail'ed file is renamed, tail will continue to track\n\
318 its end. This default behavior is not desirable when you really want to\n\
319 track the actual name of the file, not the file descriptor (e.g., log\n\
320 rotation). Use --follow=name in that case. That causes tail to track the\n\
321 named file in a way that accommodates renaming, removal and creation.\n\
322 "), stdout);
323 emit_ancillary_info ();
325 exit (status);
328 static bool
329 valid_file_spec (struct File_spec const *f)
331 /* Exactly one of the following subexpressions must be true. */
332 return ((f->fd == -1) ^ (f->errnum == 0));
335 static char const *
336 pretty_name (struct File_spec const *f)
338 return (STREQ (f->name, "-") ? _("standard input") : f->name);
341 static void
342 xwrite_stdout (char const *buffer, size_t n_bytes)
344 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
345 error (EXIT_FAILURE, errno, _("write error"));
348 /* Record a file F with descriptor FD, size SIZE, status ST, and
349 blocking status BLOCKING. */
351 static void
352 record_open_fd (struct File_spec *f, int fd,
353 off_t size, struct stat const *st,
354 int blocking)
356 f->fd = fd;
357 f->size = size;
358 f->mtime = get_stat_mtime (st);
359 f->dev = st->st_dev;
360 f->ino = st->st_ino;
361 f->mode = st->st_mode;
362 f->blocking = blocking;
363 f->n_unchanged_stats = 0;
364 f->ignore = false;
367 /* Close the file with descriptor FD and name FILENAME. */
369 static void
370 close_fd (int fd, const char *filename)
372 if (fd != -1 && fd != STDIN_FILENO && close (fd))
374 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
378 static void
379 write_header (const char *pretty_filename)
381 static bool first_file = true;
383 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
384 first_file = false;
387 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
388 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
389 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
390 Return the number of bytes read from the file. */
392 static uintmax_t
393 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
395 uintmax_t n_written;
396 uintmax_t n_remaining = n_bytes;
398 n_written = 0;
399 while (1)
401 char buffer[BUFSIZ];
402 size_t n = MIN (n_remaining, BUFSIZ);
403 size_t bytes_read = safe_read (fd, buffer, n);
404 if (bytes_read == SAFE_READ_ERROR)
406 if (errno != EAGAIN)
407 error (EXIT_FAILURE, errno, _("error reading %s"),
408 quote (pretty_filename));
409 break;
411 if (bytes_read == 0)
412 break;
413 xwrite_stdout (buffer, bytes_read);
414 n_written += bytes_read;
415 if (n_bytes != COPY_TO_EOF)
417 n_remaining -= bytes_read;
418 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
419 break;
423 return n_written;
426 /* Call lseek with the specified arguments, where file descriptor FD
427 corresponds to the file, FILENAME.
428 Give a diagnostic and exit nonzero if lseek fails.
429 Otherwise, return the resulting offset. */
431 static off_t
432 xlseek (int fd, off_t offset, int whence, char const *filename)
434 off_t new_offset = lseek (fd, offset, whence);
435 char buf[INT_BUFSIZE_BOUND (off_t)];
436 char *s;
438 if (0 <= new_offset)
439 return new_offset;
441 s = offtostr (offset, buf);
442 switch (whence)
444 case SEEK_SET:
445 error (0, errno, _("%s: cannot seek to offset %s"),
446 filename, s);
447 break;
448 case SEEK_CUR:
449 error (0, errno, _("%s: cannot seek to relative offset %s"),
450 filename, s);
451 break;
452 case SEEK_END:
453 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
454 filename, s);
455 break;
456 default:
457 abort ();
460 exit (EXIT_FAILURE);
463 /* Print the last N_LINES lines from the end of file FD.
464 Go backward through the file, reading `BUFSIZ' bytes at a time (except
465 probably the first), until we hit the start of the file or have
466 read NUMBER newlines.
467 START_POS is the starting position of the read pointer for the file
468 associated with FD (may be nonzero).
469 END_POS is the file offset of EOF (one larger than offset of last byte).
470 Return true if successful. */
472 static bool
473 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
474 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
476 char buffer[BUFSIZ];
477 size_t bytes_read;
478 off_t pos = end_pos;
480 if (n_lines == 0)
481 return true;
483 /* Set `bytes_read' to the size of the last, probably partial, buffer;
484 0 < `bytes_read' <= `BUFSIZ'. */
485 bytes_read = (pos - start_pos) % BUFSIZ;
486 if (bytes_read == 0)
487 bytes_read = BUFSIZ;
488 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
489 reads will be on block boundaries, which might increase efficiency. */
490 pos -= bytes_read;
491 xlseek (fd, pos, SEEK_SET, pretty_filename);
492 bytes_read = safe_read (fd, buffer, bytes_read);
493 if (bytes_read == SAFE_READ_ERROR)
495 error (0, errno, _("error reading %s"), quote (pretty_filename));
496 return false;
498 *read_pos = pos + bytes_read;
500 /* Count the incomplete line on files that don't end with a newline. */
501 if (bytes_read && buffer[bytes_read - 1] != '\n')
502 --n_lines;
506 /* Scan backward, counting the newlines in this bufferfull. */
508 size_t n = bytes_read;
509 while (n)
511 char const *nl;
512 nl = memrchr (buffer, '\n', n);
513 if (nl == NULL)
514 break;
515 n = nl - buffer;
516 if (n_lines-- == 0)
518 /* If this newline isn't the last character in the buffer,
519 output the part that is after it. */
520 if (n != bytes_read - 1)
521 xwrite_stdout (nl + 1, bytes_read - (n + 1));
522 *read_pos += dump_remainder (pretty_filename, fd,
523 end_pos - (pos + bytes_read));
524 return true;
528 /* Not enough newlines in that bufferfull. */
529 if (pos == start_pos)
531 /* Not enough lines in the file; print everything from
532 start_pos to the end. */
533 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
534 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
535 end_pos);
536 return true;
538 pos -= BUFSIZ;
539 xlseek (fd, pos, SEEK_SET, pretty_filename);
541 bytes_read = safe_read (fd, buffer, BUFSIZ);
542 if (bytes_read == SAFE_READ_ERROR)
544 error (0, errno, _("error reading %s"), quote (pretty_filename));
545 return false;
548 *read_pos = pos + bytes_read;
550 while (bytes_read > 0);
552 return true;
555 /* Print the last N_LINES lines from the end of the standard input,
556 open for reading as pipe FD.
557 Buffer the text as a linked list of LBUFFERs, adding them as needed.
558 Return true if successful. */
560 static bool
561 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
562 uintmax_t *read_pos)
564 struct linebuffer
566 char buffer[BUFSIZ];
567 size_t nbytes;
568 size_t nlines;
569 struct linebuffer *next;
571 typedef struct linebuffer LBUFFER;
572 LBUFFER *first, *last, *tmp;
573 size_t total_lines = 0; /* Total number of newlines in all buffers. */
574 bool ok = true;
575 size_t n_read; /* Size in bytes of most recent read */
577 first = last = xmalloc (sizeof (LBUFFER));
578 first->nbytes = first->nlines = 0;
579 first->next = NULL;
580 tmp = xmalloc (sizeof (LBUFFER));
582 /* Input is always read into a fresh buffer. */
583 while (1)
585 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
586 if (n_read == 0 || n_read == SAFE_READ_ERROR)
587 break;
588 tmp->nbytes = n_read;
589 *read_pos += n_read;
590 tmp->nlines = 0;
591 tmp->next = NULL;
593 /* Count the number of newlines just read. */
595 char const *buffer_end = tmp->buffer + n_read;
596 char const *p = tmp->buffer;
597 while ((p = memchr (p, '\n', buffer_end - p)))
599 ++p;
600 ++tmp->nlines;
603 total_lines += tmp->nlines;
605 /* If there is enough room in the last buffer read, just append the new
606 one to it. This is because when reading from a pipe, `n_read' can
607 often be very small. */
608 if (tmp->nbytes + last->nbytes < BUFSIZ)
610 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
611 last->nbytes += tmp->nbytes;
612 last->nlines += tmp->nlines;
614 else
616 /* If there's not enough room, link the new buffer onto the end of
617 the list, then either free up the oldest buffer for the next
618 read if that would leave enough lines, or else malloc a new one.
619 Some compaction mechanism is possible but probably not
620 worthwhile. */
621 last = last->next = tmp;
622 if (total_lines - first->nlines > n_lines)
624 tmp = first;
625 total_lines -= first->nlines;
626 first = first->next;
628 else
629 tmp = xmalloc (sizeof (LBUFFER));
633 free (tmp);
635 if (n_read == SAFE_READ_ERROR)
637 error (0, errno, _("error reading %s"), quote (pretty_filename));
638 ok = false;
639 goto free_lbuffers;
642 /* If the file is empty, then bail out. */
643 if (last->nbytes == 0)
644 goto free_lbuffers;
646 /* This prevents a core dump when the pipe contains no newlines. */
647 if (n_lines == 0)
648 goto free_lbuffers;
650 /* Count the incomplete line on files that don't end with a newline. */
651 if (last->buffer[last->nbytes - 1] != '\n')
653 ++last->nlines;
654 ++total_lines;
657 /* Run through the list, printing lines. First, skip over unneeded
658 buffers. */
659 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
660 total_lines -= tmp->nlines;
662 /* Find the correct beginning, then print the rest of the file. */
664 char const *beg = tmp->buffer;
665 char const *buffer_end = tmp->buffer + tmp->nbytes;
666 if (total_lines > n_lines)
668 /* Skip `total_lines' - `n_lines' newlines. We made sure that
669 `total_lines' - `n_lines' <= `tmp->nlines'. */
670 size_t j;
671 for (j = total_lines - n_lines; j; --j)
673 beg = memchr (beg, '\n', buffer_end - beg);
674 assert (beg);
675 ++beg;
679 xwrite_stdout (beg, buffer_end - beg);
682 for (tmp = tmp->next; tmp; tmp = tmp->next)
683 xwrite_stdout (tmp->buffer, tmp->nbytes);
685 free_lbuffers:
686 while (first)
688 tmp = first->next;
689 free (first);
690 first = tmp;
692 return ok;
695 /* Print the last N_BYTES characters from the end of pipe FD.
696 This is a stripped down version of pipe_lines.
697 Return true if successful. */
699 static bool
700 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
701 uintmax_t *read_pos)
703 struct charbuffer
705 char buffer[BUFSIZ];
706 size_t nbytes;
707 struct charbuffer *next;
709 typedef struct charbuffer CBUFFER;
710 CBUFFER *first, *last, *tmp;
711 size_t i; /* Index into buffers. */
712 size_t total_bytes = 0; /* Total characters in all buffers. */
713 bool ok = true;
714 size_t n_read;
716 first = last = xmalloc (sizeof (CBUFFER));
717 first->nbytes = 0;
718 first->next = NULL;
719 tmp = xmalloc (sizeof (CBUFFER));
721 /* Input is always read into a fresh buffer. */
722 while (1)
724 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
725 if (n_read == 0 || n_read == SAFE_READ_ERROR)
726 break;
727 *read_pos += n_read;
728 tmp->nbytes = n_read;
729 tmp->next = NULL;
731 total_bytes += tmp->nbytes;
732 /* If there is enough room in the last buffer read, just append the new
733 one to it. This is because when reading from a pipe, `nbytes' can
734 often be very small. */
735 if (tmp->nbytes + last->nbytes < BUFSIZ)
737 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
738 last->nbytes += tmp->nbytes;
740 else
742 /* If there's not enough room, link the new buffer onto the end of
743 the list, then either free up the oldest buffer for the next
744 read if that would leave enough characters, or else malloc a new
745 one. Some compaction mechanism is possible but probably not
746 worthwhile. */
747 last = last->next = tmp;
748 if (total_bytes - first->nbytes > n_bytes)
750 tmp = first;
751 total_bytes -= first->nbytes;
752 first = first->next;
754 else
756 tmp = xmalloc (sizeof (CBUFFER));
761 free (tmp);
763 if (n_read == SAFE_READ_ERROR)
765 error (0, errno, _("error reading %s"), quote (pretty_filename));
766 ok = false;
767 goto free_cbuffers;
770 /* Run through the list, printing characters. First, skip over unneeded
771 buffers. */
772 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
773 total_bytes -= tmp->nbytes;
775 /* Find the correct beginning, then print the rest of the file.
776 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
777 if (total_bytes > n_bytes)
778 i = total_bytes - n_bytes;
779 else
780 i = 0;
781 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
783 for (tmp = tmp->next; tmp; tmp = tmp->next)
784 xwrite_stdout (tmp->buffer, tmp->nbytes);
786 free_cbuffers:
787 while (first)
789 tmp = first->next;
790 free (first);
791 first = tmp;
793 return ok;
796 /* Skip N_BYTES characters from the start of pipe FD, and print
797 any extra characters that were read beyond that.
798 Return 1 on error, 0 if ok, -1 if EOF. */
800 static int
801 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
802 uintmax_t *read_pos)
804 char buffer[BUFSIZ];
806 while (0 < n_bytes)
808 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
809 if (bytes_read == 0)
810 return -1;
811 if (bytes_read == SAFE_READ_ERROR)
813 error (0, errno, _("error reading %s"), quote (pretty_filename));
814 return 1;
816 read_pos += bytes_read;
817 if (bytes_read <= n_bytes)
818 n_bytes -= bytes_read;
819 else
821 size_t n_remaining = bytes_read - n_bytes;
822 if (n_remaining)
823 xwrite_stdout (&buffer[n_bytes], n_remaining);
824 break;
828 return 0;
831 /* Skip N_LINES lines at the start of file or pipe FD, and print
832 any extra characters that were read beyond that.
833 Return 1 on error, 0 if ok, -1 if EOF. */
835 static int
836 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
837 uintmax_t *read_pos)
839 if (n_lines == 0)
840 return 0;
842 while (1)
844 char buffer[BUFSIZ];
845 char *p = buffer;
846 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
847 char *buffer_end = buffer + bytes_read;
848 if (bytes_read == 0) /* EOF */
849 return -1;
850 if (bytes_read == SAFE_READ_ERROR) /* error */
852 error (0, errno, _("error reading %s"), quote (pretty_filename));
853 return 1;
856 *read_pos += bytes_read;
858 while ((p = memchr (p, '\n', buffer_end - p)))
860 ++p;
861 if (--n_lines == 0)
863 if (p < buffer_end)
864 xwrite_stdout (p, buffer_end - p);
865 return 0;
871 #if HAVE_INOTIFY
872 /* Without inotify support, always return false. Otherwise, return false
873 when FD is open on a file known to reside on a local file system.
874 If fstatfs fails, give a diagnostic and return true.
875 If fstatfs cannot be called, return true. */
876 static bool
877 fremote (int fd, const char *name)
879 bool remote = true; /* be conservative (poll by default). */
881 # if HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE && defined __linux__
882 struct statfs buf;
883 int err = fstatfs (fd, &buf);
884 if (err != 0)
886 error (0, errno, _("cannot determine location of %s. "
887 "reverting to polling"), quote (name));
889 else
891 switch (buf.f_type)
893 case S_MAGIC_AFS:
894 case S_MAGIC_CIFS:
895 case S_MAGIC_CODA:
896 case S_MAGIC_FUSEBLK:
897 case S_MAGIC_FUSECTL:
898 case S_MAGIC_GFS:
899 case S_MAGIC_KAFS:
900 case S_MAGIC_LUSTRE:
901 case S_MAGIC_NCP:
902 case S_MAGIC_NFS:
903 case S_MAGIC_NFSD:
904 case S_MAGIC_OCFS2:
905 case S_MAGIC_SMB:
906 break;
907 default:
908 remote = false;
911 # endif
913 return remote;
915 #else
916 /* Without inotify support, whether a file is remote is irrelevant.
917 Always return "false" in that case. */
918 # define fremote(fd, name) false
919 #endif
921 /* FIXME: describe */
923 static void
924 recheck (struct File_spec *f, bool blocking)
926 /* open/fstat the file and announce if dev/ino have changed */
927 struct stat new_stats;
928 bool ok = true;
929 bool is_stdin = (STREQ (f->name, "-"));
930 bool was_tailable = f->tailable;
931 int prev_errnum = f->errnum;
932 bool new_file;
933 int fd = (is_stdin
934 ? STDIN_FILENO
935 : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
937 assert (valid_file_spec (f));
939 /* If the open fails because the file doesn't exist,
940 then mark the file as not tailable. */
941 f->tailable = !(reopen_inaccessible_files && fd == -1);
943 if (fd == -1 || fstat (fd, &new_stats) < 0)
945 ok = false;
946 f->errnum = errno;
947 if (!f->tailable)
949 if (was_tailable)
951 /* FIXME-maybe: detect the case in which the file first becomes
952 unreadable (perms), and later becomes readable again and can
953 be seen to be the same file (dev/ino). Otherwise, tail prints
954 the entire contents of the file when it becomes readable. */
955 error (0, f->errnum, _("%s has become inaccessible"),
956 quote (pretty_name (f)));
958 else
960 /* say nothing... it's still not tailable */
963 else if (prev_errnum != errno)
965 error (0, errno, "%s", pretty_name (f));
968 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
970 ok = false;
971 f->errnum = -1;
972 error (0, 0, _("%s has been replaced with an untailable file;\
973 giving up on this name"),
974 quote (pretty_name (f)));
975 f->ignore = true;
977 else if (!disable_inotify && fremote (fd, pretty_name (f)))
979 ok = false;
980 f->errnum = -1;
981 error (0, 0, _("%s has been replaced with a remote file. "
982 "giving up on this name"), quote (pretty_name (f)));
983 f->ignore = true;
984 f->remote = true;
986 else
988 f->errnum = 0;
991 new_file = false;
992 if (!ok)
994 close_fd (fd, pretty_name (f));
995 close_fd (f->fd, pretty_name (f));
996 f->fd = -1;
998 else if (prev_errnum && prev_errnum != ENOENT)
1000 new_file = true;
1001 assert (f->fd == -1);
1002 error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
1004 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
1006 new_file = true;
1007 if (f->fd == -1)
1009 error (0, 0,
1010 _("%s has appeared; following end of new file"),
1011 quote (pretty_name (f)));
1013 else
1015 /* Close the old one. */
1016 close_fd (f->fd, pretty_name (f));
1018 /* File has been replaced (e.g., via log rotation) --
1019 tail the new one. */
1020 error (0, 0,
1021 _("%s has been replaced; following end of new file"),
1022 quote (pretty_name (f)));
1025 else
1027 if (f->fd == -1)
1029 /* This happens when one iteration finds the file missing,
1030 then the preceding <dev,inode> pair is reused as the
1031 file is recreated. */
1032 new_file = true;
1034 else
1036 close_fd (fd, pretty_name (f));
1040 if (new_file)
1042 /* Start at the beginning of the file. */
1043 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
1044 xlseek (fd, 0, SEEK_SET, pretty_name (f));
1048 /* Return true if any of the N_FILES files in F are live, i.e., have
1049 open file descriptors. */
1051 static bool
1052 any_live_files (const struct File_spec *f, size_t n_files)
1054 size_t i;
1056 for (i = 0; i < n_files; i++)
1057 if (0 <= f[i].fd)
1058 return true;
1059 return false;
1062 /* Tail N_FILES files forever, or until killed.
1063 The pertinent information for each file is stored in an entry of F.
1064 Loop over each of them, doing an fstat to see if they have changed size,
1065 and an occasional open/fstat to see if any dev/ino pair has changed.
1066 If none of them have changed size in one iteration, sleep for a
1067 while and try again. Continue until the user interrupts us. */
1069 static void
1070 tail_forever (struct File_spec *f, size_t n_files, double sleep_interval)
1072 /* Use blocking I/O as an optimization, when it's easy. */
1073 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
1074 && n_files == 1 && ! S_ISREG (f[0].mode));
1075 size_t last;
1076 bool writer_is_dead = false;
1078 last = n_files - 1;
1080 while (1)
1082 size_t i;
1083 bool any_input = false;
1085 for (i = 0; i < n_files; i++)
1087 int fd;
1088 char const *name;
1089 mode_t mode;
1090 struct stat stats;
1091 uintmax_t bytes_read;
1093 if (f[i].ignore)
1094 continue;
1096 if (f[i].fd < 0)
1098 recheck (&f[i], blocking);
1099 continue;
1102 fd = f[i].fd;
1103 name = pretty_name (&f[i]);
1104 mode = f[i].mode;
1106 if (f[i].blocking != blocking)
1108 int old_flags = fcntl (fd, F_GETFL);
1109 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1110 if (old_flags < 0
1111 || (new_flags != old_flags
1112 && fcntl (fd, F_SETFL, new_flags) == -1))
1114 /* Don't update f[i].blocking if fcntl fails. */
1115 if (S_ISREG (f[i].mode) && errno == EPERM)
1117 /* This happens when using tail -f on a file with
1118 the append-only attribute. */
1120 else
1121 error (EXIT_FAILURE, errno,
1122 _("%s: cannot change nonblocking mode"), name);
1124 else
1125 f[i].blocking = blocking;
1128 if (!f[i].blocking)
1130 if (fstat (fd, &stats) != 0)
1132 f[i].fd = -1;
1133 f[i].errnum = errno;
1134 error (0, errno, "%s", name);
1135 continue;
1138 if (f[i].mode == stats.st_mode
1139 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1140 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1142 if ((max_n_unchanged_stats_between_opens
1143 <= f[i].n_unchanged_stats++)
1144 && follow_mode == Follow_name)
1146 recheck (&f[i], f[i].blocking);
1147 f[i].n_unchanged_stats = 0;
1149 continue;
1152 /* This file has changed. Print out what we can, and
1153 then keep looping. */
1155 f[i].mtime = get_stat_mtime (&stats);
1156 f[i].mode = stats.st_mode;
1158 /* reset counter */
1159 f[i].n_unchanged_stats = 0;
1161 if (S_ISREG (mode) && stats.st_size < f[i].size)
1163 error (0, 0, _("%s: file truncated"), name);
1164 last = i;
1165 xlseek (fd, stats.st_size, SEEK_SET, name);
1166 f[i].size = stats.st_size;
1167 continue;
1170 if (i != last)
1172 if (print_headers)
1173 write_header (name);
1174 last = i;
1178 bytes_read = dump_remainder (name, fd,
1179 (f[i].blocking
1180 ? COPY_A_BUFFER : COPY_TO_EOF));
1181 any_input |= (bytes_read != 0);
1182 f[i].size += bytes_read;
1185 if (! any_live_files (f, n_files) && ! reopen_inaccessible_files)
1187 error (0, 0, _("no files remaining"));
1188 break;
1191 if ((!any_input || blocking) && fflush (stdout) != 0)
1192 error (EXIT_FAILURE, errno, _("write error"));
1194 /* If nothing was read, sleep and/or check for dead writers. */
1195 if (!any_input)
1197 if (writer_is_dead)
1198 break;
1200 /* Once the writer is dead, read the files once more to
1201 avoid a race condition. */
1202 writer_is_dead = (pid != 0
1203 && kill (pid, 0) != 0
1204 /* Handle the case in which you cannot send a
1205 signal to the writer, so kill fails and sets
1206 errno to EPERM. */
1207 && errno != EPERM);
1209 if (!writer_is_dead && xnanosleep (sleep_interval))
1210 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1216 #if HAVE_INOTIFY
1218 /* Return true if any of the N_FILES files in F is remote, i.e., has
1219 an open file descriptor and is on a network file system. */
1221 static bool
1222 any_remote_file (const struct File_spec *f, size_t n_files)
1224 size_t i;
1226 for (i = 0; i < n_files; i++)
1227 if (0 <= f[i].fd && f[i].remote)
1228 return true;
1229 return false;
1232 /* Return true if any of the N_FILES files in F represents
1233 stdin and is tailable. */
1235 static bool
1236 tailable_stdin (const struct File_spec *f, size_t n_files)
1238 size_t i;
1240 for (i = 0; i < n_files; i++)
1241 if (!f[i].ignore && STREQ (f[i].name, "-"))
1242 return true;
1243 return false;
1246 static size_t
1247 wd_hasher (const void *entry, size_t tabsize)
1249 const struct File_spec *spec = entry;
1250 return spec->wd % tabsize;
1253 static bool
1254 wd_comparator (const void *e1, const void *e2)
1256 const struct File_spec *spec1 = e1;
1257 const struct File_spec *spec2 = e2;
1258 return spec1->wd == spec2->wd;
1261 /* Helper function used by `tail_forever_inotify'. */
1262 static void
1263 check_fspec (struct File_spec *fspec, int wd, int *prev_wd)
1265 struct stat stats;
1266 char const *name = pretty_name (fspec);
1268 if (fstat (fspec->fd, &stats) != 0)
1270 close_fd (fspec->fd, name);
1271 fspec->fd = -1;
1272 fspec->errnum = errno;
1273 return;
1276 if (S_ISREG (fspec->mode) && stats.st_size < fspec->size)
1278 error (0, 0, _("%s: file truncated"), name);
1279 *prev_wd = wd;
1280 xlseek (fspec->fd, stats.st_size, SEEK_SET, name);
1281 fspec->size = stats.st_size;
1283 else if (S_ISREG (fspec->mode) && stats.st_size == fspec->size
1284 && timespec_cmp (fspec->mtime, get_stat_mtime (&stats)) == 0)
1285 return;
1287 if (wd != *prev_wd)
1289 if (print_headers)
1290 write_header (name);
1291 *prev_wd = wd;
1294 uintmax_t bytes_read = dump_remainder (name, fspec->fd, COPY_TO_EOF);
1295 fspec->size += bytes_read;
1297 if (fflush (stdout) != 0)
1298 error (EXIT_FAILURE, errno, _("write error"));
1301 /* Tail N_FILES files forever, or until killed.
1302 Check modifications using the inotify events system. */
1303 static void
1304 tail_forever_inotify (int wd, struct File_spec *f, size_t n_files,
1305 double sleep_interval)
1307 unsigned int max_realloc = 3;
1309 /* Map an inotify watch descriptor to the name of the file it's watching. */
1310 Hash_table *wd_to_name;
1312 bool found_watchable = false;
1313 bool writer_is_dead = false;
1314 int prev_wd;
1315 size_t evlen = 0;
1316 char *evbuf;
1317 size_t evbuf_off = 0;
1318 size_t len = 0;
1320 wd_to_name = hash_initialize (n_files, NULL, wd_hasher, wd_comparator, NULL);
1321 if (! wd_to_name)
1322 xalloc_die ();
1324 /* Add an inotify watch for each watched file. If -F is specified then watch
1325 its parent directory too, in this way when they re-appear we can add them
1326 again to the watch list. */
1327 size_t i;
1328 for (i = 0; i < n_files; i++)
1330 if (!f[i].ignore)
1332 size_t fnlen = strlen (f[i].name);
1333 if (evlen < fnlen)
1334 evlen = fnlen;
1336 f[i].wd = -1;
1338 if (follow_mode == Follow_name)
1340 size_t dirlen = dir_len (f[i].name);
1341 char prev = f[i].name[dirlen];
1342 f[i].basename_start = last_component (f[i].name) - f[i].name;
1344 f[i].name[dirlen] = '\0';
1346 /* It's fine to add the same directory more than once.
1347 In that case the same watch descriptor is returned. */
1348 f[i].parent_wd = inotify_add_watch (wd, dirlen ? f[i].name : ".",
1349 (IN_CREATE | IN_MOVED_TO
1350 | IN_ATTRIB));
1352 f[i].name[dirlen] = prev;
1354 if (f[i].parent_wd < 0)
1356 error (0, errno, _("cannot watch parent directory of %s"),
1357 quote (f[i].name));
1358 continue;
1362 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1364 if (f[i].wd < 0)
1366 if (errno != f[i].errnum)
1367 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1368 continue;
1371 if (hash_insert (wd_to_name, &(f[i])) == NULL)
1372 xalloc_die ();
1374 found_watchable = true;
1378 if (follow_mode == Follow_descriptor && !found_watchable)
1379 return;
1381 prev_wd = f[n_files - 1].wd;
1383 /* Check files again. New data can be available since last time we checked
1384 and before they are watched by inotify. */
1385 for (i = 0; i < n_files; i++)
1387 if (!f[i].ignore)
1388 check_fspec (&f[i], f[i].wd, &prev_wd);
1391 evlen += sizeof (struct inotify_event) + 1;
1392 evbuf = xmalloc (evlen);
1394 /* Wait for inotify events and handle them. Events on directories make sure
1395 that watched files can be re-added when -F is used.
1396 This loop sleeps on the `safe_read' call until a new event is notified. */
1397 while (1)
1399 struct File_spec *fspec;
1400 struct inotify_event *ev;
1402 /* When watching a PID, ensure that a read from WD will not block
1403 indefinitely. */
1404 if (pid)
1406 if (writer_is_dead)
1407 exit (EXIT_SUCCESS);
1409 writer_is_dead = (kill (pid, 0) != 0 && errno != EPERM);
1411 struct timeval delay; /* how long to wait for file changes. */
1412 if (writer_is_dead)
1413 delay.tv_sec = delay.tv_usec = 0;
1414 else
1416 delay.tv_sec = (time_t) sleep_interval;
1417 delay.tv_usec = 1000000 * (sleep_interval - delay.tv_sec);
1420 fd_set rfd;
1421 FD_ZERO (&rfd);
1422 FD_SET (wd, &rfd);
1424 int file_change = select (wd + 1, &rfd, NULL, NULL, &delay);
1426 if (file_change == 0)
1427 continue;
1428 else if (file_change == -1)
1429 error (EXIT_FAILURE, errno, _("error monitoring inotify event"));
1432 if (len <= evbuf_off)
1434 len = safe_read (wd, evbuf, evlen);
1435 evbuf_off = 0;
1437 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1438 is too small. */
1439 if ((len == 0 || (len == SAFE_READ_ERROR && errno == EINVAL))
1440 && max_realloc--)
1442 len = 0;
1443 evlen *= 2;
1444 evbuf = xrealloc (evbuf, evlen);
1445 continue;
1448 if (len == 0 || len == SAFE_READ_ERROR)
1449 error (EXIT_FAILURE, errno, _("error reading inotify event"));
1452 ev = (struct inotify_event *) (evbuf + evbuf_off);
1453 evbuf_off += sizeof (*ev) + ev->len;
1455 if (ev->len) /* event on ev->name in watched directory */
1457 size_t j;
1458 for (j = 0; j < n_files; j++)
1460 /* With N=hundreds of frequently-changing files, this O(N^2)
1461 process might be a problem. FIXME: use a hash table? */
1462 if (f[j].parent_wd == ev->wd
1463 && STREQ (ev->name, f[j].name + f[j].basename_start))
1464 break;
1467 /* It is not a watched file. */
1468 if (j == n_files)
1469 continue;
1471 /* It's fine to add the same file more than once. */
1472 int new_wd = inotify_add_watch (wd, f[j].name, inotify_wd_mask);
1473 if (new_wd < 0)
1475 error (0, errno, _("cannot watch %s"), quote (f[j].name));
1476 continue;
1479 fspec = &(f[j]);
1481 /* Remove `fspec' and re-add it using `new_fd' as its key. */
1482 hash_delete (wd_to_name, fspec);
1483 fspec->wd = new_wd;
1485 /* If the file was moved then inotify will use the source file wd for
1486 the destination file. Make sure the key is not present in the
1487 table. */
1488 struct File_spec *prev = hash_delete (wd_to_name, fspec);
1489 if (prev && prev != fspec)
1491 if (follow_mode == Follow_name)
1492 recheck (prev, false);
1493 prev->wd = -1;
1494 close_fd (prev->fd, pretty_name (prev));
1497 if (hash_insert (wd_to_name, fspec) == NULL)
1498 xalloc_die ();
1500 if (follow_mode == Follow_name)
1501 recheck (fspec, false);
1503 else
1505 struct File_spec key;
1506 key.wd = ev->wd;
1507 fspec = hash_lookup (wd_to_name, &key);
1510 if (! fspec)
1511 continue;
1513 if (ev->mask & (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF))
1515 /* For IN_DELETE_SELF, we always want to remove the watch.
1516 However, for IN_MOVE_SELF (the file we're watching has
1517 been clobbered via a rename), when tailing by NAME, we
1518 must continue to watch the file. It's only when following
1519 by file descriptor that we must remove the watch. */
1520 if ((ev->mask & IN_DELETE_SELF)
1521 || ((ev->mask & IN_MOVE_SELF) && follow_mode == Follow_descriptor))
1523 inotify_rm_watch (wd, fspec->wd);
1524 hash_delete (wd_to_name, fspec);
1526 if (follow_mode == Follow_name)
1527 recheck (fspec, false);
1529 continue;
1531 check_fspec (fspec, ev->wd, &prev_wd);
1534 #endif
1536 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1537 Return true if successful. */
1539 static bool
1540 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1541 uintmax_t *read_pos)
1543 struct stat stats;
1545 if (fstat (fd, &stats))
1547 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1548 return false;
1551 if (from_start)
1553 if ( ! presume_input_pipe
1554 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1556 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1557 *read_pos += n_bytes;
1559 else
1561 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1562 if (t)
1563 return t < 0;
1565 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1567 else
1569 if ( ! presume_input_pipe
1570 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1572 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1573 off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
1574 off_t diff = end_pos - current_pos;
1575 /* Be careful here. The current position may actually be
1576 beyond the end of the file. */
1577 off_t bytes_remaining = diff < 0 ? 0 : diff;
1578 off_t nb = n_bytes;
1580 if (bytes_remaining <= nb)
1582 /* From the current position to end of file, there are no
1583 more bytes than have been requested. So reposition the
1584 file pointer to the incoming current position and print
1585 everything after that. */
1586 *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1588 else
1590 /* There are more bytes remaining than were requested.
1591 Back up. */
1592 *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
1594 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1596 else
1597 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1599 return true;
1602 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1603 Return true if successful. */
1605 static bool
1606 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1607 uintmax_t *read_pos)
1609 struct stat stats;
1611 if (fstat (fd, &stats))
1613 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1614 return false;
1617 if (from_start)
1619 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1620 if (t)
1621 return t < 0;
1622 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1624 else
1626 off_t start_pos = -1;
1627 off_t end_pos;
1629 /* Use file_lines only if FD refers to a regular file for
1630 which lseek (... SEEK_END) works. */
1631 if ( ! presume_input_pipe
1632 && S_ISREG (stats.st_mode)
1633 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1634 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1636 *read_pos = end_pos;
1637 if (end_pos != 0
1638 && ! file_lines (pretty_filename, fd, n_lines,
1639 start_pos, end_pos, read_pos))
1640 return false;
1642 else
1644 /* Under very unlikely circumstances, it is possible to reach
1645 this point after positioning the file pointer to end of file
1646 via the `lseek (...SEEK_END)' above. In that case, reposition
1647 the file pointer back to start_pos before calling pipe_lines. */
1648 if (start_pos != -1)
1649 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1651 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1654 return true;
1657 /* Display the last N_UNITS units of file FILENAME, open for reading
1658 via FD. Set *READ_POS to the position of the input stream pointer.
1659 *READ_POS is usually the number of bytes read and corresponds to an
1660 offset from the beginning of a file. However, it may be larger than
1661 OFF_T_MAX (as for an input pipe), and may also be larger than the
1662 number of bytes read (when an input pointer is initially not at
1663 beginning of file), and may be far greater than the number of bytes
1664 actually read for an input file that is seekable.
1665 Return true if successful. */
1667 static bool
1668 tail (const char *filename, int fd, uintmax_t n_units,
1669 uintmax_t *read_pos)
1671 *read_pos = 0;
1672 if (count_lines)
1673 return tail_lines (filename, fd, n_units, read_pos);
1674 else
1675 return tail_bytes (filename, fd, n_units, read_pos);
1678 /* Display the last N_UNITS units of the file described by F.
1679 Return true if successful. */
1681 static bool
1682 tail_file (struct File_spec *f, uintmax_t n_units)
1684 int fd;
1685 bool ok;
1687 bool is_stdin = (STREQ (f->name, "-"));
1689 if (is_stdin)
1691 have_read_stdin = true;
1692 fd = STDIN_FILENO;
1693 if (O_BINARY && ! isatty (STDIN_FILENO))
1694 xfreopen (NULL, "rb", stdin);
1696 else
1697 fd = open (f->name, O_RDONLY | O_BINARY);
1699 f->tailable = !(reopen_inaccessible_files && fd == -1);
1701 if (fd == -1)
1703 if (forever)
1705 f->fd = -1;
1706 f->errnum = errno;
1707 f->ignore = false;
1708 f->ino = 0;
1709 f->dev = 0;
1711 error (0, errno, _("cannot open %s for reading"),
1712 quote (pretty_name (f)));
1713 ok = false;
1715 else
1717 uintmax_t read_pos;
1719 if (print_headers)
1720 write_header (pretty_name (f));
1721 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1722 if (forever)
1724 struct stat stats;
1726 #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1727 /* Before the tail function provided `read_pos', there was
1728 a race condition described in the URL below. This sleep
1729 call made the window big enough to exercise the problem. */
1730 xnanosleep (1);
1731 #endif
1732 f->errnum = ok - 1;
1733 if (fstat (fd, &stats) < 0)
1735 ok = false;
1736 f->errnum = errno;
1737 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1739 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1741 error (0, 0, _("%s: cannot follow end of this type of file;\
1742 giving up on this name"),
1743 pretty_name (f));
1744 ok = false;
1745 f->errnum = -1;
1746 f->ignore = true;
1749 if (!ok)
1751 close_fd (fd, pretty_name (f));
1752 f->fd = -1;
1754 else
1756 /* Note: we must use read_pos here, not stats.st_size,
1757 to avoid a race condition described by Ken Raeburn:
1758 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1759 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1760 f->remote = fremote (fd, pretty_name (f));
1763 else
1765 if (!is_stdin && close (fd))
1767 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1768 ok = false;
1773 return ok;
1776 /* If obsolete usage is allowed, and the command line arguments are of
1777 the obsolete form and the option string is well-formed, set
1778 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1779 return true. If the command line arguments are obviously incorrect
1780 (e.g., because obsolete usage is not allowed and the arguments are
1781 incorrect for non-obsolete usage), report an error and exit.
1782 Otherwise, return false and don't modify any parameter or global
1783 variable. */
1785 static bool
1786 parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1788 const char *p;
1789 const char *n_string;
1790 const char *n_string_end;
1791 bool obsolete_usage;
1792 int default_count = DEFAULT_N_LINES;
1793 bool t_from_start;
1794 bool t_count_lines = true;
1795 bool t_forever = false;
1797 /* With the obsolete form, there is one option string and at most
1798 one file argument. Watch out for "-" and "--", though. */
1799 if (! (argc == 2
1800 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1801 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1802 return false;
1804 obsolete_usage = (posix2_version () < 200112);
1805 p = argv[1];
1807 switch (*p++)
1809 default:
1810 return false;
1812 case '+':
1813 /* Leading "+" is a file name in the non-obsolete form. */
1814 if (!obsolete_usage)
1815 return false;
1817 t_from_start = true;
1818 break;
1820 case '-':
1821 /* In the non-obsolete form, "-" is standard input and "-c"
1822 requires an option-argument. The obsolete multidigit options
1823 are supported as a GNU extension even when conforming to
1824 POSIX 1003.1-2001, so don't complain about them. */
1825 if (!obsolete_usage && !p[p[0] == 'c'])
1826 return false;
1828 t_from_start = false;
1829 break;
1832 n_string = p;
1833 while (ISDIGIT (*p))
1834 p++;
1835 n_string_end = p;
1837 switch (*p)
1839 case 'b': default_count *= 512; /* Fall through. */
1840 case 'c': t_count_lines = false; /* Fall through. */
1841 case 'l': p++; break;
1844 if (*p == 'f')
1846 t_forever = true;
1847 ++p;
1850 if (*p)
1851 return false;
1853 if (n_string == n_string_end)
1854 *n_units = default_count;
1855 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
1856 & ~LONGINT_INVALID_SUFFIX_CHAR)
1857 != LONGINT_OK)
1858 error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1]));
1860 /* Set globals. */
1861 from_start = t_from_start;
1862 count_lines = t_count_lines;
1863 forever = t_forever;
1865 return true;
1868 static void
1869 parse_options (int argc, char **argv,
1870 uintmax_t *n_units, enum header_mode *header_mode,
1871 double *sleep_interval)
1873 int c;
1875 while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789",
1876 long_options, NULL))
1877 != -1)
1879 switch (c)
1881 case 'F':
1882 forever = true;
1883 follow_mode = Follow_name;
1884 reopen_inaccessible_files = true;
1885 break;
1887 case 'c':
1888 case 'n':
1889 count_lines = (c == 'n');
1890 if (*optarg == '+')
1891 from_start = true;
1892 else if (*optarg == '-')
1893 ++optarg;
1896 strtol_error s_err;
1897 s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0");
1898 if (s_err != LONGINT_OK)
1900 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1901 (c == 'n'
1902 ? _("invalid number of lines")
1903 : _("invalid number of bytes")));
1906 break;
1908 case 'f':
1909 case LONG_FOLLOW_OPTION:
1910 forever = true;
1911 if (optarg == NULL)
1912 follow_mode = DEFAULT_FOLLOW_MODE;
1913 else
1914 follow_mode = XARGMATCH ("--follow", optarg,
1915 follow_mode_string, follow_mode_map);
1916 break;
1918 case RETRY_OPTION:
1919 reopen_inaccessible_files = true;
1920 break;
1922 case MAX_UNCHANGED_STATS_OPTION:
1923 /* --max-unchanged-stats=N */
1924 if (xstrtoumax (optarg, NULL, 10,
1925 &max_n_unchanged_stats_between_opens,
1927 != LONGINT_OK)
1929 error (EXIT_FAILURE, 0,
1930 _("%s: invalid maximum number of unchanged stats between opens"),
1931 optarg);
1933 break;
1935 case DISABLE_INOTIFY_OPTION:
1936 disable_inotify = true;
1937 break;
1939 case PID_OPTION:
1941 strtol_error s_err;
1942 unsigned long int tmp_ulong;
1943 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1944 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1946 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1948 pid = tmp_ulong;
1950 break;
1952 case PRESUME_INPUT_PIPE_OPTION:
1953 presume_input_pipe = true;
1954 break;
1956 case 'q':
1957 *header_mode = never;
1958 break;
1960 case 's':
1962 double s;
1963 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
1964 error (EXIT_FAILURE, 0,
1965 _("%s: invalid number of seconds"), optarg);
1966 *sleep_interval = s;
1968 break;
1970 case 'v':
1971 *header_mode = always;
1972 break;
1974 case_GETOPT_HELP_CHAR;
1976 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1978 case '0': case '1': case '2': case '3': case '4':
1979 case '5': case '6': case '7': case '8': case '9':
1980 error (EXIT_FAILURE, 0,
1981 _("option used in invalid context -- %c"), c);
1983 default:
1984 usage (EXIT_FAILURE);
1988 if (reopen_inaccessible_files && follow_mode != Follow_name)
1989 error (0, 0, _("warning: --retry is useful mainly when following by name"));
1991 if (pid && !forever)
1992 error (0, 0,
1993 _("warning: PID ignored; --pid=PID is useful only when following"));
1994 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1996 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1997 pid = 0;
2001 /* Mark as '.ignore'd each member of F that corresponds to a
2002 pipe or fifo, and return the number of non-ignored members. */
2003 static size_t
2004 ignore_fifo_and_pipe (struct File_spec *f, size_t n_files)
2006 /* When there is no FILE operand and stdin is a pipe or FIFO
2007 POSIX requires that tail ignore the -f option.
2008 Since we allow multiple FILE operands, we extend that to say: with -f,
2009 ignore any "-" operand that corresponds to a pipe or FIFO. */
2010 size_t n_viable = 0;
2012 size_t i;
2013 for (i = 0; i < n_files; i++)
2015 bool is_a_fifo_or_pipe =
2016 (STREQ (f[i].name, "-")
2017 && !f[i].ignore
2018 && 0 <= f[i].fd
2019 && (S_ISFIFO (f[i].mode)
2020 || (HAVE_FIFO_PIPES != 1 && isapipe (f[i].fd))));
2021 if (is_a_fifo_or_pipe)
2022 f[i].ignore = true;
2023 else
2024 ++n_viable;
2027 return n_viable;
2031 main (int argc, char **argv)
2033 enum header_mode header_mode = multiple_files;
2034 bool ok = true;
2035 /* If from_start, the number of items to skip before printing; otherwise,
2036 the number of items at the end of the file to print. Although the type
2037 is signed, the value is never negative. */
2038 uintmax_t n_units = DEFAULT_N_LINES;
2039 size_t n_files;
2040 char **file;
2041 struct File_spec *F;
2042 size_t i;
2043 bool obsolete_option;
2045 /* The number of seconds to sleep between iterations.
2046 During one iteration, every file name or descriptor is checked to
2047 see if it has changed. */
2048 double sleep_interval = 1.0;
2050 initialize_main (&argc, &argv);
2051 set_program_name (argv[0]);
2052 setlocale (LC_ALL, "");
2053 bindtextdomain (PACKAGE, LOCALEDIR);
2054 textdomain (PACKAGE);
2056 atexit (close_stdout);
2058 have_read_stdin = false;
2060 count_lines = true;
2061 forever = from_start = print_headers = false;
2062 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
2063 argc -= obsolete_option;
2064 argv += obsolete_option;
2065 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
2067 /* To start printing with item N_UNITS from the start of the file, skip
2068 N_UNITS - 1 items. `tail -n +0' is actually meaningless, but for Unix
2069 compatibility it's treated the same as `tail -n +1'. */
2070 if (from_start)
2072 if (n_units)
2073 --n_units;
2076 if (optind < argc)
2078 n_files = argc - optind;
2079 file = argv + optind;
2081 else
2083 static char *dummy_stdin = (char *) "-";
2084 n_files = 1;
2085 file = &dummy_stdin;
2089 bool found_hyphen = false;
2091 for (i = 0; i < n_files; i++)
2092 if (STREQ (file[i], "-"))
2093 found_hyphen = true;
2095 /* When following by name, there must be a name. */
2096 if (found_hyphen && follow_mode == Follow_name)
2097 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
2099 /* When following forever, warn if any file is `-'.
2100 This is only a warning, since tail's output (before a failing seek,
2101 and that from any non-stdin files) might still be useful. */
2102 if (forever && found_hyphen && isatty (STDIN_FILENO))
2103 error (0, 0, _("warning: following standard input"
2104 " indefinitely is ineffective"));
2107 F = xnmalloc (n_files, sizeof *F);
2108 for (i = 0; i < n_files; i++)
2109 F[i].name = file[i];
2111 if (header_mode == always
2112 || (header_mode == multiple_files && n_files > 1))
2113 print_headers = true;
2115 if (O_BINARY && ! isatty (STDOUT_FILENO))
2116 xfreopen (NULL, "wb", stdout);
2118 for (i = 0; i < n_files; i++)
2119 ok &= tail_file (&F[i], n_units);
2121 if (forever && ignore_fifo_and_pipe (F, n_files))
2123 #if HAVE_INOTIFY
2124 /* tailable_stdin() checks if the user specifies stdin via "-",
2125 or implicitly by providing no arguments. If so, we won't use inotify.
2126 Technically, on systems with a working /dev/stdin, we *could*,
2127 but would it be worth it? Verifying that it's a real device
2128 and hooked up to stdin is not trivial, while reverting to
2129 non-inotify-based tail_forever is easy and portable.
2131 any_remote_file() checks if the user has specified any
2132 files that reside on remote file systems. inotify is not used
2133 in this case because it would miss any updates to the file
2134 that were not initiated from the local system.
2136 FIXME: inotify doesn't give any notification when a new
2137 (remote) file or directory is mounted on top a watched file.
2138 When follow_mode == Follow_name we would ideally like to detect that.
2139 Note if there is a change to the original file then we'll
2140 recheck it and follow the new file, or ignore it if the
2141 file has changed to being remote. */
2142 if (tailable_stdin (F, n_files) || any_remote_file (F, n_files))
2143 disable_inotify = true;
2145 if (!disable_inotify)
2147 int wd = inotify_init ();
2148 if (wd < 0)
2149 error (0, errno, _("inotify cannot be used, reverting to polling"));
2150 else
2152 /* Flush any output from tail_file, now, since
2153 tail_forever_inotify flushes only after writing,
2154 not before reading. */
2155 if (fflush (stdout) != 0)
2156 error (EXIT_FAILURE, errno, _("write error"));
2158 tail_forever_inotify (wd, F, n_files, sleep_interval);
2160 /* The only way the above returns is upon failure. */
2161 exit (EXIT_FAILURE);
2164 #endif
2165 tail_forever (F, n_files, sleep_interval);
2168 if (have_read_stdin && close (STDIN_FILENO) < 0)
2169 error (EXIT_FAILURE, errno, "-");
2170 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);