doc: clarify the operation of wc -L
[coreutils.git] / src / tail.c
blobc9736ca5b80c6d436db8f0465c3f070e0bbc5bf1
1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989-2015 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-size.h"
44 #include "stat-time.h"
45 #include "xfreopen.h"
46 #include "xnanosleep.h"
47 #include "xdectoint.h"
48 #include "xstrtol.h"
49 #include "xstrtod.h"
51 #if HAVE_INOTIFY
52 # include "hash.h"
53 # include <sys/inotify.h>
54 /* 'select' is used by tail_forever_inotify. */
55 # include <sys/select.h>
57 /* inotify needs to know if a file is local. */
58 # include "fs.h"
59 # include "fs-is-local.h"
60 # if HAVE_SYS_STATFS_H
61 # include <sys/statfs.h>
62 # elif HAVE_SYS_VFS_H
63 # include <sys/vfs.h>
64 # endif
65 #endif
67 /* The official name of this program (e.g., no 'g' prefix). */
68 #define PROGRAM_NAME "tail"
70 #define AUTHORS \
71 proper_name ("Paul Rubin"), \
72 proper_name ("David MacKenzie"), \
73 proper_name ("Ian Lance Taylor"), \
74 proper_name ("Jim Meyering")
76 /* Number of items to tail. */
77 #define DEFAULT_N_LINES 10
79 /* Special values for dump_remainder's N_BYTES parameter. */
80 #define COPY_TO_EOF UINTMAX_MAX
81 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
83 /* FIXME: make Follow_name the default? */
84 #define DEFAULT_FOLLOW_MODE Follow_descriptor
86 enum Follow_mode
88 /* Follow the name of each file: if the file is renamed, try to reopen
89 that name and track the end of the new file if/when it's recreated.
90 This is useful for tracking logs that are occasionally rotated. */
91 Follow_name = 1,
93 /* Follow each descriptor obtained upon opening a file.
94 That means we'll continue to follow the end of a file even after
95 it has been renamed or unlinked. */
96 Follow_descriptor = 2
99 /* The types of files for which tail works. */
100 #define IS_TAILABLE_FILE_TYPE(Mode) \
101 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
103 static char const *const follow_mode_string[] =
105 "descriptor", "name", NULL
108 static enum Follow_mode const follow_mode_map[] =
110 Follow_descriptor, Follow_name,
113 struct File_spec
115 /* The actual file name, or "-" for stdin. */
116 char *name;
118 /* Attributes of the file the last time we checked. */
119 off_t size;
120 struct timespec mtime;
121 dev_t dev;
122 ino_t ino;
123 mode_t mode;
125 /* The specified name initially referred to a directory or some other
126 type for which tail isn't meaningful. Unlike for a permission problem
127 (tailable, below) once this is set, the name is not checked ever again. */
128 bool ignore;
130 /* See the description of fremote. */
131 bool remote;
133 /* A file is tailable if it exists, is readable, and is of type
134 IS_TAILABLE_FILE_TYPE. */
135 bool tailable;
137 /* File descriptor on which the file is open; -1 if it's not open. */
138 int fd;
140 /* The value of errno seen last time we checked this file. */
141 int errnum;
143 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
144 int blocking;
146 #if HAVE_INOTIFY
147 /* The watch descriptor used by inotify. */
148 int wd;
150 /* The parent directory watch descriptor. It is used only
151 * when Follow_name is used. */
152 int parent_wd;
154 /* Offset in NAME of the basename part. */
155 size_t basename_start;
156 #endif
158 /* See description of DEFAULT_MAX_N_... below. */
159 uintmax_t n_unchanged_stats;
162 /* Keep trying to open a file even if it is inaccessible when tail starts
163 or if it becomes inaccessible later -- useful only with -f. */
164 static bool reopen_inaccessible_files;
166 /* If true, interpret the numeric argument as the number of lines.
167 Otherwise, interpret it as the number of bytes. */
168 static bool count_lines;
170 /* Whether we follow the name of each file or the file descriptor
171 that is initially associated with each name. */
172 static enum Follow_mode follow_mode = Follow_descriptor;
174 /* If true, read from the ends of all specified files until killed. */
175 static bool forever;
177 /* If true, count from start of file instead of end. */
178 static bool from_start;
180 /* If true, print filename headers. */
181 static bool print_headers;
183 /* When to print the filename banners. */
184 enum header_mode
186 multiple_files, always, never
189 /* When tailing a file by name, if there have been this many consecutive
190 iterations for which the file has not changed, then open/fstat
191 the file to determine if that file name is still associated with the
192 same device/inode-number pair as before. This option is meaningful only
193 when following by name. --max-unchanged-stats=N */
194 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
195 static uintmax_t max_n_unchanged_stats_between_opens =
196 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
198 /* The process ID of the process (presumably on the current host)
199 that is writing to all followed files. */
200 static pid_t pid;
202 /* True if we have ever read standard input. */
203 static bool have_read_stdin;
205 /* If nonzero, skip the is-regular-file test used to determine whether
206 to use the lseek optimization. Instead, use the more general (and
207 more expensive) code unconditionally. Intended solely for testing. */
208 static bool presume_input_pipe;
210 /* If nonzero then don't use inotify even if available. */
211 static bool disable_inotify;
213 /* For long options that have no equivalent short option, use a
214 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
215 enum
217 RETRY_OPTION = CHAR_MAX + 1,
218 MAX_UNCHANGED_STATS_OPTION,
219 PID_OPTION,
220 PRESUME_INPUT_PIPE_OPTION,
221 LONG_FOLLOW_OPTION,
222 DISABLE_INOTIFY_OPTION
225 static struct option const long_options[] =
227 {"bytes", required_argument, NULL, 'c'},
228 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
229 {"lines", required_argument, NULL, 'n'},
230 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
231 {"-disable-inotify", no_argument, NULL,
232 DISABLE_INOTIFY_OPTION}, /* do not document */
233 {"pid", required_argument, NULL, PID_OPTION},
234 {"-presume-input-pipe", no_argument, NULL,
235 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
236 {"quiet", no_argument, NULL, 'q'},
237 {"retry", no_argument, NULL, RETRY_OPTION},
238 {"silent", no_argument, NULL, 'q'},
239 {"sleep-interval", required_argument, NULL, 's'},
240 {"verbose", no_argument, NULL, 'v'},
241 {GETOPT_HELP_OPTION_DECL},
242 {GETOPT_VERSION_OPTION_DECL},
243 {NULL, 0, NULL, 0}
246 void
247 usage (int status)
249 if (status != EXIT_SUCCESS)
250 emit_try_help ();
251 else
253 printf (_("\
254 Usage: %s [OPTION]... [FILE]...\n\
256 program_name);
257 printf (_("\
258 Print the last %d lines of each FILE to standard output.\n\
259 With more than one FILE, precede each with a header giving the file name.\n\
260 "), DEFAULT_N_LINES);
262 emit_stdin_note ();
263 emit_mandatory_arg_note ();
265 fputs (_("\
266 -c, --bytes=K output the last K bytes; or use -c +K to output\n\
267 bytes starting with the Kth of each file\n\
268 "), stdout);
269 fputs (_("\
270 -f, --follow[={name|descriptor}]\n\
271 output appended data as the file grows;\n\
272 an absent option argument means 'descriptor'\n\
273 -F same as --follow=name --retry\n\
274 "), stdout);
275 printf (_("\
276 -n, --lines=K output the last K lines, instead of the last %d;\n\
277 or use -n +K to output starting with the Kth\n\
278 --max-unchanged-stats=N\n\
279 with --follow=name, reopen a FILE which has not\n\
280 changed size after N (default %d) iterations\n\
281 to see if it has been unlinked or renamed\n\
282 (this is the usual case of rotated log files);\n\
283 with inotify, this option is rarely useful\n\
285 DEFAULT_N_LINES,
286 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
288 fputs (_("\
289 --pid=PID with -f, terminate after process ID, PID dies\n\
290 -q, --quiet, --silent never output headers giving file names\n\
291 --retry keep trying to open a file if it is inaccessible\n\
292 "), stdout);
293 fputs (_("\
294 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
295 (default 1.0) between iterations;\n\
296 with inotify and --pid=P, check process P at\n\
297 least once every N seconds\n\
298 -v, --verbose always output headers giving file names\n\
299 "), stdout);
300 fputs (HELP_OPTION_DESCRIPTION, stdout);
301 fputs (VERSION_OPTION_DESCRIPTION, stdout);
302 fputs (_("\
304 If the first character of K (the number of bytes or lines) is a '+',\n\
305 print beginning with the Kth item from the start of each file, otherwise,\n\
306 print the last K items in the file. K may have a multiplier suffix:\n\
307 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
308 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
310 "), stdout);
311 fputs (_("\
312 With --follow (-f), tail defaults to following the file descriptor, which\n\
313 means that even if a tail'ed file is renamed, tail will continue to track\n\
314 its end. This default behavior is not desirable when you really want to\n\
315 track the actual name of the file, not the file descriptor (e.g., log\n\
316 rotation). Use --follow=name in that case. That causes tail to track the\n\
317 named file in a way that accommodates renaming, removal and creation.\n\
318 "), stdout);
319 emit_ancillary_info (PROGRAM_NAME);
321 exit (status);
324 static bool
325 valid_file_spec (struct File_spec const *f)
327 /* Exactly one of the following subexpressions must be true. */
328 return ((f->fd == -1) ^ (f->errnum == 0));
331 static char const *
332 pretty_name (struct File_spec const *f)
334 return (STREQ (f->name, "-") ? _("standard input") : f->name);
337 /* Record a file F with descriptor FD, size SIZE, status ST, and
338 blocking status BLOCKING. */
340 static void
341 record_open_fd (struct File_spec *f, int fd,
342 off_t size, struct stat const *st,
343 int blocking)
345 f->fd = fd;
346 f->size = size;
347 f->mtime = get_stat_mtime (st);
348 f->dev = st->st_dev;
349 f->ino = st->st_ino;
350 f->mode = st->st_mode;
351 f->blocking = blocking;
352 f->n_unchanged_stats = 0;
353 f->ignore = false;
356 /* Close the file with descriptor FD and name FILENAME. */
358 static void
359 close_fd (int fd, const char *filename)
361 if (fd != -1 && fd != STDIN_FILENO && close (fd))
363 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
367 static void
368 write_header (const char *pretty_filename)
370 static bool first_file = true;
372 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
373 first_file = false;
376 /* Write N_BYTES from BUFFER to stdout.
377 Exit immediately on error with a single diagnostic. */
379 static void
380 xwrite_stdout (char const *buffer, size_t n_bytes)
382 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) < n_bytes)
384 clearerr (stdout); /* To avoid redundant close_stdout diagnostic. */
385 error (EXIT_FAILURE, errno, _("error writing %s"),
386 quote ("standard output"));
390 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
391 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
392 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
393 Return the number of bytes read from the file. */
395 static uintmax_t
396 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
398 uintmax_t n_written;
399 uintmax_t n_remaining = n_bytes;
401 n_written = 0;
402 while (1)
404 char buffer[BUFSIZ];
405 size_t n = MIN (n_remaining, BUFSIZ);
406 size_t bytes_read = safe_read (fd, buffer, n);
407 if (bytes_read == SAFE_READ_ERROR)
409 if (errno != EAGAIN)
410 error (EXIT_FAILURE, errno, _("error reading %s"),
411 quote (pretty_filename));
412 break;
414 if (bytes_read == 0)
415 break;
416 xwrite_stdout (buffer, bytes_read);
417 n_written += bytes_read;
418 if (n_bytes != COPY_TO_EOF)
420 n_remaining -= bytes_read;
421 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
422 break;
426 return n_written;
429 /* Call lseek with the specified arguments, where file descriptor FD
430 corresponds to the file, FILENAME.
431 Give a diagnostic and exit nonzero if lseek fails.
432 Otherwise, return the resulting offset. */
434 static off_t
435 xlseek (int fd, off_t offset, int whence, char const *filename)
437 off_t new_offset = lseek (fd, offset, whence);
438 char buf[INT_BUFSIZE_BOUND (offset)];
439 char *s;
441 if (0 <= new_offset)
442 return new_offset;
444 s = offtostr (offset, buf);
445 switch (whence)
447 case SEEK_SET:
448 error (0, errno, _("%s: cannot seek to offset %s"),
449 filename, s);
450 break;
451 case SEEK_CUR:
452 error (0, errno, _("%s: cannot seek to relative offset %s"),
453 filename, s);
454 break;
455 case SEEK_END:
456 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
457 filename, s);
458 break;
459 default:
460 abort ();
463 exit (EXIT_FAILURE);
466 /* Print the last N_LINES lines from the end of file FD.
467 Go backward through the file, reading 'BUFSIZ' bytes at a time (except
468 probably the first), until we hit the start of the file or have
469 read NUMBER newlines.
470 START_POS is the starting position of the read pointer for the file
471 associated with FD (may be nonzero).
472 END_POS is the file offset of EOF (one larger than offset of last byte).
473 Return true if successful. */
475 static bool
476 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
477 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
479 char buffer[BUFSIZ];
480 size_t bytes_read;
481 off_t pos = end_pos;
483 if (n_lines == 0)
484 return true;
486 /* Set 'bytes_read' to the size of the last, probably partial, buffer;
487 0 < 'bytes_read' <= 'BUFSIZ'. */
488 bytes_read = (pos - start_pos) % BUFSIZ;
489 if (bytes_read == 0)
490 bytes_read = BUFSIZ;
491 /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
492 reads will be on block boundaries, which might increase efficiency. */
493 pos -= bytes_read;
494 xlseek (fd, pos, SEEK_SET, pretty_filename);
495 bytes_read = safe_read (fd, buffer, bytes_read);
496 if (bytes_read == SAFE_READ_ERROR)
498 error (0, errno, _("error reading %s"), quote (pretty_filename));
499 return false;
501 *read_pos = pos + bytes_read;
503 /* Count the incomplete line on files that don't end with a newline. */
504 if (bytes_read && buffer[bytes_read - 1] != '\n')
505 --n_lines;
509 /* Scan backward, counting the newlines in this bufferfull. */
511 size_t n = bytes_read;
512 while (n)
514 char const *nl;
515 nl = memrchr (buffer, '\n', n);
516 if (nl == NULL)
517 break;
518 n = nl - buffer;
519 if (n_lines-- == 0)
521 /* If this newline isn't the last character in the buffer,
522 output the part that is after it. */
523 if (n != bytes_read - 1)
524 xwrite_stdout (nl + 1, bytes_read - (n + 1));
525 *read_pos += dump_remainder (pretty_filename, fd,
526 end_pos - (pos + bytes_read));
527 return true;
531 /* Not enough newlines in that bufferfull. */
532 if (pos == start_pos)
534 /* Not enough lines in the file; print everything from
535 start_pos to the end. */
536 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
537 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
538 end_pos);
539 return true;
541 pos -= BUFSIZ;
542 xlseek (fd, pos, SEEK_SET, pretty_filename);
544 bytes_read = safe_read (fd, buffer, BUFSIZ);
545 if (bytes_read == SAFE_READ_ERROR)
547 error (0, errno, _("error reading %s"), quote (pretty_filename));
548 return false;
551 *read_pos = pos + bytes_read;
553 while (bytes_read > 0);
555 return true;
558 /* Print the last N_LINES lines from the end of the standard input,
559 open for reading as pipe FD.
560 Buffer the text as a linked list of LBUFFERs, adding them as needed.
561 Return true if successful. */
563 static bool
564 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
565 uintmax_t *read_pos)
567 struct linebuffer
569 char buffer[BUFSIZ];
570 size_t nbytes;
571 size_t nlines;
572 struct linebuffer *next;
574 typedef struct linebuffer LBUFFER;
575 LBUFFER *first, *last, *tmp;
576 size_t total_lines = 0; /* Total number of newlines in all buffers. */
577 bool ok = true;
578 size_t n_read; /* Size in bytes of most recent read */
580 first = last = xmalloc (sizeof (LBUFFER));
581 first->nbytes = first->nlines = 0;
582 first->next = NULL;
583 tmp = xmalloc (sizeof (LBUFFER));
585 /* Input is always read into a fresh buffer. */
586 while (1)
588 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
589 if (n_read == 0 || n_read == SAFE_READ_ERROR)
590 break;
591 tmp->nbytes = n_read;
592 *read_pos += n_read;
593 tmp->nlines = 0;
594 tmp->next = NULL;
596 /* Count the number of newlines just read. */
598 char const *buffer_end = tmp->buffer + n_read;
599 char const *p = tmp->buffer;
600 while ((p = memchr (p, '\n', buffer_end - p)))
602 ++p;
603 ++tmp->nlines;
606 total_lines += tmp->nlines;
608 /* If there is enough room in the last buffer read, just append the new
609 one to it. This is because when reading from a pipe, 'n_read' can
610 often be very small. */
611 if (tmp->nbytes + last->nbytes < BUFSIZ)
613 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
614 last->nbytes += tmp->nbytes;
615 last->nlines += tmp->nlines;
617 else
619 /* If there's not enough room, link the new buffer onto the end of
620 the list, then either free up the oldest buffer for the next
621 read if that would leave enough lines, or else malloc a new one.
622 Some compaction mechanism is possible but probably not
623 worthwhile. */
624 last = last->next = tmp;
625 if (total_lines - first->nlines > n_lines)
627 tmp = first;
628 total_lines -= first->nlines;
629 first = first->next;
631 else
632 tmp = xmalloc (sizeof (LBUFFER));
636 free (tmp);
638 if (n_read == SAFE_READ_ERROR)
640 error (0, errno, _("error reading %s"), quote (pretty_filename));
641 ok = false;
642 goto free_lbuffers;
645 /* If the file is empty, then bail out. */
646 if (last->nbytes == 0)
647 goto free_lbuffers;
649 /* This prevents a core dump when the pipe contains no newlines. */
650 if (n_lines == 0)
651 goto free_lbuffers;
653 /* Count the incomplete line on files that don't end with a newline. */
654 if (last->buffer[last->nbytes - 1] != '\n')
656 ++last->nlines;
657 ++total_lines;
660 /* Run through the list, printing lines. First, skip over unneeded
661 buffers. */
662 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
663 total_lines -= tmp->nlines;
665 /* Find the correct beginning, then print the rest of the file. */
667 char const *beg = tmp->buffer;
668 char const *buffer_end = tmp->buffer + tmp->nbytes;
669 if (total_lines > n_lines)
671 /* Skip 'total_lines' - 'n_lines' newlines. We made sure that
672 'total_lines' - 'n_lines' <= 'tmp->nlines'. */
673 size_t j;
674 for (j = total_lines - n_lines; j; --j)
676 beg = memchr (beg, '\n', buffer_end - beg);
677 assert (beg);
678 ++beg;
682 xwrite_stdout (beg, buffer_end - beg);
685 for (tmp = tmp->next; tmp; tmp = tmp->next)
686 xwrite_stdout (tmp->buffer, tmp->nbytes);
688 free_lbuffers:
689 while (first)
691 tmp = first->next;
692 free (first);
693 first = tmp;
695 return ok;
698 /* Print the last N_BYTES characters from the end of pipe FD.
699 This is a stripped down version of pipe_lines.
700 Return true if successful. */
702 static bool
703 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
704 uintmax_t *read_pos)
706 struct charbuffer
708 char buffer[BUFSIZ];
709 size_t nbytes;
710 struct charbuffer *next;
712 typedef struct charbuffer CBUFFER;
713 CBUFFER *first, *last, *tmp;
714 size_t i; /* Index into buffers. */
715 size_t total_bytes = 0; /* Total characters in all buffers. */
716 bool ok = true;
717 size_t n_read;
719 first = last = xmalloc (sizeof (CBUFFER));
720 first->nbytes = 0;
721 first->next = NULL;
722 tmp = xmalloc (sizeof (CBUFFER));
724 /* Input is always read into a fresh buffer. */
725 while (1)
727 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
728 if (n_read == 0 || n_read == SAFE_READ_ERROR)
729 break;
730 *read_pos += n_read;
731 tmp->nbytes = n_read;
732 tmp->next = NULL;
734 total_bytes += tmp->nbytes;
735 /* If there is enough room in the last buffer read, just append the new
736 one to it. This is because when reading from a pipe, 'nbytes' can
737 often be very small. */
738 if (tmp->nbytes + last->nbytes < BUFSIZ)
740 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
741 last->nbytes += tmp->nbytes;
743 else
745 /* If there's not enough room, link the new buffer onto the end of
746 the list, then either free up the oldest buffer for the next
747 read if that would leave enough characters, or else malloc a new
748 one. Some compaction mechanism is possible but probably not
749 worthwhile. */
750 last = last->next = tmp;
751 if (total_bytes - first->nbytes > n_bytes)
753 tmp = first;
754 total_bytes -= first->nbytes;
755 first = first->next;
757 else
759 tmp = xmalloc (sizeof (CBUFFER));
764 free (tmp);
766 if (n_read == SAFE_READ_ERROR)
768 error (0, errno, _("error reading %s"), quote (pretty_filename));
769 ok = false;
770 goto free_cbuffers;
773 /* Run through the list, printing characters. First, skip over unneeded
774 buffers. */
775 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
776 total_bytes -= tmp->nbytes;
778 /* Find the correct beginning, then print the rest of the file.
779 We made sure that 'total_bytes' - 'n_bytes' <= 'tmp->nbytes'. */
780 if (total_bytes > n_bytes)
781 i = total_bytes - n_bytes;
782 else
783 i = 0;
784 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
786 for (tmp = tmp->next; tmp; tmp = tmp->next)
787 xwrite_stdout (tmp->buffer, tmp->nbytes);
789 free_cbuffers:
790 while (first)
792 tmp = first->next;
793 free (first);
794 first = tmp;
796 return ok;
799 /* Skip N_BYTES characters from the start of pipe FD, and print
800 any extra characters that were read beyond that.
801 Return 1 on error, 0 if ok, -1 if EOF. */
803 static int
804 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
805 uintmax_t *read_pos)
807 char buffer[BUFSIZ];
809 while (0 < n_bytes)
811 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
812 if (bytes_read == 0)
813 return -1;
814 if (bytes_read == SAFE_READ_ERROR)
816 error (0, errno, _("error reading %s"), quote (pretty_filename));
817 return 1;
819 *read_pos += bytes_read;
820 if (bytes_read <= n_bytes)
821 n_bytes -= bytes_read;
822 else
824 size_t n_remaining = bytes_read - n_bytes;
825 if (n_remaining)
826 xwrite_stdout (&buffer[n_bytes], n_remaining);
827 break;
831 return 0;
834 /* Skip N_LINES lines at the start of file or pipe FD, and print
835 any extra characters that were read beyond that.
836 Return 1 on error, 0 if ok, -1 if EOF. */
838 static int
839 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
840 uintmax_t *read_pos)
842 if (n_lines == 0)
843 return 0;
845 while (1)
847 char buffer[BUFSIZ];
848 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
849 if (bytes_read == 0) /* EOF */
850 return -1;
851 if (bytes_read == SAFE_READ_ERROR) /* error */
853 error (0, errno, _("error reading %s"), quote (pretty_filename));
854 return 1;
857 char *buffer_end = buffer + bytes_read;
859 *read_pos += bytes_read;
861 char *p = buffer;
862 while ((p = memchr (p, '\n', buffer_end - p)))
864 ++p;
865 if (--n_lines == 0)
867 if (p < buffer_end)
868 xwrite_stdout (p, buffer_end - p);
869 return 0;
875 #if HAVE_INOTIFY
876 /* Without inotify support, always return false. Otherwise, return false
877 when FD is open on a file known to reside on a local file system.
878 If fstatfs fails, give a diagnostic and return true.
879 If fstatfs cannot be called, return true. */
880 static bool
881 fremote (int fd, const char *name)
883 bool remote = true; /* be conservative (poll by default). */
885 # if HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE && defined __linux__
886 struct statfs buf;
887 int err = fstatfs (fd, &buf);
888 if (err != 0)
890 /* On at least linux-2.6.38, fstatfs fails with ENOSYS when FD
891 is open on a pipe. Treat that like a remote file. */
892 if (errno != ENOSYS)
893 error (0, errno, _("cannot determine location of %s. "
894 "reverting to polling"), quote (name));
896 else
898 switch (is_local_fs_type (buf.f_type))
900 case 0:
901 break;
902 case -1:
904 unsigned long int fs_type = buf.f_type;
905 error (0, 0, _("unrecognized file system type 0x%08lx for %s. "
906 "please report this to %s. reverting to polling"),
907 fs_type, quote (name), PACKAGE_BUGREPORT);
908 /* Treat as "remote", so caller polls. */
910 break;
911 case 1:
912 remote = false;
913 break;
914 default:
915 assert (!"unexpected return value from is_local_fs_type");
918 # endif
920 return remote;
922 #else
923 /* Without inotify support, whether a file is remote is irrelevant.
924 Always return "false" in that case. */
925 # define fremote(fd, name) false
926 #endif
928 /* open/fstat F->name and handle changes. */
929 static void
930 recheck (struct File_spec *f, bool blocking)
932 struct stat new_stats;
933 bool ok = true;
934 bool is_stdin = (STREQ (f->name, "-"));
935 bool was_tailable = f->tailable;
936 int prev_errnum = f->errnum;
937 bool new_file;
938 int fd = (is_stdin
939 ? STDIN_FILENO
940 : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
942 assert (valid_file_spec (f));
944 /* If the open fails because the file doesn't exist,
945 then mark the file as not tailable. */
946 f->tailable = !(reopen_inaccessible_files && fd == -1);
948 if (! disable_inotify && ! lstat (f->name, &new_stats)
949 && S_ISLNK (new_stats.st_mode))
951 /* Diagnose the edge case where a regular file is changed
952 to a symlink. We avoid inotify with symlinks since
953 it's awkward to match between symlink name and target. */
954 ok = false;
955 f->errnum = -1;
956 f->ignore = true;
958 error (0, 0, _("%s has been replaced with a symbolic link. "
959 "giving up on this name"), quote (pretty_name (f)));
961 else if (fd == -1 || fstat (fd, &new_stats) < 0)
963 ok = false;
964 f->errnum = errno;
965 if (!f->tailable)
967 if (was_tailable)
969 /* FIXME-maybe: detect the case in which the file first becomes
970 unreadable (perms), and later becomes readable again and can
971 be seen to be the same file (dev/ino). Otherwise, tail prints
972 the entire contents of the file when it becomes readable. */
973 error (0, f->errnum, _("%s has become inaccessible"),
974 quote (pretty_name (f)));
976 else
978 /* say nothing... it's still not tailable */
981 else if (prev_errnum != errno)
983 error (0, errno, "%s", pretty_name (f));
986 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
988 ok = false;
989 f->errnum = -1;
990 error (0, 0, _("%s has been replaced with an untailable file;\
991 giving up on this name"),
992 quote (pretty_name (f)));
993 f->ignore = true;
995 else if (!disable_inotify && fremote (fd, pretty_name (f)))
997 ok = false;
998 f->errnum = -1;
999 error (0, 0, _("%s has been replaced with a remote file. "
1000 "giving up on this name"), quote (pretty_name (f)));
1001 f->ignore = true;
1002 f->remote = true;
1004 else
1006 f->errnum = 0;
1009 new_file = false;
1010 if (!ok)
1012 close_fd (fd, pretty_name (f));
1013 close_fd (f->fd, pretty_name (f));
1014 f->fd = -1;
1016 else if (prev_errnum && prev_errnum != ENOENT)
1018 new_file = true;
1019 assert (f->fd == -1);
1020 error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
1022 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
1024 new_file = true;
1025 if (f->fd == -1)
1027 error (0, 0,
1028 _("%s has appeared; following new file"),
1029 quote (pretty_name (f)));
1031 else
1033 /* Close the old one. */
1034 close_fd (f->fd, pretty_name (f));
1036 /* File has been replaced (e.g., via log rotation) --
1037 tail the new one. */
1038 error (0, 0,
1039 _("%s has been replaced; following new file"),
1040 quote (pretty_name (f)));
1043 else
1045 if (f->fd == -1)
1047 /* This happens when one iteration finds the file missing,
1048 then the preceding <dev,inode> pair is reused as the
1049 file is recreated. */
1050 new_file = true;
1052 else
1054 close_fd (fd, pretty_name (f));
1058 /* FIXME: When a log is rotated, daemons tend to log to the
1059 old file descriptor until the new file is present and
1060 the daemon is sent a signal. Therefore tail may miss entries
1061 being written to the old file. Perhaps we should keep
1062 the older file open and continue to monitor it until
1063 data is written to a new file. */
1064 if (new_file)
1066 /* Start at the beginning of the file. */
1067 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
1068 xlseek (fd, 0, SEEK_SET, pretty_name (f));
1072 /* Return true if any of the N_FILES files in F are live, i.e., have
1073 open file descriptors, or should be checked again (see --retry).
1074 When following descriptors, checking should only continue when any
1075 of the files is not yet ignored. */
1077 static bool
1078 any_live_files (const struct File_spec *f, size_t n_files)
1080 size_t i;
1082 if (reopen_inaccessible_files && follow_mode == Follow_name)
1083 return true; /* continue following for -F option */
1085 for (i = 0; i < n_files; i++)
1087 if (0 <= f[i].fd)
1089 return true;
1091 else
1093 if (reopen_inaccessible_files && follow_mode == Follow_descriptor)
1094 if (! f[i].ignore)
1095 return true;
1099 return false;
1102 /* Tail N_FILES files forever, or until killed.
1103 The pertinent information for each file is stored in an entry of F.
1104 Loop over each of them, doing an fstat to see if they have changed size,
1105 and an occasional open/fstat to see if any dev/ino pair has changed.
1106 If none of them have changed size in one iteration, sleep for a
1107 while and try again. Continue until the user interrupts us. */
1109 static void
1110 tail_forever (struct File_spec *f, size_t n_files, double sleep_interval)
1112 /* Use blocking I/O as an optimization, when it's easy. */
1113 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
1114 && n_files == 1 && ! S_ISREG (f[0].mode));
1115 size_t last;
1116 bool writer_is_dead = false;
1118 last = n_files - 1;
1120 while (1)
1122 size_t i;
1123 bool any_input = false;
1125 for (i = 0; i < n_files; i++)
1127 int fd;
1128 char const *name;
1129 mode_t mode;
1130 struct stat stats;
1131 uintmax_t bytes_read;
1133 if (f[i].ignore)
1134 continue;
1136 if (f[i].fd < 0)
1138 recheck (&f[i], blocking);
1139 continue;
1142 fd = f[i].fd;
1143 name = pretty_name (&f[i]);
1144 mode = f[i].mode;
1146 if (f[i].blocking != blocking)
1148 int old_flags = fcntl (fd, F_GETFL);
1149 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1150 if (old_flags < 0
1151 || (new_flags != old_flags
1152 && fcntl (fd, F_SETFL, new_flags) == -1))
1154 /* Don't update f[i].blocking if fcntl fails. */
1155 if (S_ISREG (f[i].mode) && errno == EPERM)
1157 /* This happens when using tail -f on a file with
1158 the append-only attribute. */
1160 else
1161 error (EXIT_FAILURE, errno,
1162 _("%s: cannot change nonblocking mode"), name);
1164 else
1165 f[i].blocking = blocking;
1168 if (!f[i].blocking)
1170 if (fstat (fd, &stats) != 0)
1172 f[i].fd = -1;
1173 f[i].errnum = errno;
1174 error (0, errno, "%s", name);
1175 close (fd); /* ignore failure */
1176 continue;
1179 if (f[i].mode == stats.st_mode
1180 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1181 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1183 if ((max_n_unchanged_stats_between_opens
1184 <= f[i].n_unchanged_stats++)
1185 && follow_mode == Follow_name)
1187 recheck (&f[i], f[i].blocking);
1188 f[i].n_unchanged_stats = 0;
1190 continue;
1193 /* This file has changed. Print out what we can, and
1194 then keep looping. */
1196 f[i].mtime = get_stat_mtime (&stats);
1197 f[i].mode = stats.st_mode;
1199 /* reset counter */
1200 f[i].n_unchanged_stats = 0;
1202 /* XXX: This is only a heuristic, as the file may have also
1203 been truncated and written to if st_size >= size
1204 (in which case we ignore new data <= size). */
1205 if (S_ISREG (mode) && stats.st_size < f[i].size)
1207 error (0, 0, _("%s: file truncated"), name);
1208 /* Assume the file was truncated to 0,
1209 and therefore output all "new" data. */
1210 xlseek (fd, 0, SEEK_SET, name);
1211 f[i].size = 0;
1214 if (i != last)
1216 if (print_headers)
1217 write_header (name);
1218 last = i;
1222 bytes_read = dump_remainder (name, fd,
1223 (f[i].blocking
1224 ? COPY_A_BUFFER : COPY_TO_EOF));
1225 any_input |= (bytes_read != 0);
1226 f[i].size += bytes_read;
1229 if (! any_live_files (f, n_files))
1231 error (0, 0, _("no files remaining"));
1232 break;
1235 if ((!any_input || blocking) && fflush (stdout) != 0)
1236 error (EXIT_FAILURE, errno, _("write error"));
1238 /* If nothing was read, sleep and/or check for dead writers. */
1239 if (!any_input)
1241 if (writer_is_dead)
1242 break;
1244 /* Once the writer is dead, read the files once more to
1245 avoid a race condition. */
1246 writer_is_dead = (pid != 0
1247 && kill (pid, 0) != 0
1248 /* Handle the case in which you cannot send a
1249 signal to the writer, so kill fails and sets
1250 errno to EPERM. */
1251 && errno != EPERM);
1253 if (!writer_is_dead && xnanosleep (sleep_interval))
1254 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1260 #if HAVE_INOTIFY
1262 /* Return true if any of the N_FILES files in F is remote, i.e., has
1263 an open file descriptor and is on a network file system. */
1265 static bool
1266 any_remote_file (const struct File_spec *f, size_t n_files)
1268 size_t i;
1270 for (i = 0; i < n_files; i++)
1271 if (0 <= f[i].fd && f[i].remote)
1272 return true;
1273 return false;
1276 /* Return true if any of the N_FILES files in F is a symlink.
1277 Note we don't worry about the edge case where "-" exists,
1278 since that will have the same consequences for inotify,
1279 which is the only context this function is currently used. */
1281 static bool
1282 any_symlinks (const struct File_spec *f, size_t n_files)
1284 size_t i;
1286 struct stat st;
1287 for (i = 0; i < n_files; i++)
1288 if (lstat (f[i].name, &st) == 0 && S_ISLNK (st.st_mode))
1289 return true;
1290 return false;
1293 /* Return true if any of the N_FILES files in F represents
1294 stdin and is tailable. */
1296 static bool
1297 tailable_stdin (const struct File_spec *f, size_t n_files)
1299 size_t i;
1301 for (i = 0; i < n_files; i++)
1302 if (!f[i].ignore && STREQ (f[i].name, "-"))
1303 return true;
1304 return false;
1307 static size_t
1308 wd_hasher (const void *entry, size_t tabsize)
1310 const struct File_spec *spec = entry;
1311 return spec->wd % tabsize;
1314 static bool
1315 wd_comparator (const void *e1, const void *e2)
1317 const struct File_spec *spec1 = e1;
1318 const struct File_spec *spec2 = e2;
1319 return spec1->wd == spec2->wd;
1322 /* Output (new) data for FSPEC->fd. */
1323 static void
1324 check_fspec (struct File_spec *fspec, int wd, int *prev_wd)
1326 struct stat stats;
1327 char const *name;
1329 if (fspec->fd == -1)
1330 return;
1332 name = pretty_name (fspec);
1334 if (fstat (fspec->fd, &stats) != 0)
1336 fspec->errnum = errno;
1337 close_fd (fspec->fd, name);
1338 fspec->fd = -1;
1339 return;
1342 /* XXX: This is only a heuristic, as the file may have also
1343 been truncated and written to if st_size >= size
1344 (in which case we ignore new data <= size).
1345 Though in the inotify case it's more likely we'll get
1346 separate events for truncate() and write(). */
1347 if (S_ISREG (fspec->mode) && stats.st_size < fspec->size)
1349 error (0, 0, _("%s: file truncated"), name);
1350 *prev_wd = wd;
1351 xlseek (fspec->fd, 0, SEEK_SET, name);
1352 fspec->size = 0;
1354 else if (S_ISREG (fspec->mode) && stats.st_size == fspec->size
1355 && timespec_cmp (fspec->mtime, get_stat_mtime (&stats)) == 0)
1356 return;
1358 if (wd != *prev_wd)
1360 if (print_headers)
1361 write_header (name);
1362 *prev_wd = wd;
1365 uintmax_t bytes_read = dump_remainder (name, fspec->fd, COPY_TO_EOF);
1366 fspec->size += bytes_read;
1368 if (fflush (stdout) != 0)
1369 error (EXIT_FAILURE, errno, _("write error"));
1372 /* Attempt to tail N_FILES files forever, or until killed.
1373 Check modifications using the inotify events system.
1374 Return false on error, or true to revert to polling. */
1375 static bool
1376 tail_forever_inotify (int wd, struct File_spec *f, size_t n_files,
1377 double sleep_interval)
1379 # if TAIL_TEST_SLEEP
1380 /* Delay between open() and inotify_add_watch()
1381 to help trigger different cases. */
1382 xnanosleep (1000000);
1383 # endif
1384 unsigned int max_realloc = 3;
1386 /* Map an inotify watch descriptor to the name of the file it's watching. */
1387 Hash_table *wd_to_name;
1389 bool found_watchable_file = false;
1390 bool tailed_but_unwatchable = false;
1391 bool found_unwatchable_dir = false;
1392 bool no_inotify_resources = false;
1393 bool writer_is_dead = false;
1394 int prev_wd;
1395 size_t evlen = 0;
1396 char *evbuf;
1397 size_t evbuf_off = 0;
1398 size_t len = 0;
1400 wd_to_name = hash_initialize (n_files, NULL, wd_hasher, wd_comparator, NULL);
1401 if (! wd_to_name)
1402 xalloc_die ();
1404 /* The events mask used with inotify on files (not directories). */
1405 uint32_t inotify_wd_mask = IN_MODIFY;
1406 /* TODO: Perhaps monitor these events in Follow_descriptor mode also,
1407 to tag reported file names with "deleted", "moved" etc. */
1408 if (follow_mode == Follow_name)
1409 inotify_wd_mask |= (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF);
1411 /* Add an inotify watch for each watched file. If -F is specified then watch
1412 its parent directory too, in this way when they re-appear we can add them
1413 again to the watch list. */
1414 size_t i;
1415 for (i = 0; i < n_files; i++)
1417 if (!f[i].ignore)
1419 size_t fnlen = strlen (f[i].name);
1420 if (evlen < fnlen)
1421 evlen = fnlen;
1423 f[i].wd = -1;
1425 if (follow_mode == Follow_name)
1427 size_t dirlen = dir_len (f[i].name);
1428 char prev = f[i].name[dirlen];
1429 f[i].basename_start = last_component (f[i].name) - f[i].name;
1431 f[i].name[dirlen] = '\0';
1433 /* It's fine to add the same directory more than once.
1434 In that case the same watch descriptor is returned. */
1435 f[i].parent_wd = inotify_add_watch (wd, dirlen ? f[i].name : ".",
1436 (IN_CREATE | IN_MOVED_TO
1437 | IN_ATTRIB));
1439 f[i].name[dirlen] = prev;
1441 if (f[i].parent_wd < 0)
1443 if (errno != ENOSPC) /* suppress confusing error. */
1444 error (0, errno, _("cannot watch parent directory of %s"),
1445 quote (f[i].name));
1446 else
1447 error (0, 0, _("inotify resources exhausted"));
1448 found_unwatchable_dir = true;
1449 /* We revert to polling below. Note invalid uses
1450 of the inotify API will still be diagnosed. */
1451 break;
1455 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1457 if (f[i].wd < 0)
1459 if (f[i].fd != -1) /* already tailed. */
1460 tailed_but_unwatchable = true;
1461 if (errno == ENOSPC || errno == ENOMEM)
1463 no_inotify_resources = true;
1464 error (0, 0, _("inotify resources exhausted"));
1465 break;
1467 else if (errno != f[i].errnum)
1468 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1469 continue;
1472 if (hash_insert (wd_to_name, &(f[i])) == NULL)
1473 xalloc_die ();
1475 found_watchable_file = true;
1479 /* Linux kernel 2.6.24 at least has a bug where eventually, ENOSPC is always
1480 returned by inotify_add_watch. In any case we should revert to polling
1481 when there are no inotify resources. Also a specified directory may not
1482 be currently present or accessible, so revert to polling. Also an already
1483 tailed but unwatchable due rename/unlink race, should also revert. */
1484 if (no_inotify_resources || found_unwatchable_dir
1485 || (follow_mode == Follow_descriptor && tailed_but_unwatchable))
1487 hash_free (wd_to_name);
1489 errno = 0;
1490 return true;
1492 if (follow_mode == Follow_descriptor && !found_watchable_file)
1493 return false;
1495 prev_wd = f[n_files - 1].wd;
1497 /* Check files again. New files or data can be available since last time we
1498 checked and before they are watched by inotify. */
1499 for (i = 0; i < n_files; i++)
1501 if (! f[i].ignore)
1503 /* check for new files. */
1504 if (follow_mode == Follow_name)
1505 recheck (&(f[i]), false);
1506 else if (f[i].fd != -1)
1508 /* If the file was replaced in the small window since we tailed,
1509 then assume the watch is on the wrong item (different to
1510 that we've already produced output for), and so revert to
1511 polling the original descriptor. */
1512 struct stat stats;
1514 if (stat (f[i].name, &stats) == 0
1515 && (f[i].dev != stats.st_dev || f[i].ino != stats.st_ino))
1517 error (0, errno, _("%s was replaced"),
1518 quote (pretty_name (&(f[i]))));
1519 hash_free (wd_to_name);
1521 errno = 0;
1522 return true;
1526 /* check for new data. */
1527 check_fspec (&f[i], f[i].wd, &prev_wd);
1531 evlen += sizeof (struct inotify_event) + 1;
1532 evbuf = xmalloc (evlen);
1534 /* Wait for inotify events and handle them. Events on directories
1535 ensure that watched files can be re-added when following by name.
1536 This loop blocks on the 'safe_read' call until a new event is notified.
1537 But when --pid=P is specified, tail usually waits via the select. */
1538 while (1)
1540 struct File_spec *fspec;
1541 struct inotify_event *ev;
1542 void *void_ev;
1544 /* When following by name without --retry, and the last file has
1545 been unlinked or renamed-away, diagnose it and return. */
1546 if (follow_mode == Follow_name
1547 && ! reopen_inaccessible_files
1548 && hash_get_n_entries (wd_to_name) == 0)
1550 error (0, 0, _("no files remaining"));
1551 return false;
1554 /* When watching a PID, ensure that a read from WD will not block
1555 indefinitely. */
1556 if (pid)
1558 if (writer_is_dead)
1559 exit (EXIT_SUCCESS);
1561 writer_is_dead = (kill (pid, 0) != 0 && errno != EPERM);
1563 struct timeval delay; /* how long to wait for file changes. */
1564 if (writer_is_dead)
1565 delay.tv_sec = delay.tv_usec = 0;
1566 else
1568 delay.tv_sec = (time_t) sleep_interval;
1569 delay.tv_usec = 1000000 * (sleep_interval - delay.tv_sec);
1572 fd_set rfd;
1573 FD_ZERO (&rfd);
1574 FD_SET (wd, &rfd);
1576 int file_change = select (wd + 1, &rfd, NULL, NULL, &delay);
1578 if (file_change == 0)
1579 continue;
1580 else if (file_change == -1)
1581 error (EXIT_FAILURE, errno, _("error monitoring inotify event"));
1584 if (len <= evbuf_off)
1586 len = safe_read (wd, evbuf, evlen);
1587 evbuf_off = 0;
1589 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1590 is too small. */
1591 if ((len == 0 || (len == SAFE_READ_ERROR && errno == EINVAL))
1592 && max_realloc--)
1594 len = 0;
1595 evlen *= 2;
1596 evbuf = xrealloc (evbuf, evlen);
1597 continue;
1600 if (len == 0 || len == SAFE_READ_ERROR)
1601 error (EXIT_FAILURE, errno, _("error reading inotify event"));
1604 void_ev = evbuf + evbuf_off;
1605 ev = void_ev;
1606 evbuf_off += sizeof (*ev) + ev->len;
1608 if (ev->len) /* event on ev->name in watched directory. */
1610 size_t j;
1611 for (j = 0; j < n_files; j++)
1613 /* With N=hundreds of frequently-changing files, this O(N^2)
1614 process might be a problem. FIXME: use a hash table? */
1615 if (f[j].parent_wd == ev->wd
1616 && STREQ (ev->name, f[j].name + f[j].basename_start))
1617 break;
1620 /* It is not a watched file. */
1621 if (j == n_files)
1622 continue;
1624 fspec = &(f[j]);
1626 /* Adding the same inode again will look up any existing wd. */
1627 int new_wd = inotify_add_watch (wd, f[j].name, inotify_wd_mask);
1628 if (new_wd < 0)
1630 if (errno == ENOSPC || errno == ENOMEM)
1632 error (0, 0, _("inotify resources exhausted"));
1633 hash_free (wd_to_name);
1634 errno = 0;
1635 return true; /* revert to polling. */
1637 else
1639 /* Can get ENOENT for a dangling symlink for example. */
1640 error (0, errno, _("cannot watch %s"), quote (f[j].name));
1642 /* We'll continue below after removing the existing watch. */
1645 /* This will be false if only attributes of file change. */
1646 bool new_watch = fspec->wd < 0 || new_wd != fspec->wd;
1648 if (new_watch)
1650 if (0 <= fspec->wd)
1652 inotify_rm_watch (wd, fspec->wd);
1653 hash_delete (wd_to_name, fspec);
1656 fspec->wd = new_wd;
1658 if (new_wd == -1)
1659 continue;
1661 /* If the file was moved then inotify will use the source file wd
1662 for the destination file. Make sure the key is not present in
1663 the table. */
1664 struct File_spec *prev = hash_delete (wd_to_name, fspec);
1665 if (prev && prev != fspec)
1667 if (follow_mode == Follow_name)
1668 recheck (prev, false);
1669 prev->wd = -1;
1670 close_fd (prev->fd, pretty_name (prev));
1673 if (hash_insert (wd_to_name, fspec) == NULL)
1674 xalloc_die ();
1677 if (follow_mode == Follow_name)
1678 recheck (fspec, false);
1680 else
1682 struct File_spec key;
1683 key.wd = ev->wd;
1684 fspec = hash_lookup (wd_to_name, &key);
1687 if (! fspec)
1688 continue;
1690 if (ev->mask & (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF))
1692 /* Note for IN_MOVE_SELF (the file we're watching has
1693 been clobbered via a rename) we leave the watch
1694 in place since it may still be part of the set
1695 of watched names. */
1696 if (ev->mask & IN_DELETE_SELF)
1698 inotify_rm_watch (wd, fspec->wd);
1699 hash_delete (wd_to_name, fspec);
1702 recheck (fspec, false);
1704 continue;
1706 check_fspec (fspec, ev->wd, &prev_wd);
1709 #endif
1711 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1712 Return true if successful. */
1714 static bool
1715 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1716 uintmax_t *read_pos)
1718 struct stat stats;
1720 if (fstat (fd, &stats))
1722 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1723 return false;
1726 if (from_start)
1728 if ( ! presume_input_pipe
1729 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1731 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1732 *read_pos += n_bytes;
1734 else
1736 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1737 if (t)
1738 return t < 0;
1740 n_bytes = COPY_TO_EOF;
1742 else
1744 off_t end_pos = ((! presume_input_pipe && usable_st_size (&stats)
1745 && n_bytes <= OFF_T_MAX)
1746 ? stats.st_size : -1);
1747 if (end_pos <= ST_BLKSIZE (stats))
1748 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1749 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1750 if (current_pos < end_pos)
1752 off_t bytes_remaining = end_pos - current_pos;
1754 if (n_bytes < bytes_remaining)
1756 current_pos = end_pos - n_bytes;
1757 xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1760 *read_pos = current_pos;
1763 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1764 return true;
1767 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1768 Return true if successful. */
1770 static bool
1771 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1772 uintmax_t *read_pos)
1774 struct stat stats;
1776 if (fstat (fd, &stats))
1778 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1779 return false;
1782 if (from_start)
1784 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1785 if (t)
1786 return t < 0;
1787 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1789 else
1791 off_t start_pos = -1;
1792 off_t end_pos;
1794 /* Use file_lines only if FD refers to a regular file for
1795 which lseek (... SEEK_END) works. */
1796 if ( ! presume_input_pipe
1797 && S_ISREG (stats.st_mode)
1798 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1799 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1801 *read_pos = end_pos;
1802 if (end_pos != 0
1803 && ! file_lines (pretty_filename, fd, n_lines,
1804 start_pos, end_pos, read_pos))
1805 return false;
1807 else
1809 /* Under very unlikely circumstances, it is possible to reach
1810 this point after positioning the file pointer to end of file
1811 via the 'lseek (...SEEK_END)' above. In that case, reposition
1812 the file pointer back to start_pos before calling pipe_lines. */
1813 if (start_pos != -1)
1814 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1816 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1819 return true;
1822 /* Display the last N_UNITS units of file FILENAME, open for reading
1823 via FD. Set *READ_POS to the position of the input stream pointer.
1824 *READ_POS is usually the number of bytes read and corresponds to an
1825 offset from the beginning of a file. However, it may be larger than
1826 OFF_T_MAX (as for an input pipe), and may also be larger than the
1827 number of bytes read (when an input pointer is initially not at
1828 beginning of file), and may be far greater than the number of bytes
1829 actually read for an input file that is seekable.
1830 Return true if successful. */
1832 static bool
1833 tail (const char *filename, int fd, uintmax_t n_units,
1834 uintmax_t *read_pos)
1836 *read_pos = 0;
1837 if (count_lines)
1838 return tail_lines (filename, fd, n_units, read_pos);
1839 else
1840 return tail_bytes (filename, fd, n_units, read_pos);
1843 /* Display the last N_UNITS units of the file described by F.
1844 Return true if successful. */
1846 static bool
1847 tail_file (struct File_spec *f, uintmax_t n_units)
1849 int fd;
1850 bool ok;
1852 bool is_stdin = (STREQ (f->name, "-"));
1854 if (is_stdin)
1856 have_read_stdin = true;
1857 fd = STDIN_FILENO;
1858 if (O_BINARY && ! isatty (STDIN_FILENO))
1859 xfreopen (NULL, "rb", stdin);
1861 else
1862 fd = open (f->name, O_RDONLY | O_BINARY);
1864 f->tailable = !(reopen_inaccessible_files && fd == -1);
1866 if (fd == -1)
1868 if (forever)
1870 f->fd = -1;
1871 f->errnum = errno;
1872 f->ignore = false;
1873 f->ino = 0;
1874 f->dev = 0;
1876 error (0, errno, _("cannot open %s for reading"),
1877 quote (pretty_name (f)));
1878 ok = false;
1880 else
1882 uintmax_t read_pos;
1884 if (print_headers)
1885 write_header (pretty_name (f));
1886 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1887 if (forever)
1889 struct stat stats;
1891 #if TAIL_TEST_SLEEP
1892 /* Before the tail function provided 'read_pos', there was
1893 a race condition described in the URL below. This sleep
1894 call made the window big enough to exercise the problem. */
1895 xnanosleep (1);
1896 #endif
1897 f->errnum = ok - 1;
1898 if (fstat (fd, &stats) < 0)
1900 ok = false;
1901 f->errnum = errno;
1902 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1904 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1906 error (0, 0, _("%s: cannot follow end of this type of file;\
1907 giving up on this name"),
1908 pretty_name (f));
1909 ok = false;
1910 f->errnum = -1;
1911 f->ignore = true;
1914 if (!ok)
1916 close_fd (fd, pretty_name (f));
1917 f->fd = -1;
1919 else
1921 /* Note: we must use read_pos here, not stats.st_size,
1922 to avoid a race condition described by Ken Raeburn:
1923 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1924 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1925 f->remote = fremote (fd, pretty_name (f));
1928 else
1930 if (!is_stdin && close (fd))
1932 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1933 ok = false;
1938 return ok;
1941 /* If obsolete usage is allowed, and the command line arguments are of
1942 the obsolete form and the option string is well-formed, set
1943 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1944 return true. If the command line arguments are obviously incorrect
1945 (e.g., because obsolete usage is not allowed and the arguments are
1946 incorrect for non-obsolete usage), report an error and exit.
1947 Otherwise, return false and don't modify any parameter or global
1948 variable. */
1950 static bool
1951 parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1953 const char *p;
1954 const char *n_string;
1955 const char *n_string_end;
1956 bool obsolete_usage;
1957 int default_count = DEFAULT_N_LINES;
1958 bool t_from_start;
1959 bool t_count_lines = true;
1960 bool t_forever = false;
1962 /* With the obsolete form, there is one option string and at most
1963 one file argument. Watch out for "-" and "--", though. */
1964 if (! (argc == 2
1965 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1966 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1967 return false;
1969 obsolete_usage = (posix2_version () < 200112);
1970 p = argv[1];
1972 switch (*p++)
1974 default:
1975 return false;
1977 case '+':
1978 /* Leading "+" is a file name in the non-obsolete form. */
1979 if (!obsolete_usage)
1980 return false;
1982 t_from_start = true;
1983 break;
1985 case '-':
1986 /* In the non-obsolete form, "-" is standard input and "-c"
1987 requires an option-argument. The obsolete multidigit options
1988 are supported as a GNU extension even when conforming to
1989 POSIX 1003.1-2001, so don't complain about them. */
1990 if (!obsolete_usage && !p[p[0] == 'c'])
1991 return false;
1993 t_from_start = false;
1994 break;
1997 n_string = p;
1998 while (ISDIGIT (*p))
1999 p++;
2000 n_string_end = p;
2002 switch (*p)
2004 case 'b': default_count *= 512; /* Fall through. */
2005 case 'c': t_count_lines = false; /* Fall through. */
2006 case 'l': p++; break;
2009 if (*p == 'f')
2011 t_forever = true;
2012 ++p;
2015 if (*p)
2016 return false;
2018 if (n_string == n_string_end)
2019 *n_units = default_count;
2020 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
2021 & ~LONGINT_INVALID_SUFFIX_CHAR)
2022 != LONGINT_OK)
2024 error (EXIT_FAILURE, errno, "%s: %s", _("invalid number"),
2025 quote (argv[1]));
2028 /* Set globals. */
2029 from_start = t_from_start;
2030 count_lines = t_count_lines;
2031 forever = t_forever;
2033 return true;
2036 static void
2037 parse_options (int argc, char **argv,
2038 uintmax_t *n_units, enum header_mode *header_mode,
2039 double *sleep_interval)
2041 int c;
2043 while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789",
2044 long_options, NULL))
2045 != -1)
2047 switch (c)
2049 case 'F':
2050 forever = true;
2051 follow_mode = Follow_name;
2052 reopen_inaccessible_files = true;
2053 break;
2055 case 'c':
2056 case 'n':
2057 count_lines = (c == 'n');
2058 if (*optarg == '+')
2059 from_start = true;
2060 else if (*optarg == '-')
2061 ++optarg;
2063 *n_units = xdectoumax (optarg, 0, UINTMAX_MAX, "bkKmMGTPEZY0",
2064 count_lines
2065 ? _("invalid number of lines")
2066 : _("invalid number of bytes"), 0);
2067 break;
2069 case 'f':
2070 case LONG_FOLLOW_OPTION:
2071 forever = true;
2072 if (optarg == NULL)
2073 follow_mode = DEFAULT_FOLLOW_MODE;
2074 else
2075 follow_mode = XARGMATCH ("--follow", optarg,
2076 follow_mode_string, follow_mode_map);
2077 break;
2079 case RETRY_OPTION:
2080 reopen_inaccessible_files = true;
2081 break;
2083 case MAX_UNCHANGED_STATS_OPTION:
2084 /* --max-unchanged-stats=N */
2085 max_n_unchanged_stats_between_opens =
2086 xdectoumax (optarg, 0, UINTMAX_MAX, "",
2087 _("invalid maximum number of unchanged stats between opens"), 0);
2088 break;
2090 case DISABLE_INOTIFY_OPTION:
2091 disable_inotify = true;
2092 break;
2094 case PID_OPTION:
2095 pid = xdectoumax (optarg, 0, PID_T_MAX, "", _("invalid PID"), 0);
2096 break;
2098 case PRESUME_INPUT_PIPE_OPTION:
2099 presume_input_pipe = true;
2100 break;
2102 case 'q':
2103 *header_mode = never;
2104 break;
2106 case 's':
2108 double s;
2109 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
2110 error (EXIT_FAILURE, 0,
2111 _("invalid number of seconds: %s"), quote (optarg));
2112 *sleep_interval = s;
2114 break;
2116 case 'v':
2117 *header_mode = always;
2118 break;
2120 case_GETOPT_HELP_CHAR;
2122 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
2124 case '0': case '1': case '2': case '3': case '4':
2125 case '5': case '6': case '7': case '8': case '9':
2126 error (EXIT_FAILURE, 0,
2127 _("option used in invalid context -- %c"), c);
2129 default:
2130 usage (EXIT_FAILURE);
2134 if (reopen_inaccessible_files)
2136 if (!forever)
2138 reopen_inaccessible_files = false;
2139 error (0, 0, _("warning: --retry ignored; --retry is useful"
2140 " only when following"));
2142 else if (follow_mode == Follow_descriptor)
2143 error (0, 0, _("warning: --retry only effective for the initial open"));
2146 if (pid && !forever)
2147 error (0, 0,
2148 _("warning: PID ignored; --pid=PID is useful only when following"));
2149 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
2151 error (0, 0, _("warning: --pid=PID is not supported on this system"));
2152 pid = 0;
2156 /* Mark as '.ignore'd each member of F that corresponds to a
2157 pipe or fifo, and return the number of non-ignored members. */
2158 static size_t
2159 ignore_fifo_and_pipe (struct File_spec *f, size_t n_files)
2161 /* When there is no FILE operand and stdin is a pipe or FIFO
2162 POSIX requires that tail ignore the -f option.
2163 Since we allow multiple FILE operands, we extend that to say: with -f,
2164 ignore any "-" operand that corresponds to a pipe or FIFO. */
2165 size_t n_viable = 0;
2167 size_t i;
2168 for (i = 0; i < n_files; i++)
2170 bool is_a_fifo_or_pipe =
2171 (STREQ (f[i].name, "-")
2172 && !f[i].ignore
2173 && 0 <= f[i].fd
2174 && (S_ISFIFO (f[i].mode)
2175 || (HAVE_FIFO_PIPES != 1 && isapipe (f[i].fd))));
2176 if (is_a_fifo_or_pipe)
2177 f[i].ignore = true;
2178 else
2179 ++n_viable;
2182 return n_viable;
2186 main (int argc, char **argv)
2188 enum header_mode header_mode = multiple_files;
2189 bool ok = true;
2190 /* If from_start, the number of items to skip before printing; otherwise,
2191 the number of items at the end of the file to print. Although the type
2192 is signed, the value is never negative. */
2193 uintmax_t n_units = DEFAULT_N_LINES;
2194 size_t n_files;
2195 char **file;
2196 struct File_spec *F;
2197 size_t i;
2198 bool obsolete_option;
2200 /* The number of seconds to sleep between iterations.
2201 During one iteration, every file name or descriptor is checked to
2202 see if it has changed. */
2203 double sleep_interval = 1.0;
2205 initialize_main (&argc, &argv);
2206 set_program_name (argv[0]);
2207 setlocale (LC_ALL, "");
2208 bindtextdomain (PACKAGE, LOCALEDIR);
2209 textdomain (PACKAGE);
2211 atexit (close_stdout);
2213 have_read_stdin = false;
2215 count_lines = true;
2216 forever = from_start = print_headers = false;
2217 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
2218 argc -= obsolete_option;
2219 argv += obsolete_option;
2220 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
2222 /* To start printing with item N_UNITS from the start of the file, skip
2223 N_UNITS - 1 items. 'tail -n +0' is actually meaningless, but for Unix
2224 compatibility it's treated the same as 'tail -n +1'. */
2225 if (from_start)
2227 if (n_units)
2228 --n_units;
2231 IF_LINT (assert (0 <= argc));
2233 if (optind < argc)
2235 n_files = argc - optind;
2236 file = argv + optind;
2238 else
2240 static char *dummy_stdin = (char *) "-";
2241 n_files = 1;
2242 file = &dummy_stdin;
2246 bool found_hyphen = false;
2248 for (i = 0; i < n_files; i++)
2249 if (STREQ (file[i], "-"))
2250 found_hyphen = true;
2252 /* When following by name, there must be a name. */
2253 if (found_hyphen && follow_mode == Follow_name)
2254 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
2256 /* When following forever, warn if any file is '-'.
2257 This is only a warning, since tail's output (before a failing seek,
2258 and that from any non-stdin files) might still be useful. */
2259 if (forever && found_hyphen && isatty (STDIN_FILENO))
2260 error (0, 0, _("warning: following standard input"
2261 " indefinitely is ineffective"));
2264 /* Don't read anything if we'll never output anything. */
2265 if (! n_units && ! forever && ! from_start)
2266 return EXIT_SUCCESS;
2268 F = xnmalloc (n_files, sizeof *F);
2269 for (i = 0; i < n_files; i++)
2270 F[i].name = file[i];
2272 if (header_mode == always
2273 || (header_mode == multiple_files && n_files > 1))
2274 print_headers = true;
2276 if (O_BINARY && ! isatty (STDOUT_FILENO))
2277 xfreopen (NULL, "wb", stdout);
2279 for (i = 0; i < n_files; i++)
2280 ok &= tail_file (&F[i], n_units);
2282 if (forever && ignore_fifo_and_pipe (F, n_files))
2284 #if HAVE_INOTIFY
2285 /* tailable_stdin() checks if the user specifies stdin via "-",
2286 or implicitly by providing no arguments. If so, we won't use inotify.
2287 Technically, on systems with a working /dev/stdin, we *could*,
2288 but would it be worth it? Verifying that it's a real device
2289 and hooked up to stdin is not trivial, while reverting to
2290 non-inotify-based tail_forever is easy and portable.
2292 any_remote_file() checks if the user has specified any
2293 files that reside on remote file systems. inotify is not used
2294 in this case because it would miss any updates to the file
2295 that were not initiated from the local system.
2297 any_symlinks() checks if the user has specified any symbolic links.
2298 inotify is not used in this case because it returns updated _targets_
2299 which would not match the specified names. If we tried to always
2300 use the target names, then we would miss changes to the symlink itself.
2302 ok is false when one of the files specified could not be opened for
2303 reading. In this case and when following by descriptor,
2304 tail_forever_inotify() cannot be used (in its current implementation).
2306 FIXME: inotify doesn't give any notification when a new
2307 (remote) file or directory is mounted on top a watched file.
2308 When follow_mode == Follow_name we would ideally like to detect that.
2309 Note if there is a change to the original file then we'll
2310 recheck it and follow the new file, or ignore it if the
2311 file has changed to being remote.
2313 FIXME: when using inotify, and a directory for a watched file
2314 is recreated, then we don't recheck any new file when
2315 follow_mode == Follow_name.
2317 FIXME-maybe: inotify has a watch descriptor per inode, and hence with
2318 our current hash implementation will only --follow data for one
2319 of the names when multiple hardlinked files are specified. */
2320 if (!disable_inotify && (tailable_stdin (F, n_files)
2321 || any_remote_file (F, n_files)
2322 || any_symlinks (F, n_files)
2323 || (!ok && follow_mode == Follow_descriptor)))
2324 disable_inotify = true;
2326 if (!disable_inotify)
2328 int wd = inotify_init ();
2329 if (0 <= wd)
2331 /* Flush any output from tail_file, now, since
2332 tail_forever_inotify flushes only after writing,
2333 not before reading. */
2334 if (fflush (stdout) != 0)
2335 error (EXIT_FAILURE, errno, _("write error"));
2337 if (! tail_forever_inotify (wd, F, n_files, sleep_interval))
2338 return EXIT_FAILURE;
2340 error (0, errno, _("inotify cannot be used, reverting to polling"));
2342 /* Free resources as this process can be long lived,
2343 and we may have exhausted system resources above. */
2345 for (i = 0; i < n_files; i++)
2347 /* It's OK to remove the same watch multiple times,
2348 ignoring the EINVAL from redundant calls. */
2349 if (F[i].wd != -1)
2350 inotify_rm_watch (wd, F[i].wd);
2351 if (F[i].parent_wd != -1)
2352 inotify_rm_watch (wd, F[i].parent_wd);
2355 #endif
2356 disable_inotify = true;
2357 tail_forever (F, n_files, sleep_interval);
2360 if (have_read_stdin && close (STDIN_FILENO) < 0)
2361 error (EXIT_FAILURE, errno, "-");
2362 return ok ? EXIT_SUCCESS : EXIT_FAILURE;