shred: increase I/O block size for periodic pattern case
[coreutils.git] / src / tail.c
blobe7fefda71d557ec9ddb45d7f1d794ea0f5d946e7
1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989-2013 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 # include "fs-is-local.h"
58 # if HAVE_SYS_STATFS_H
59 # include <sys/statfs.h>
60 # elif HAVE_SYS_VFS_H
61 # include <sys/vfs.h>
62 # endif
63 #endif
65 /* The official name of this program (e.g., no 'g' prefix). */
66 #define PROGRAM_NAME "tail"
68 #define AUTHORS \
69 proper_name ("Paul Rubin"), \
70 proper_name ("David MacKenzie"), \
71 proper_name ("Ian Lance Taylor"), \
72 proper_name ("Jim Meyering")
74 /* Number of items to tail. */
75 #define DEFAULT_N_LINES 10
77 /* Special values for dump_remainder's N_BYTES parameter. */
78 #define COPY_TO_EOF UINTMAX_MAX
79 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
81 /* FIXME: make Follow_name the default? */
82 #define DEFAULT_FOLLOW_MODE Follow_descriptor
84 enum Follow_mode
86 /* Follow the name of each file: if the file is renamed, try to reopen
87 that name and track the end of the new file if/when it's recreated.
88 This is useful for tracking logs that are occasionally rotated. */
89 Follow_name = 1,
91 /* Follow each descriptor obtained upon opening a file.
92 That means we'll continue to follow the end of a file even after
93 it has been renamed or unlinked. */
94 Follow_descriptor = 2
97 /* The types of files for which tail works. */
98 #define IS_TAILABLE_FILE_TYPE(Mode) \
99 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
101 static char const *const follow_mode_string[] =
103 "descriptor", "name", NULL
106 static enum Follow_mode const follow_mode_map[] =
108 Follow_descriptor, Follow_name,
111 struct File_spec
113 /* The actual file name, or "-" for stdin. */
114 char *name;
116 /* Attributes of the file the last time we checked. */
117 off_t size;
118 struct timespec mtime;
119 dev_t dev;
120 ino_t ino;
121 mode_t mode;
123 /* The specified name initially referred to a directory or some other
124 type for which tail isn't meaningful. Unlike for a permission problem
125 (tailable, below) once this is set, the name is not checked ever again. */
126 bool ignore;
128 /* See the description of fremote. */
129 bool remote;
131 /* A file is tailable if it exists, is readable, and is of type
132 IS_TAILABLE_FILE_TYPE. */
133 bool tailable;
135 /* File descriptor on which the file is open; -1 if it's not open. */
136 int fd;
138 /* The value of errno seen last time we checked this file. */
139 int errnum;
141 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
142 int blocking;
144 #if HAVE_INOTIFY
145 /* The watch descriptor used by inotify. */
146 int wd;
148 /* The parent directory watch descriptor. It is used only
149 * when Follow_name is used. */
150 int parent_wd;
152 /* Offset in NAME of the basename part. */
153 size_t basename_start;
154 #endif
156 /* See description of DEFAULT_MAX_N_... below. */
157 uintmax_t n_unchanged_stats;
160 #if HAVE_INOTIFY
161 /* The events mask used with inotify on files. This mask is not used on
162 directories. */
163 static const uint32_t inotify_wd_mask = (IN_MODIFY | IN_ATTRIB
164 | IN_DELETE_SELF | IN_MOVE_SELF);
165 #endif
167 /* Keep trying to open a file even if it is inaccessible when tail starts
168 or if it becomes inaccessible later -- useful only with -f. */
169 static bool reopen_inaccessible_files;
171 /* If true, interpret the numeric argument as the number of lines.
172 Otherwise, interpret it as the number of bytes. */
173 static bool count_lines;
175 /* Whether we follow the name of each file or the file descriptor
176 that is initially associated with each name. */
177 static enum Follow_mode follow_mode = Follow_descriptor;
179 /* If true, read from the ends of all specified files until killed. */
180 static bool forever;
182 /* If true, count from start of file instead of end. */
183 static bool from_start;
185 /* If true, print filename headers. */
186 static bool print_headers;
188 /* When to print the filename banners. */
189 enum header_mode
191 multiple_files, always, never
194 /* When tailing a file by name, if there have been this many consecutive
195 iterations for which the file has not changed, then open/fstat
196 the file to determine if that file name is still associated with the
197 same device/inode-number pair as before. This option is meaningful only
198 when following by name. --max-unchanged-stats=N */
199 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
200 static uintmax_t max_n_unchanged_stats_between_opens =
201 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
203 /* The process ID of the process (presumably on the current host)
204 that is writing to all followed files. */
205 static pid_t pid;
207 /* True if we have ever read standard input. */
208 static bool have_read_stdin;
210 /* If nonzero, skip the is-regular-file test used to determine whether
211 to use the lseek optimization. Instead, use the more general (and
212 more expensive) code unconditionally. Intended solely for testing. */
213 static bool presume_input_pipe;
215 /* If nonzero then don't use inotify even if available. */
216 static bool disable_inotify;
218 /* For long options that have no equivalent short option, use a
219 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
220 enum
222 RETRY_OPTION = CHAR_MAX + 1,
223 MAX_UNCHANGED_STATS_OPTION,
224 PID_OPTION,
225 PRESUME_INPUT_PIPE_OPTION,
226 LONG_FOLLOW_OPTION,
227 DISABLE_INOTIFY_OPTION
230 static struct option const long_options[] =
232 {"bytes", required_argument, NULL, 'c'},
233 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
234 {"lines", required_argument, NULL, 'n'},
235 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
236 {"-disable-inotify", no_argument, NULL,
237 DISABLE_INOTIFY_OPTION}, /* do not document */
238 {"pid", required_argument, NULL, PID_OPTION},
239 {"-presume-input-pipe", no_argument, NULL,
240 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
241 {"quiet", no_argument, NULL, 'q'},
242 {"retry", no_argument, NULL, RETRY_OPTION},
243 {"silent", no_argument, NULL, 'q'},
244 {"sleep-interval", required_argument, NULL, 's'},
245 {"verbose", no_argument, NULL, 'v'},
246 {GETOPT_HELP_OPTION_DECL},
247 {GETOPT_VERSION_OPTION_DECL},
248 {NULL, 0, NULL, 0}
251 void
252 usage (int status)
254 if (status != EXIT_SUCCESS)
255 emit_try_help ();
256 else
258 printf (_("\
259 Usage: %s [OPTION]... [FILE]...\n\
261 program_name);
262 printf (_("\
263 Print the last %d lines of each FILE to standard output.\n\
264 With more than one FILE, precede each with a header giving the file name.\n\
265 With no FILE, or when FILE is -, read standard input.\n\
266 "), DEFAULT_N_LINES);
268 emit_mandatory_arg_note ();
270 fputs (_("\
271 -c, --bytes=K output the last K bytes; or use -c +K to output\n\
272 bytes starting with the Kth of each file\n\
273 "), stdout);
274 fputs (_("\
275 -f, --follow[={name|descriptor}]\n\
276 output appended data as the file grows;\n\
277 an absent option argument means 'descriptor'\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 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\
288 with inotify, this option is rarely useful\n\
290 DEFAULT_N_LINES,
291 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
293 fputs (_("\
294 --pid=PID with -f, terminate after process ID, PID dies\n\
295 -q, --quiet, --silent never output headers giving file names\n\
296 --retry keep trying to open a file if it is inaccessible\n\
297 "), stdout);
298 fputs (_("\
299 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
300 (default 1.0) between iterations;\n\
301 with inotify and --pid=P, check process P at\n\
302 least once every N seconds\n\
303 -v, --verbose always output headers giving file names\n\
304 "), stdout);
305 fputs (HELP_OPTION_DESCRIPTION, stdout);
306 fputs (VERSION_OPTION_DESCRIPTION, stdout);
307 fputs (_("\
309 If the first character of K (the number of bytes or lines) is a '+',\n\
310 print beginning with the Kth item from the start of each file, otherwise,\n\
311 print the last K items in the file. K may have a multiplier suffix:\n\
312 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
313 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
315 "), stdout);
316 fputs (_("\
317 With --follow (-f), tail defaults to following the file descriptor, which\n\
318 means that even if a tail'ed file is renamed, tail will continue to track\n\
319 its end. This default behavior is not desirable when you really want to\n\
320 track the actual name of the file, not the file descriptor (e.g., log\n\
321 rotation). Use --follow=name in that case. That causes tail to track the\n\
322 named file in a way that accommodates renaming, removal and creation.\n\
323 "), stdout);
324 emit_ancillary_info ();
326 exit (status);
329 static bool
330 valid_file_spec (struct File_spec const *f)
332 /* Exactly one of the following subexpressions must be true. */
333 return ((f->fd == -1) ^ (f->errnum == 0));
336 static char const *
337 pretty_name (struct File_spec const *f)
339 return (STREQ (f->name, "-") ? _("standard input") : f->name);
342 static void
343 xwrite_stdout (char const *buffer, size_t n_bytes)
345 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
346 error (EXIT_FAILURE, errno, _("write error"));
349 /* Record a file F with descriptor FD, size SIZE, status ST, and
350 blocking status BLOCKING. */
352 static void
353 record_open_fd (struct File_spec *f, int fd,
354 off_t size, struct stat const *st,
355 int blocking)
357 f->fd = fd;
358 f->size = size;
359 f->mtime = get_stat_mtime (st);
360 f->dev = st->st_dev;
361 f->ino = st->st_ino;
362 f->mode = st->st_mode;
363 f->blocking = blocking;
364 f->n_unchanged_stats = 0;
365 f->ignore = false;
368 /* Close the file with descriptor FD and name FILENAME. */
370 static void
371 close_fd (int fd, const char *filename)
373 if (fd != -1 && fd != STDIN_FILENO && close (fd))
375 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
379 static void
380 write_header (const char *pretty_filename)
382 static bool first_file = true;
384 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
385 first_file = false;
388 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
389 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
390 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
391 Return the number of bytes read from the file. */
393 static uintmax_t
394 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
396 uintmax_t n_written;
397 uintmax_t n_remaining = n_bytes;
399 n_written = 0;
400 while (1)
402 char buffer[BUFSIZ];
403 size_t n = MIN (n_remaining, BUFSIZ);
404 size_t bytes_read = safe_read (fd, buffer, n);
405 if (bytes_read == SAFE_READ_ERROR)
407 if (errno != EAGAIN)
408 error (EXIT_FAILURE, errno, _("error reading %s"),
409 quote (pretty_filename));
410 break;
412 if (bytes_read == 0)
413 break;
414 xwrite_stdout (buffer, bytes_read);
415 n_written += bytes_read;
416 if (n_bytes != COPY_TO_EOF)
418 n_remaining -= bytes_read;
419 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
420 break;
424 return n_written;
427 /* Call lseek with the specified arguments, where file descriptor FD
428 corresponds to the file, FILENAME.
429 Give a diagnostic and exit nonzero if lseek fails.
430 Otherwise, return the resulting offset. */
432 static off_t
433 xlseek (int fd, off_t offset, int whence, char const *filename)
435 off_t new_offset = lseek (fd, offset, whence);
436 char buf[INT_BUFSIZE_BOUND (offset)];
437 char *s;
439 if (0 <= new_offset)
440 return new_offset;
442 s = offtostr (offset, buf);
443 switch (whence)
445 case SEEK_SET:
446 error (0, errno, _("%s: cannot seek to offset %s"),
447 filename, s);
448 break;
449 case SEEK_CUR:
450 error (0, errno, _("%s: cannot seek to relative offset %s"),
451 filename, s);
452 break;
453 case SEEK_END:
454 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
455 filename, s);
456 break;
457 default:
458 abort ();
461 exit (EXIT_FAILURE);
464 /* Print the last N_LINES lines from the end of file FD.
465 Go backward through the file, reading 'BUFSIZ' bytes at a time (except
466 probably the first), until we hit the start of the file or have
467 read NUMBER newlines.
468 START_POS is the starting position of the read pointer for the file
469 associated with FD (may be nonzero).
470 END_POS is the file offset of EOF (one larger than offset of last byte).
471 Return true if successful. */
473 static bool
474 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
475 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
477 char buffer[BUFSIZ];
478 size_t bytes_read;
479 off_t pos = end_pos;
481 if (n_lines == 0)
482 return true;
484 /* Set 'bytes_read' to the size of the last, probably partial, buffer;
485 0 < 'bytes_read' <= 'BUFSIZ'. */
486 bytes_read = (pos - start_pos) % BUFSIZ;
487 if (bytes_read == 0)
488 bytes_read = BUFSIZ;
489 /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
490 reads will be on block boundaries, which might increase efficiency. */
491 pos -= bytes_read;
492 xlseek (fd, pos, SEEK_SET, pretty_filename);
493 bytes_read = safe_read (fd, buffer, bytes_read);
494 if (bytes_read == SAFE_READ_ERROR)
496 error (0, errno, _("error reading %s"), quote (pretty_filename));
497 return false;
499 *read_pos = pos + bytes_read;
501 /* Count the incomplete line on files that don't end with a newline. */
502 if (bytes_read && buffer[bytes_read - 1] != '\n')
503 --n_lines;
507 /* Scan backward, counting the newlines in this bufferfull. */
509 size_t n = bytes_read;
510 while (n)
512 char const *nl;
513 nl = memrchr (buffer, '\n', n);
514 if (nl == NULL)
515 break;
516 n = nl - buffer;
517 if (n_lines-- == 0)
519 /* If this newline isn't the last character in the buffer,
520 output the part that is after it. */
521 if (n != bytes_read - 1)
522 xwrite_stdout (nl + 1, bytes_read - (n + 1));
523 *read_pos += dump_remainder (pretty_filename, fd,
524 end_pos - (pos + bytes_read));
525 return true;
529 /* Not enough newlines in that bufferfull. */
530 if (pos == start_pos)
532 /* Not enough lines in the file; print everything from
533 start_pos to the end. */
534 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
535 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
536 end_pos);
537 return true;
539 pos -= BUFSIZ;
540 xlseek (fd, pos, SEEK_SET, pretty_filename);
542 bytes_read = safe_read (fd, buffer, BUFSIZ);
543 if (bytes_read == SAFE_READ_ERROR)
545 error (0, errno, _("error reading %s"), quote (pretty_filename));
546 return false;
549 *read_pos = pos + bytes_read;
551 while (bytes_read > 0);
553 return true;
556 /* Print the last N_LINES lines from the end of the standard input,
557 open for reading as pipe FD.
558 Buffer the text as a linked list of LBUFFERs, adding them as needed.
559 Return true if successful. */
561 static bool
562 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
563 uintmax_t *read_pos)
565 struct linebuffer
567 char buffer[BUFSIZ];
568 size_t nbytes;
569 size_t nlines;
570 struct linebuffer *next;
572 typedef struct linebuffer LBUFFER;
573 LBUFFER *first, *last, *tmp;
574 size_t total_lines = 0; /* Total number of newlines in all buffers. */
575 bool ok = true;
576 size_t n_read; /* Size in bytes of most recent read */
578 first = last = xmalloc (sizeof (LBUFFER));
579 first->nbytes = first->nlines = 0;
580 first->next = NULL;
581 tmp = xmalloc (sizeof (LBUFFER));
583 /* Input is always read into a fresh buffer. */
584 while (1)
586 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
587 if (n_read == 0 || n_read == SAFE_READ_ERROR)
588 break;
589 tmp->nbytes = n_read;
590 *read_pos += n_read;
591 tmp->nlines = 0;
592 tmp->next = NULL;
594 /* Count the number of newlines just read. */
596 char const *buffer_end = tmp->buffer + n_read;
597 char const *p = tmp->buffer;
598 while ((p = memchr (p, '\n', buffer_end - p)))
600 ++p;
601 ++tmp->nlines;
604 total_lines += tmp->nlines;
606 /* If there is enough room in the last buffer read, just append the new
607 one to it. This is because when reading from a pipe, 'n_read' can
608 often be very small. */
609 if (tmp->nbytes + last->nbytes < BUFSIZ)
611 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
612 last->nbytes += tmp->nbytes;
613 last->nlines += tmp->nlines;
615 else
617 /* If there's not enough room, link the new buffer onto the end of
618 the list, then either free up the oldest buffer for the next
619 read if that would leave enough lines, or else malloc a new one.
620 Some compaction mechanism is possible but probably not
621 worthwhile. */
622 last = last->next = tmp;
623 if (total_lines - first->nlines > n_lines)
625 tmp = first;
626 total_lines -= first->nlines;
627 first = first->next;
629 else
630 tmp = xmalloc (sizeof (LBUFFER));
634 free (tmp);
636 if (n_read == SAFE_READ_ERROR)
638 error (0, errno, _("error reading %s"), quote (pretty_filename));
639 ok = false;
640 goto free_lbuffers;
643 /* If the file is empty, then bail out. */
644 if (last->nbytes == 0)
645 goto free_lbuffers;
647 /* This prevents a core dump when the pipe contains no newlines. */
648 if (n_lines == 0)
649 goto free_lbuffers;
651 /* Count the incomplete line on files that don't end with a newline. */
652 if (last->buffer[last->nbytes - 1] != '\n')
654 ++last->nlines;
655 ++total_lines;
658 /* Run through the list, printing lines. First, skip over unneeded
659 buffers. */
660 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
661 total_lines -= tmp->nlines;
663 /* Find the correct beginning, then print the rest of the file. */
665 char const *beg = tmp->buffer;
666 char const *buffer_end = tmp->buffer + tmp->nbytes;
667 if (total_lines > n_lines)
669 /* Skip 'total_lines' - 'n_lines' newlines. We made sure that
670 'total_lines' - 'n_lines' <= 'tmp->nlines'. */
671 size_t j;
672 for (j = total_lines - n_lines; j; --j)
674 beg = memchr (beg, '\n', buffer_end - beg);
675 assert (beg);
676 ++beg;
680 xwrite_stdout (beg, buffer_end - beg);
683 for (tmp = tmp->next; tmp; tmp = tmp->next)
684 xwrite_stdout (tmp->buffer, tmp->nbytes);
686 free_lbuffers:
687 while (first)
689 tmp = first->next;
690 free (first);
691 first = tmp;
693 return ok;
696 /* Print the last N_BYTES characters from the end of pipe FD.
697 This is a stripped down version of pipe_lines.
698 Return true if successful. */
700 static bool
701 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
702 uintmax_t *read_pos)
704 struct charbuffer
706 char buffer[BUFSIZ];
707 size_t nbytes;
708 struct charbuffer *next;
710 typedef struct charbuffer CBUFFER;
711 CBUFFER *first, *last, *tmp;
712 size_t i; /* Index into buffers. */
713 size_t total_bytes = 0; /* Total characters in all buffers. */
714 bool ok = true;
715 size_t n_read;
717 first = last = xmalloc (sizeof (CBUFFER));
718 first->nbytes = 0;
719 first->next = NULL;
720 tmp = xmalloc (sizeof (CBUFFER));
722 /* Input is always read into a fresh buffer. */
723 while (1)
725 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
726 if (n_read == 0 || n_read == SAFE_READ_ERROR)
727 break;
728 *read_pos += n_read;
729 tmp->nbytes = n_read;
730 tmp->next = NULL;
732 total_bytes += tmp->nbytes;
733 /* If there is enough room in the last buffer read, just append the new
734 one to it. This is because when reading from a pipe, 'nbytes' can
735 often be very small. */
736 if (tmp->nbytes + last->nbytes < BUFSIZ)
738 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
739 last->nbytes += tmp->nbytes;
741 else
743 /* If there's not enough room, link the new buffer onto the end of
744 the list, then either free up the oldest buffer for the next
745 read if that would leave enough characters, or else malloc a new
746 one. Some compaction mechanism is possible but probably not
747 worthwhile. */
748 last = last->next = tmp;
749 if (total_bytes - first->nbytes > n_bytes)
751 tmp = first;
752 total_bytes -= first->nbytes;
753 first = first->next;
755 else
757 tmp = xmalloc (sizeof (CBUFFER));
762 free (tmp);
764 if (n_read == SAFE_READ_ERROR)
766 error (0, errno, _("error reading %s"), quote (pretty_filename));
767 ok = false;
768 goto free_cbuffers;
771 /* Run through the list, printing characters. First, skip over unneeded
772 buffers. */
773 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
774 total_bytes -= tmp->nbytes;
776 /* Find the correct beginning, then print the rest of the file.
777 We made sure that 'total_bytes' - 'n_bytes' <= 'tmp->nbytes'. */
778 if (total_bytes > n_bytes)
779 i = total_bytes - n_bytes;
780 else
781 i = 0;
782 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
784 for (tmp = tmp->next; tmp; tmp = tmp->next)
785 xwrite_stdout (tmp->buffer, tmp->nbytes);
787 free_cbuffers:
788 while (first)
790 tmp = first->next;
791 free (first);
792 first = tmp;
794 return ok;
797 /* Skip N_BYTES characters from the start of pipe FD, and print
798 any extra characters that were read beyond that.
799 Return 1 on error, 0 if ok, -1 if EOF. */
801 static int
802 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
803 uintmax_t *read_pos)
805 char buffer[BUFSIZ];
807 while (0 < n_bytes)
809 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
810 if (bytes_read == 0)
811 return -1;
812 if (bytes_read == SAFE_READ_ERROR)
814 error (0, errno, _("error reading %s"), quote (pretty_filename));
815 return 1;
817 *read_pos += bytes_read;
818 if (bytes_read <= n_bytes)
819 n_bytes -= bytes_read;
820 else
822 size_t n_remaining = bytes_read - n_bytes;
823 if (n_remaining)
824 xwrite_stdout (&buffer[n_bytes], n_remaining);
825 break;
829 return 0;
832 /* Skip N_LINES lines at the start of file or pipe FD, and print
833 any extra characters that were read beyond that.
834 Return 1 on error, 0 if ok, -1 if EOF. */
836 static int
837 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
838 uintmax_t *read_pos)
840 if (n_lines == 0)
841 return 0;
843 while (1)
845 char buffer[BUFSIZ];
846 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
847 if (bytes_read == 0) /* EOF */
848 return -1;
849 if (bytes_read == SAFE_READ_ERROR) /* error */
851 error (0, errno, _("error reading %s"), quote (pretty_filename));
852 return 1;
855 char *buffer_end = buffer + bytes_read;
857 *read_pos += bytes_read;
859 char *p = buffer;
860 while ((p = memchr (p, '\n', buffer_end - p)))
862 ++p;
863 if (--n_lines == 0)
865 if (p < buffer_end)
866 xwrite_stdout (p, buffer_end - p);
867 return 0;
873 #if HAVE_INOTIFY
874 /* Without inotify support, always return false. Otherwise, return false
875 when FD is open on a file known to reside on a local file system.
876 If fstatfs fails, give a diagnostic and return true.
877 If fstatfs cannot be called, return true. */
878 static bool
879 fremote (int fd, const char *name)
881 bool remote = true; /* be conservative (poll by default). */
883 # if HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE && defined __linux__
884 struct statfs buf;
885 int err = fstatfs (fd, &buf);
886 if (err != 0)
888 /* On at least linux-2.6.38, fstatfs fails with ENOSYS when FD
889 is open on a pipe. Treat that like a remote file. */
890 if (errno != ENOSYS)
891 error (0, errno, _("cannot determine location of %s. "
892 "reverting to polling"), quote (name));
894 else
896 switch (is_local_fs_type (buf.f_type))
898 case 0:
899 break;
900 case -1:
902 unsigned long int fs_type = buf.f_type;
903 error (0, 0, _("unrecognized file system type 0x%08lx for %s. "
904 "please report this to %s. reverting to polling"),
905 fs_type, quote (name), PACKAGE_BUGREPORT);
906 /* Treat as "remote", so caller polls. */
908 break;
909 case 1:
910 remote = false;
911 break;
912 default:
913 assert (!"unexpected return value from is_local_fs_type");
916 # endif
918 return remote;
920 #else
921 /* Without inotify support, whether a file is remote is irrelevant.
922 Always return "false" in that case. */
923 # define fremote(fd, name) false
924 #endif
926 /* FIXME: describe */
928 static void
929 recheck (struct File_spec *f, bool blocking)
931 /* open/fstat the file and announce if dev/ino have changed */
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 (fd == -1 || fstat (fd, &new_stats) < 0)
950 ok = false;
951 f->errnum = errno;
952 if (!f->tailable)
954 if (was_tailable)
956 /* FIXME-maybe: detect the case in which the file first becomes
957 unreadable (perms), and later becomes readable again and can
958 be seen to be the same file (dev/ino). Otherwise, tail prints
959 the entire contents of the file when it becomes readable. */
960 error (0, f->errnum, _("%s has become inaccessible"),
961 quote (pretty_name (f)));
963 else
965 /* say nothing... it's still not tailable */
968 else if (prev_errnum != errno)
970 error (0, errno, "%s", pretty_name (f));
973 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
975 ok = false;
976 f->errnum = -1;
977 error (0, 0, _("%s has been replaced with an untailable file;\
978 giving up on this name"),
979 quote (pretty_name (f)));
980 f->ignore = true;
982 else if (!disable_inotify && fremote (fd, pretty_name (f)))
984 ok = false;
985 f->errnum = -1;
986 error (0, 0, _("%s has been replaced with a remote file. "
987 "giving up on this name"), quote (pretty_name (f)));
988 f->ignore = true;
989 f->remote = true;
991 else
993 f->errnum = 0;
996 new_file = false;
997 if (!ok)
999 close_fd (fd, pretty_name (f));
1000 close_fd (f->fd, pretty_name (f));
1001 f->fd = -1;
1003 else if (prev_errnum && prev_errnum != ENOENT)
1005 new_file = true;
1006 assert (f->fd == -1);
1007 error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
1009 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
1011 new_file = true;
1012 if (f->fd == -1)
1014 error (0, 0,
1015 _("%s has appeared; following end of new file"),
1016 quote (pretty_name (f)));
1018 else
1020 /* Close the old one. */
1021 close_fd (f->fd, pretty_name (f));
1023 /* File has been replaced (e.g., via log rotation) --
1024 tail the new one. */
1025 error (0, 0,
1026 _("%s has been replaced; following end of new file"),
1027 quote (pretty_name (f)));
1030 else
1032 if (f->fd == -1)
1034 /* This happens when one iteration finds the file missing,
1035 then the preceding <dev,inode> pair is reused as the
1036 file is recreated. */
1037 new_file = true;
1039 else
1041 close_fd (fd, pretty_name (f));
1045 if (new_file)
1047 /* Start at the beginning of the file. */
1048 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
1049 xlseek (fd, 0, SEEK_SET, pretty_name (f));
1053 /* Return true if any of the N_FILES files in F are live, i.e., have
1054 open file descriptors, or should be checked again (see --retry).
1055 When following descriptors, checking should only continue when any
1056 of the files is not yet ignored. */
1058 static bool
1059 any_live_files (const struct File_spec *f, size_t n_files)
1061 size_t i;
1063 if (reopen_inaccessible_files && follow_mode == Follow_name)
1064 return true; /* continue following for -F option */
1066 for (i = 0; i < n_files; i++)
1068 if (0 <= f[i].fd)
1070 return true;
1072 else
1074 if (reopen_inaccessible_files && follow_mode == Follow_descriptor)
1075 if (! f[i].ignore)
1076 return true;
1080 return false;
1083 /* Tail N_FILES files forever, or until killed.
1084 The pertinent information for each file is stored in an entry of F.
1085 Loop over each of them, doing an fstat to see if they have changed size,
1086 and an occasional open/fstat to see if any dev/ino pair has changed.
1087 If none of them have changed size in one iteration, sleep for a
1088 while and try again. Continue until the user interrupts us. */
1090 static void
1091 tail_forever (struct File_spec *f, size_t n_files, double sleep_interval)
1093 /* Use blocking I/O as an optimization, when it's easy. */
1094 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
1095 && n_files == 1 && ! S_ISREG (f[0].mode));
1096 size_t last;
1097 bool writer_is_dead = false;
1099 last = n_files - 1;
1101 while (1)
1103 size_t i;
1104 bool any_input = false;
1106 for (i = 0; i < n_files; i++)
1108 int fd;
1109 char const *name;
1110 mode_t mode;
1111 struct stat stats;
1112 uintmax_t bytes_read;
1114 if (f[i].ignore)
1115 continue;
1117 if (f[i].fd < 0)
1119 recheck (&f[i], blocking);
1120 continue;
1123 fd = f[i].fd;
1124 name = pretty_name (&f[i]);
1125 mode = f[i].mode;
1127 if (f[i].blocking != blocking)
1129 int old_flags = fcntl (fd, F_GETFL);
1130 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1131 if (old_flags < 0
1132 || (new_flags != old_flags
1133 && fcntl (fd, F_SETFL, new_flags) == -1))
1135 /* Don't update f[i].blocking if fcntl fails. */
1136 if (S_ISREG (f[i].mode) && errno == EPERM)
1138 /* This happens when using tail -f on a file with
1139 the append-only attribute. */
1141 else
1142 error (EXIT_FAILURE, errno,
1143 _("%s: cannot change nonblocking mode"), name);
1145 else
1146 f[i].blocking = blocking;
1149 if (!f[i].blocking)
1151 if (fstat (fd, &stats) != 0)
1153 f[i].fd = -1;
1154 f[i].errnum = errno;
1155 error (0, errno, "%s", name);
1156 close (fd); /* ignore failure */
1157 continue;
1160 if (f[i].mode == stats.st_mode
1161 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1162 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1164 if ((max_n_unchanged_stats_between_opens
1165 <= f[i].n_unchanged_stats++)
1166 && follow_mode == Follow_name)
1168 recheck (&f[i], f[i].blocking);
1169 f[i].n_unchanged_stats = 0;
1171 continue;
1174 /* This file has changed. Print out what we can, and
1175 then keep looping. */
1177 f[i].mtime = get_stat_mtime (&stats);
1178 f[i].mode = stats.st_mode;
1180 /* reset counter */
1181 f[i].n_unchanged_stats = 0;
1183 if (S_ISREG (mode) && stats.st_size < f[i].size)
1185 error (0, 0, _("%s: file truncated"), name);
1186 last = i;
1187 xlseek (fd, stats.st_size, SEEK_SET, name);
1188 f[i].size = stats.st_size;
1189 continue;
1192 if (i != last)
1194 if (print_headers)
1195 write_header (name);
1196 last = i;
1200 bytes_read = dump_remainder (name, fd,
1201 (f[i].blocking
1202 ? COPY_A_BUFFER : COPY_TO_EOF));
1203 any_input |= (bytes_read != 0);
1204 f[i].size += bytes_read;
1207 if (! any_live_files (f, n_files))
1209 error (0, 0, _("no files remaining"));
1210 break;
1213 if ((!any_input || blocking) && fflush (stdout) != 0)
1214 error (EXIT_FAILURE, errno, _("write error"));
1216 /* If nothing was read, sleep and/or check for dead writers. */
1217 if (!any_input)
1219 if (writer_is_dead)
1220 break;
1222 /* Once the writer is dead, read the files once more to
1223 avoid a race condition. */
1224 writer_is_dead = (pid != 0
1225 && kill (pid, 0) != 0
1226 /* Handle the case in which you cannot send a
1227 signal to the writer, so kill fails and sets
1228 errno to EPERM. */
1229 && errno != EPERM);
1231 if (!writer_is_dead && xnanosleep (sleep_interval))
1232 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1238 #if HAVE_INOTIFY
1240 /* Return true if any of the N_FILES files in F is remote, i.e., has
1241 an open file descriptor and is on a network file system. */
1243 static bool
1244 any_remote_file (const struct File_spec *f, size_t n_files)
1246 size_t i;
1248 for (i = 0; i < n_files; i++)
1249 if (0 <= f[i].fd && f[i].remote)
1250 return true;
1251 return false;
1254 /* Return true if any of the N_FILES files in F represents
1255 stdin and is tailable. */
1257 static bool
1258 tailable_stdin (const struct File_spec *f, size_t n_files)
1260 size_t i;
1262 for (i = 0; i < n_files; i++)
1263 if (!f[i].ignore && STREQ (f[i].name, "-"))
1264 return true;
1265 return false;
1268 static size_t
1269 wd_hasher (const void *entry, size_t tabsize)
1271 const struct File_spec *spec = entry;
1272 return spec->wd % tabsize;
1275 static bool
1276 wd_comparator (const void *e1, const void *e2)
1278 const struct File_spec *spec1 = e1;
1279 const struct File_spec *spec2 = e2;
1280 return spec1->wd == spec2->wd;
1283 /* Helper function used by 'tail_forever_inotify'. */
1284 static void
1285 check_fspec (struct File_spec *fspec, int wd, int *prev_wd)
1287 struct stat stats;
1288 char const *name = pretty_name (fspec);
1290 if (fstat (fspec->fd, &stats) != 0)
1292 fspec->errnum = errno;
1293 close_fd (fspec->fd, name);
1294 fspec->fd = -1;
1295 return;
1298 if (S_ISREG (fspec->mode) && stats.st_size < fspec->size)
1300 error (0, 0, _("%s: file truncated"), name);
1301 *prev_wd = wd;
1302 xlseek (fspec->fd, stats.st_size, SEEK_SET, name);
1303 fspec->size = stats.st_size;
1305 else if (S_ISREG (fspec->mode) && stats.st_size == fspec->size
1306 && timespec_cmp (fspec->mtime, get_stat_mtime (&stats)) == 0)
1307 return;
1309 if (wd != *prev_wd)
1311 if (print_headers)
1312 write_header (name);
1313 *prev_wd = wd;
1316 uintmax_t bytes_read = dump_remainder (name, fspec->fd, COPY_TO_EOF);
1317 fspec->size += bytes_read;
1319 if (fflush (stdout) != 0)
1320 error (EXIT_FAILURE, errno, _("write error"));
1323 /* Attempt to tail N_FILES files forever, or until killed.
1324 Check modifications using the inotify events system.
1325 Return false on error, or true to revert to polling. */
1326 static bool
1327 tail_forever_inotify (int wd, struct File_spec *f, size_t n_files,
1328 double sleep_interval)
1330 unsigned int max_realloc = 3;
1332 /* Map an inotify watch descriptor to the name of the file it's watching. */
1333 Hash_table *wd_to_name;
1335 bool found_watchable_file = false;
1336 bool found_unwatchable_dir = false;
1337 bool no_inotify_resources = false;
1338 bool writer_is_dead = false;
1339 int prev_wd;
1340 size_t evlen = 0;
1341 char *evbuf;
1342 size_t evbuf_off = 0;
1343 size_t len = 0;
1345 wd_to_name = hash_initialize (n_files, NULL, wd_hasher, wd_comparator, NULL);
1346 if (! wd_to_name)
1347 xalloc_die ();
1349 /* Add an inotify watch for each watched file. If -F is specified then watch
1350 its parent directory too, in this way when they re-appear we can add them
1351 again to the watch list. */
1352 size_t i;
1353 for (i = 0; i < n_files; i++)
1355 if (!f[i].ignore)
1357 size_t fnlen = strlen (f[i].name);
1358 if (evlen < fnlen)
1359 evlen = fnlen;
1361 f[i].wd = -1;
1363 if (follow_mode == Follow_name)
1365 size_t dirlen = dir_len (f[i].name);
1366 char prev = f[i].name[dirlen];
1367 f[i].basename_start = last_component (f[i].name) - f[i].name;
1369 f[i].name[dirlen] = '\0';
1371 /* It's fine to add the same directory more than once.
1372 In that case the same watch descriptor is returned. */
1373 f[i].parent_wd = inotify_add_watch (wd, dirlen ? f[i].name : ".",
1374 (IN_CREATE | IN_MOVED_TO
1375 | IN_ATTRIB));
1377 f[i].name[dirlen] = prev;
1379 if (f[i].parent_wd < 0)
1381 if (errno != ENOSPC) /* suppress confusing error. */
1382 error (0, errno, _("cannot watch parent directory of %s"),
1383 quote (f[i].name));
1384 else
1385 error (0, 0, _("inotify resources exhausted"));
1386 found_unwatchable_dir = true;
1387 /* We revert to polling below. Note invalid uses
1388 of the inotify API will still be diagnosed. */
1389 break;
1393 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1395 if (f[i].wd < 0)
1397 if (errno == ENOSPC)
1399 no_inotify_resources = true;
1400 error (0, 0, _("inotify resources exhausted"));
1402 else if (errno != f[i].errnum)
1403 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1404 continue;
1407 if (hash_insert (wd_to_name, &(f[i])) == NULL)
1408 xalloc_die ();
1410 found_watchable_file = true;
1414 /* Linux kernel 2.6.24 at least has a bug where eventually, ENOSPC is always
1415 returned by inotify_add_watch. In any case we should revert to polling
1416 when there are no inotify resources. Also a specified directory may not
1417 be currently present or accessible, so revert to polling. */
1418 if (no_inotify_resources || found_unwatchable_dir)
1420 /* FIXME: release hash and inotify resources allocated above. */
1421 errno = 0;
1422 return true;
1424 if (follow_mode == Follow_descriptor && !found_watchable_file)
1425 return false;
1427 prev_wd = f[n_files - 1].wd;
1429 /* Check files again. New data can be available since last time we checked
1430 and before they are watched by inotify. */
1431 for (i = 0; i < n_files; i++)
1433 if (!f[i].ignore)
1434 check_fspec (&f[i], f[i].wd, &prev_wd);
1437 evlen += sizeof (struct inotify_event) + 1;
1438 evbuf = xmalloc (evlen);
1440 /* Wait for inotify events and handle them. Events on directories
1441 ensure that watched files can be re-added when following by name.
1442 This loop blocks on the 'safe_read' call until a new event is notified.
1443 But when --pid=P is specified, tail usually waits via the select. */
1444 while (1)
1446 struct File_spec *fspec;
1447 struct inotify_event *ev;
1448 void *void_ev;
1450 /* When following by name without --retry, and the last file has
1451 been unlinked or renamed-away, diagnose it and return. */
1452 if (follow_mode == Follow_name
1453 && ! reopen_inaccessible_files
1454 && hash_get_n_entries (wd_to_name) == 0)
1456 error (0, 0, _("no files remaining"));
1457 return false;
1460 /* When watching a PID, ensure that a read from WD will not block
1461 indefinitely. */
1462 if (pid)
1464 if (writer_is_dead)
1465 exit (EXIT_SUCCESS);
1467 writer_is_dead = (kill (pid, 0) != 0 && errno != EPERM);
1469 struct timeval delay; /* how long to wait for file changes. */
1470 if (writer_is_dead)
1471 delay.tv_sec = delay.tv_usec = 0;
1472 else
1474 delay.tv_sec = (time_t) sleep_interval;
1475 delay.tv_usec = 1000000 * (sleep_interval - delay.tv_sec);
1478 fd_set rfd;
1479 FD_ZERO (&rfd);
1480 FD_SET (wd, &rfd);
1482 int file_change = select (wd + 1, &rfd, NULL, NULL, &delay);
1484 if (file_change == 0)
1485 continue;
1486 else if (file_change == -1)
1487 error (EXIT_FAILURE, errno, _("error monitoring inotify event"));
1490 if (len <= evbuf_off)
1492 len = safe_read (wd, evbuf, evlen);
1493 evbuf_off = 0;
1495 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1496 is too small. */
1497 if ((len == 0 || (len == SAFE_READ_ERROR && errno == EINVAL))
1498 && max_realloc--)
1500 len = 0;
1501 evlen *= 2;
1502 evbuf = xrealloc (evbuf, evlen);
1503 continue;
1506 if (len == 0 || len == SAFE_READ_ERROR)
1507 error (EXIT_FAILURE, errno, _("error reading inotify event"));
1510 void_ev = evbuf + evbuf_off;
1511 ev = void_ev;
1512 evbuf_off += sizeof (*ev) + ev->len;
1514 if (ev->len) /* event on ev->name in watched directory */
1516 size_t j;
1517 for (j = 0; j < n_files; j++)
1519 /* With N=hundreds of frequently-changing files, this O(N^2)
1520 process might be a problem. FIXME: use a hash table? */
1521 if (f[j].parent_wd == ev->wd
1522 && STREQ (ev->name, f[j].name + f[j].basename_start))
1523 break;
1526 /* It is not a watched file. */
1527 if (j == n_files)
1528 continue;
1530 /* It's fine to add the same file more than once. */
1531 int new_wd = inotify_add_watch (wd, f[j].name, inotify_wd_mask);
1532 if (new_wd < 0)
1534 error (0, errno, _("cannot watch %s"), quote (f[j].name));
1535 continue;
1538 fspec = &(f[j]);
1540 /* Remove 'fspec' and re-add it using 'new_fd' as its key. */
1541 hash_delete (wd_to_name, fspec);
1542 fspec->wd = new_wd;
1544 /* If the file was moved then inotify will use the source file wd for
1545 the destination file. Make sure the key is not present in the
1546 table. */
1547 struct File_spec *prev = hash_delete (wd_to_name, fspec);
1548 if (prev && prev != fspec)
1550 if (follow_mode == Follow_name)
1551 recheck (prev, false);
1552 prev->wd = -1;
1553 close_fd (prev->fd, pretty_name (prev));
1556 if (hash_insert (wd_to_name, fspec) == NULL)
1557 xalloc_die ();
1559 if (follow_mode == Follow_name)
1560 recheck (fspec, false);
1562 else
1564 struct File_spec key;
1565 key.wd = ev->wd;
1566 fspec = hash_lookup (wd_to_name, &key);
1569 if (! fspec)
1570 continue;
1572 if (ev->mask & (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF))
1574 /* For IN_DELETE_SELF, we always want to remove the watch.
1575 However, for IN_MOVE_SELF (the file we're watching has
1576 been clobbered via a rename), when tailing by NAME, we
1577 must continue to watch the file. It's only when following
1578 by file descriptor that we must remove the watch. */
1579 if ((ev->mask & IN_DELETE_SELF)
1580 || ((ev->mask & IN_MOVE_SELF)
1581 && follow_mode == Follow_descriptor))
1583 inotify_rm_watch (wd, fspec->wd);
1584 hash_delete (wd_to_name, fspec);
1586 if (follow_mode == Follow_name)
1587 recheck (fspec, false);
1589 continue;
1591 check_fspec (fspec, ev->wd, &prev_wd);
1594 #endif
1596 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1597 Return true if successful. */
1599 static bool
1600 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1601 uintmax_t *read_pos)
1603 struct stat stats;
1605 if (fstat (fd, &stats))
1607 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1608 return false;
1611 if (from_start)
1613 if ( ! presume_input_pipe
1614 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1616 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1617 *read_pos += n_bytes;
1619 else
1621 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1622 if (t)
1623 return t < 0;
1625 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1627 else
1629 if ( ! presume_input_pipe
1630 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1632 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1633 off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
1634 off_t diff = end_pos - current_pos;
1635 /* Be careful here. The current position may actually be
1636 beyond the end of the file. */
1637 off_t bytes_remaining = diff < 0 ? 0 : diff;
1638 off_t nb = n_bytes;
1640 if (bytes_remaining <= nb)
1642 /* From the current position to end of file, there are no
1643 more bytes than have been requested. So reposition the
1644 file pointer to the incoming current position and print
1645 everything after that. */
1646 *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1648 else
1650 /* There are more bytes remaining than were requested.
1651 Back up. */
1652 *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
1654 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1656 else
1657 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1659 return true;
1662 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1663 Return true if successful. */
1665 static bool
1666 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1667 uintmax_t *read_pos)
1669 struct stat stats;
1671 if (fstat (fd, &stats))
1673 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1674 return false;
1677 if (from_start)
1679 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1680 if (t)
1681 return t < 0;
1682 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1684 else
1686 off_t start_pos = -1;
1687 off_t end_pos;
1689 /* Use file_lines only if FD refers to a regular file for
1690 which lseek (... SEEK_END) works. */
1691 if ( ! presume_input_pipe
1692 && S_ISREG (stats.st_mode)
1693 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1694 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1696 *read_pos = end_pos;
1697 if (end_pos != 0
1698 && ! file_lines (pretty_filename, fd, n_lines,
1699 start_pos, end_pos, read_pos))
1700 return false;
1702 else
1704 /* Under very unlikely circumstances, it is possible to reach
1705 this point after positioning the file pointer to end of file
1706 via the 'lseek (...SEEK_END)' above. In that case, reposition
1707 the file pointer back to start_pos before calling pipe_lines. */
1708 if (start_pos != -1)
1709 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1711 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1714 return true;
1717 /* Display the last N_UNITS units of file FILENAME, open for reading
1718 via FD. Set *READ_POS to the position of the input stream pointer.
1719 *READ_POS is usually the number of bytes read and corresponds to an
1720 offset from the beginning of a file. However, it may be larger than
1721 OFF_T_MAX (as for an input pipe), and may also be larger than the
1722 number of bytes read (when an input pointer is initially not at
1723 beginning of file), and may be far greater than the number of bytes
1724 actually read for an input file that is seekable.
1725 Return true if successful. */
1727 static bool
1728 tail (const char *filename, int fd, uintmax_t n_units,
1729 uintmax_t *read_pos)
1731 *read_pos = 0;
1732 if (count_lines)
1733 return tail_lines (filename, fd, n_units, read_pos);
1734 else
1735 return tail_bytes (filename, fd, n_units, read_pos);
1738 /* Display the last N_UNITS units of the file described by F.
1739 Return true if successful. */
1741 static bool
1742 tail_file (struct File_spec *f, uintmax_t n_units)
1744 int fd;
1745 bool ok;
1747 bool is_stdin = (STREQ (f->name, "-"));
1749 if (is_stdin)
1751 have_read_stdin = true;
1752 fd = STDIN_FILENO;
1753 if (O_BINARY && ! isatty (STDIN_FILENO))
1754 xfreopen (NULL, "rb", stdin);
1756 else
1757 fd = open (f->name, O_RDONLY | O_BINARY);
1759 f->tailable = !(reopen_inaccessible_files && fd == -1);
1761 if (fd == -1)
1763 if (forever)
1765 f->fd = -1;
1766 f->errnum = errno;
1767 f->ignore = false;
1768 f->ino = 0;
1769 f->dev = 0;
1771 error (0, errno, _("cannot open %s for reading"),
1772 quote (pretty_name (f)));
1773 ok = false;
1775 else
1777 uintmax_t read_pos;
1779 if (print_headers)
1780 write_header (pretty_name (f));
1781 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1782 if (forever)
1784 struct stat stats;
1786 #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1787 /* Before the tail function provided 'read_pos', there was
1788 a race condition described in the URL below. This sleep
1789 call made the window big enough to exercise the problem. */
1790 xnanosleep (1);
1791 #endif
1792 f->errnum = ok - 1;
1793 if (fstat (fd, &stats) < 0)
1795 ok = false;
1796 f->errnum = errno;
1797 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1799 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1801 error (0, 0, _("%s: cannot follow end of this type of file;\
1802 giving up on this name"),
1803 pretty_name (f));
1804 ok = false;
1805 f->errnum = -1;
1806 f->ignore = true;
1809 if (!ok)
1811 close_fd (fd, pretty_name (f));
1812 f->fd = -1;
1814 else
1816 /* Note: we must use read_pos here, not stats.st_size,
1817 to avoid a race condition described by Ken Raeburn:
1818 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1819 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1820 f->remote = fremote (fd, pretty_name (f));
1823 else
1825 if (!is_stdin && close (fd))
1827 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1828 ok = false;
1833 return ok;
1836 /* If obsolete usage is allowed, and the command line arguments are of
1837 the obsolete form and the option string is well-formed, set
1838 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1839 return true. If the command line arguments are obviously incorrect
1840 (e.g., because obsolete usage is not allowed and the arguments are
1841 incorrect for non-obsolete usage), report an error and exit.
1842 Otherwise, return false and don't modify any parameter or global
1843 variable. */
1845 static bool
1846 parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1848 const char *p;
1849 const char *n_string;
1850 const char *n_string_end;
1851 bool obsolete_usage;
1852 int default_count = DEFAULT_N_LINES;
1853 bool t_from_start;
1854 bool t_count_lines = true;
1855 bool t_forever = false;
1857 /* With the obsolete form, there is one option string and at most
1858 one file argument. Watch out for "-" and "--", though. */
1859 if (! (argc == 2
1860 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1861 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1862 return false;
1864 obsolete_usage = (posix2_version () < 200112);
1865 p = argv[1];
1867 switch (*p++)
1869 default:
1870 return false;
1872 case '+':
1873 /* Leading "+" is a file name in the non-obsolete form. */
1874 if (!obsolete_usage)
1875 return false;
1877 t_from_start = true;
1878 break;
1880 case '-':
1881 /* In the non-obsolete form, "-" is standard input and "-c"
1882 requires an option-argument. The obsolete multidigit options
1883 are supported as a GNU extension even when conforming to
1884 POSIX 1003.1-2001, so don't complain about them. */
1885 if (!obsolete_usage && !p[p[0] == 'c'])
1886 return false;
1888 t_from_start = false;
1889 break;
1892 n_string = p;
1893 while (ISDIGIT (*p))
1894 p++;
1895 n_string_end = p;
1897 switch (*p)
1899 case 'b': default_count *= 512; /* Fall through. */
1900 case 'c': t_count_lines = false; /* Fall through. */
1901 case 'l': p++; break;
1904 if (*p == 'f')
1906 t_forever = true;
1907 ++p;
1910 if (*p)
1911 return false;
1913 if (n_string == n_string_end)
1914 *n_units = default_count;
1915 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
1916 & ~LONGINT_INVALID_SUFFIX_CHAR)
1917 != LONGINT_OK)
1918 error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1]));
1920 /* Set globals. */
1921 from_start = t_from_start;
1922 count_lines = t_count_lines;
1923 forever = t_forever;
1925 return true;
1928 static void
1929 parse_options (int argc, char **argv,
1930 uintmax_t *n_units, enum header_mode *header_mode,
1931 double *sleep_interval)
1933 int c;
1935 while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789",
1936 long_options, NULL))
1937 != -1)
1939 switch (c)
1941 case 'F':
1942 forever = true;
1943 follow_mode = Follow_name;
1944 reopen_inaccessible_files = true;
1945 break;
1947 case 'c':
1948 case 'n':
1949 count_lines = (c == 'n');
1950 if (*optarg == '+')
1951 from_start = true;
1952 else if (*optarg == '-')
1953 ++optarg;
1956 strtol_error s_err;
1957 s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0");
1958 if (s_err != LONGINT_OK)
1960 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1961 (c == 'n'
1962 ? _("invalid number of lines")
1963 : _("invalid number of bytes")));
1966 break;
1968 case 'f':
1969 case LONG_FOLLOW_OPTION:
1970 forever = true;
1971 if (optarg == NULL)
1972 follow_mode = DEFAULT_FOLLOW_MODE;
1973 else
1974 follow_mode = XARGMATCH ("--follow", optarg,
1975 follow_mode_string, follow_mode_map);
1976 break;
1978 case RETRY_OPTION:
1979 reopen_inaccessible_files = true;
1980 break;
1982 case MAX_UNCHANGED_STATS_OPTION:
1983 /* --max-unchanged-stats=N */
1984 if (xstrtoumax (optarg, NULL, 10,
1985 &max_n_unchanged_stats_between_opens,
1987 != LONGINT_OK)
1989 error (EXIT_FAILURE, 0,
1990 _("%s: invalid maximum number of unchanged stats between opens"),
1991 optarg);
1993 break;
1995 case DISABLE_INOTIFY_OPTION:
1996 disable_inotify = true;
1997 break;
1999 case PID_OPTION:
2001 strtol_error s_err;
2002 unsigned long int tmp_ulong;
2003 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
2004 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
2006 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
2008 pid = tmp_ulong;
2010 break;
2012 case PRESUME_INPUT_PIPE_OPTION:
2013 presume_input_pipe = true;
2014 break;
2016 case 'q':
2017 *header_mode = never;
2018 break;
2020 case 's':
2022 double s;
2023 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
2024 error (EXIT_FAILURE, 0,
2025 _("%s: invalid number of seconds"), optarg);
2026 *sleep_interval = s;
2028 break;
2030 case 'v':
2031 *header_mode = always;
2032 break;
2034 case_GETOPT_HELP_CHAR;
2036 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
2038 case '0': case '1': case '2': case '3': case '4':
2039 case '5': case '6': case '7': case '8': case '9':
2040 error (EXIT_FAILURE, 0,
2041 _("option used in invalid context -- %c"), c);
2043 default:
2044 usage (EXIT_FAILURE);
2048 if (reopen_inaccessible_files)
2050 if (!forever)
2052 reopen_inaccessible_files = false;
2053 error (0, 0, _("warning: --retry ignored; --retry is useful"
2054 " only when following"));
2056 else if (follow_mode == Follow_descriptor)
2057 error (0, 0, _("warning: --retry only effective for the initial open"));
2060 if (pid && !forever)
2061 error (0, 0,
2062 _("warning: PID ignored; --pid=PID is useful only when following"));
2063 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
2065 error (0, 0, _("warning: --pid=PID is not supported on this system"));
2066 pid = 0;
2070 /* Mark as '.ignore'd each member of F that corresponds to a
2071 pipe or fifo, and return the number of non-ignored members. */
2072 static size_t
2073 ignore_fifo_and_pipe (struct File_spec *f, size_t n_files)
2075 /* When there is no FILE operand and stdin is a pipe or FIFO
2076 POSIX requires that tail ignore the -f option.
2077 Since we allow multiple FILE operands, we extend that to say: with -f,
2078 ignore any "-" operand that corresponds to a pipe or FIFO. */
2079 size_t n_viable = 0;
2081 size_t i;
2082 for (i = 0; i < n_files; i++)
2084 bool is_a_fifo_or_pipe =
2085 (STREQ (f[i].name, "-")
2086 && !f[i].ignore
2087 && 0 <= f[i].fd
2088 && (S_ISFIFO (f[i].mode)
2089 || (HAVE_FIFO_PIPES != 1 && isapipe (f[i].fd))));
2090 if (is_a_fifo_or_pipe)
2091 f[i].ignore = true;
2092 else
2093 ++n_viable;
2096 return n_viable;
2100 main (int argc, char **argv)
2102 enum header_mode header_mode = multiple_files;
2103 bool ok = true;
2104 /* If from_start, the number of items to skip before printing; otherwise,
2105 the number of items at the end of the file to print. Although the type
2106 is signed, the value is never negative. */
2107 uintmax_t n_units = DEFAULT_N_LINES;
2108 size_t n_files;
2109 char **file;
2110 struct File_spec *F;
2111 size_t i;
2112 bool obsolete_option;
2114 /* The number of seconds to sleep between iterations.
2115 During one iteration, every file name or descriptor is checked to
2116 see if it has changed. */
2117 double sleep_interval = 1.0;
2119 initialize_main (&argc, &argv);
2120 set_program_name (argv[0]);
2121 setlocale (LC_ALL, "");
2122 bindtextdomain (PACKAGE, LOCALEDIR);
2123 textdomain (PACKAGE);
2125 atexit (close_stdout);
2127 have_read_stdin = false;
2129 count_lines = true;
2130 forever = from_start = print_headers = false;
2131 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
2132 argc -= obsolete_option;
2133 argv += obsolete_option;
2134 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
2136 /* To start printing with item N_UNITS from the start of the file, skip
2137 N_UNITS - 1 items. 'tail -n +0' is actually meaningless, but for Unix
2138 compatibility it's treated the same as 'tail -n +1'. */
2139 if (from_start)
2141 if (n_units)
2142 --n_units;
2145 if (optind < argc)
2147 n_files = argc - optind;
2148 file = argv + optind;
2150 else
2152 static char *dummy_stdin = (char *) "-";
2153 n_files = 1;
2154 file = &dummy_stdin;
2158 bool found_hyphen = false;
2160 for (i = 0; i < n_files; i++)
2161 if (STREQ (file[i], "-"))
2162 found_hyphen = true;
2164 /* When following by name, there must be a name. */
2165 if (found_hyphen && follow_mode == Follow_name)
2166 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
2168 /* When following forever, warn if any file is '-'.
2169 This is only a warning, since tail's output (before a failing seek,
2170 and that from any non-stdin files) might still be useful. */
2171 if (forever && found_hyphen && isatty (STDIN_FILENO))
2172 error (0, 0, _("warning: following standard input"
2173 " indefinitely is ineffective"));
2176 /* Don't read anything if we'll never output anything. */
2177 if (! n_units && ! forever && ! from_start)
2178 exit (EXIT_SUCCESS);
2180 F = xnmalloc (n_files, sizeof *F);
2181 for (i = 0; i < n_files; i++)
2182 F[i].name = file[i];
2184 if (header_mode == always
2185 || (header_mode == multiple_files && n_files > 1))
2186 print_headers = true;
2188 if (O_BINARY && ! isatty (STDOUT_FILENO))
2189 xfreopen (NULL, "wb", stdout);
2191 for (i = 0; i < n_files; i++)
2192 ok &= tail_file (&F[i], n_units);
2194 if (forever && ignore_fifo_and_pipe (F, n_files))
2196 #if HAVE_INOTIFY
2197 /* tailable_stdin() checks if the user specifies stdin via "-",
2198 or implicitly by providing no arguments. If so, we won't use inotify.
2199 Technically, on systems with a working /dev/stdin, we *could*,
2200 but would it be worth it? Verifying that it's a real device
2201 and hooked up to stdin is not trivial, while reverting to
2202 non-inotify-based tail_forever is easy and portable.
2204 any_remote_file() checks if the user has specified any
2205 files that reside on remote file systems. inotify is not used
2206 in this case because it would miss any updates to the file
2207 that were not initiated from the local system.
2209 ok is false when one of the files specified could not be opened for
2210 reading. In this case and when following by descriptor,
2211 tail_forever_inotify() cannot be used (in its current implementation).
2213 FIXME: inotify doesn't give any notification when a new
2214 (remote) file or directory is mounted on top a watched file.
2215 When follow_mode == Follow_name we would ideally like to detect that.
2216 Note if there is a change to the original file then we'll
2217 recheck it and follow the new file, or ignore it if the
2218 file has changed to being remote.
2220 FIXME: when using inotify, and a directory for a watched file
2221 is recreated, then we don't recheck any new file when
2222 follow_mode == Follow_name */
2223 if (!disable_inotify && (tailable_stdin (F, n_files)
2224 || any_remote_file (F, n_files)
2225 || (!ok && follow_mode == Follow_descriptor)))
2226 disable_inotify = true;
2228 if (!disable_inotify)
2230 int wd = inotify_init ();
2231 if (0 <= wd)
2233 /* Flush any output from tail_file, now, since
2234 tail_forever_inotify flushes only after writing,
2235 not before reading. */
2236 if (fflush (stdout) != 0)
2237 error (EXIT_FAILURE, errno, _("write error"));
2239 if (!tail_forever_inotify (wd, F, n_files, sleep_interval))
2240 exit (EXIT_FAILURE);
2242 error (0, errno, _("inotify cannot be used, reverting to polling"));
2244 #endif
2245 disable_inotify = true;
2246 tail_forever (F, n_files, sleep_interval);
2249 if (have_read_stdin && close (STDIN_FILENO) < 0)
2250 error (EXIT_FAILURE, errno, "-");
2251 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);