LCOV - code coverage report
Current view: top level - src - tail.c (source / functions) Hit Total Coverage
Test: coreutils.info Lines: 463 632 73.3 %
Date: 2018-01-30 Functions: 24 24 100.0 %

          Line data    Source code
       1             : /* tail -- output the last part of file(s)
       2             :    Copyright (C) 1989, 90, 91, 1995-2006 Free Software Foundation, Inc.
       3             : 
       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.
       8             : 
       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.
      13             : 
      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/>.  */
      16             : 
      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.
      20             : 
      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             : 
      25             : #include <config.h>
      26             : 
      27             : #include <stdio.h>
      28             : #include <assert.h>
      29             : #include <getopt.h>
      30             : #include <sys/types.h>
      31             : #include <signal.h>
      32             : 
      33             : #include "system.h"
      34             : #include "argmatch.h"
      35             : #include "c-strtod.h"
      36             : #include "error.h"
      37             : #include "fcntl--.h"
      38             : #include "inttostr.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 "xnanosleep.h"
      45             : #include "xstrtol.h"
      46             : #include "xstrtod.h"
      47             : 
      48             : /* The official name of this program (e.g., no `g' prefix).  */
      49             : #define PROGRAM_NAME "tail"
      50             : 
      51             : #define AUTHORS \
      52             :   "Paul Rubin", "David MacKenzie, Ian Lance Taylor", "Jim Meyering"
      53             : 
      54             : /* Number of items to tail.  */
      55             : #define DEFAULT_N_LINES 10
      56             : 
      57             : /* Special values for dump_remainder's N_BYTES parameter.  */
      58             : #define COPY_TO_EOF UINTMAX_MAX
      59             : #define COPY_A_BUFFER (UINTMAX_MAX - 1)
      60             : 
      61             : /* FIXME: make Follow_name the default?  */
      62             : #define DEFAULT_FOLLOW_MODE Follow_descriptor
      63             : 
      64             : enum Follow_mode
      65             : {
      66             :   /* Follow the name of each file: if the file is renamed, try to reopen
      67             :      that name and track the end of the new file if/when it's recreated.
      68             :      This is useful for tracking logs that are occasionally rotated.  */
      69             :   Follow_name = 1,
      70             : 
      71             :   /* Follow each descriptor obtained upon opening a file.
      72             :      That means we'll continue to follow the end of a file even after
      73             :      it has been renamed or unlinked.  */
      74             :   Follow_descriptor = 2
      75             : };
      76             : 
      77             : /* The types of files for which tail works.  */
      78             : #define IS_TAILABLE_FILE_TYPE(Mode) \
      79             :   (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
      80             : 
      81             : static char const *const follow_mode_string[] =
      82             : {
      83             :   "descriptor", "name", NULL
      84             : };
      85             : 
      86             : static enum Follow_mode const follow_mode_map[] =
      87             : {
      88             :   Follow_descriptor, Follow_name,
      89             : };
      90             : 
      91             : struct File_spec
      92             : {
      93             :   /* The actual file name, or "-" for stdin.  */
      94             :   char *name;
      95             : 
      96             :   /* File descriptor on which the file is open; -1 if it's not open.  */
      97             :   int fd;
      98             : 
      99             :   /* Attributes of the file the last time we checked.  */
     100             :   off_t size;
     101             :   struct timespec mtime;
     102             :   dev_t dev;
     103             :   ino_t ino;
     104             :   mode_t mode;
     105             : 
     106             :   /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known.  */
     107             :   int blocking;
     108             : 
     109             :   /* The specified name initially referred to a directory or some other
     110             :      type for which tail isn't meaningful.  Unlike for a permission problem
     111             :      (tailable, below) once this is set, the name is not checked ever again.  */
     112             :   bool ignore;
     113             : 
     114             :   /* See description of DEFAULT_MAX_N_... below.  */
     115             :   uintmax_t n_unchanged_stats;
     116             : 
     117             :   /* A file is tailable if it exists, is readable, and is of type
     118             :      IS_TAILABLE_FILE_TYPE.  */
     119             :   bool tailable;
     120             : 
     121             :   /* The value of errno seen last time we checked this file.  */
     122             :   int errnum;
     123             : 
     124             : };
     125             : 
     126             : /* Keep trying to open a file even if it is inaccessible when tail starts
     127             :    or if it becomes inaccessible later -- useful only with -f.  */
     128             : static bool reopen_inaccessible_files;
     129             : 
     130             : /* If true, interpret the numeric argument as the number of lines.
     131             :    Otherwise, interpret it as the number of bytes.  */
     132             : static bool count_lines;
     133             : 
     134             : /* Whether we follow the name of each file or the file descriptor
     135             :    that is initially associated with each name.  */
     136             : static enum Follow_mode follow_mode = Follow_descriptor;
     137             : 
     138             : /* If true, read from the ends of all specified files until killed.  */
     139             : static bool forever;
     140             : 
     141             : /* If true, count from start of file instead of end.  */
     142             : static bool from_start;
     143             : 
     144             : /* If true, print filename headers.  */
     145             : static bool print_headers;
     146             : 
     147             : /* When to print the filename banners.  */
     148             : enum header_mode
     149             : {
     150             :   multiple_files, always, never
     151             : };
     152             : 
     153             : /* When tailing a file by name, if there have been this many consecutive
     154             :    iterations for which the file has not changed, then open/fstat
     155             :    the file to determine if that file name is still associated with the
     156             :    same device/inode-number pair as before.  This option is meaningful only
     157             :    when following by name.  --max-unchanged-stats=N  */
     158             : #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
     159             : static uintmax_t max_n_unchanged_stats_between_opens =
     160             :   DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
     161             : 
     162             : /* The name this program was run with.  */
     163             : char *program_name;
     164             : 
     165             : /* The process ID of the process (presumably on the current host)
     166             :    that is writing to all followed files.  */
     167             : static pid_t pid;
     168             : 
     169             : /* True if we have ever read standard input.  */
     170             : static bool have_read_stdin;
     171             : 
     172             : /* If nonzero, skip the is-regular-file test used to determine whether
     173             :    to use the lseek optimization.  Instead, use the more general (and
     174             :    more expensive) code unconditionally. Intended solely for testing.  */
     175             : static bool presume_input_pipe;
     176             : 
     177             : /* For long options that have no equivalent short option, use a
     178             :    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
     179             : enum
     180             : {
     181             :   RETRY_OPTION = CHAR_MAX + 1,
     182             :   MAX_UNCHANGED_STATS_OPTION,
     183             :   PID_OPTION,
     184             :   PRESUME_INPUT_PIPE_OPTION,
     185             :   LONG_FOLLOW_OPTION
     186             : };
     187             : 
     188             : static struct option const long_options[] =
     189             : {
     190             :   {"bytes", required_argument, NULL, 'c'},
     191             :   {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
     192             :   {"lines", required_argument, NULL, 'n'},
     193             :   {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
     194             :   {"pid", required_argument, NULL, PID_OPTION},
     195             :   {"-presume-input-pipe", no_argument, NULL,
     196             :    PRESUME_INPUT_PIPE_OPTION}, /* do not document */
     197             :   {"quiet", no_argument, NULL, 'q'},
     198             :   {"retry", no_argument, NULL, RETRY_OPTION},
     199             :   {"silent", no_argument, NULL, 'q'},
     200             :   {"sleep-interval", required_argument, NULL, 's'},
     201             :   {"verbose", no_argument, NULL, 'v'},
     202             :   {GETOPT_HELP_OPTION_DECL},
     203             :   {GETOPT_VERSION_OPTION_DECL},
     204             :   {NULL, 0, NULL, 0}
     205             : };
     206             : 
     207             : void
     208          18 : usage (int status)
     209             : {
     210          18 :   if (status != EXIT_SUCCESS)
     211          18 :     fprintf (stderr, _("Try `%s --help' for more information.\n"),
     212             :              program_name);
     213             :   else
     214             :     {
     215           0 :       printf (_("\
     216             : Usage: %s [OPTION]... [FILE]...\n\
     217             : "),
     218             :               program_name);
     219           0 :       printf (_("\
     220             : Print the last %d lines of each FILE to standard output.\n\
     221             : With more than one FILE, precede each with a header giving the file name.\n\
     222             : With no FILE, or when FILE is -, read standard input.\n\
     223             : \n\
     224             : "), DEFAULT_N_LINES);
     225           0 :      fputs (_("\
     226             : Mandatory arguments to long options are mandatory for short options too.\n\
     227             : "), stdout);
     228           0 :      fputs (_("\
     229             :       --retry              keep trying to open a file even if it is\n\
     230             :                            inaccessible when tail starts or if it becomes\n\
     231             :                            inaccessible later; useful when following by name,\n\
     232             :                            i.e., with --follow=name\n\
     233             :   -c, --bytes=N            output the last N bytes; alternatively, use +N to\n\
     234             :                            output bytes starting with the Nth of each file\n\
     235             : "), stdout);
     236           0 :      fputs (_("\
     237             :   -f, --follow[={name|descriptor}]\n\
     238             :                            output appended data as the file grows;\n\
     239             :                            -f, --follow, and --follow=descriptor are\n\
     240             :                            equivalent\n\
     241             :   -F                       same as --follow=name --retry\n\
     242             : "), stdout);
     243           0 :      printf (_("\
     244             :   -n, --lines=N            output the last N lines, instead of the last %d;\n\
     245             :                            or use +N to output lines starting with the Nth\n\
     246             :       --max-unchanged-stats=N\n\
     247             :                            with --follow=name, reopen a FILE which has not\n\
     248             :                            changed size after N (default %d) iterations\n\
     249             :                            to see if it has been unlinked or renamed\n\
     250             :                            (this is the usual case of rotated log files)\n\
     251             : "),
     252             :              DEFAULT_N_LINES,
     253             :              DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
     254             :              );
     255           0 :      fputs (_("\
     256             :       --pid=PID            with -f, terminate after process ID, PID dies\n\
     257             :   -q, --quiet, --silent    never output headers giving file names\n\
     258             :   -s, --sleep-interval=S   with -f, sleep for approximately S seconds\n\
     259             :                            (default 1.0) between iterations.\n\
     260             :   -v, --verbose            always output headers giving file names\n\
     261             : "), stdout);
     262           0 :      fputs (HELP_OPTION_DESCRIPTION, stdout);
     263           0 :      fputs (VERSION_OPTION_DESCRIPTION, stdout);
     264           0 :      fputs (_("\
     265             : \n\
     266             : If the first character of N (the number of bytes or lines) is a `+',\n\
     267             : print beginning with the Nth item from the start of each file, otherwise,\n\
     268             : print the last N items in the file.  N may have a multiplier suffix:\n\
     269             : b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
     270             : GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
     271             : \n\
     272             : "), stdout);
     273           0 :      fputs (_("\
     274             : With --follow (-f), tail defaults to following the file descriptor, which\n\
     275             : means that even if a tail'ed file is renamed, tail will continue to track\n\
     276             : its end.  \
     277             : "), stdout);
     278           0 :      fputs (_("\
     279             : This default behavior is not desirable when you really want to\n\
     280             : track the actual name of the file, not the file descriptor (e.g., log\n\
     281             : rotation).  Use --follow=name in that case.  That causes tail to track the\n\
     282             : named file by reopening it periodically to see if it has been removed and\n\
     283             : recreated by some other program.\n\
     284             : "), stdout);
     285           0 :       emit_bug_reporting_address ();
     286             :     }
     287          18 :   exit (status);
     288             : }
     289             : 
     290             : static bool
     291          15 : valid_file_spec (struct File_spec const *f)
     292             : {
     293             :   /* Exactly one of the following subexpressions must be true. */
     294          15 :   return ((f->fd == -1) ^ (f->errnum == 0));
     295             : }
     296             : 
     297             : static char const *
     298         177 : pretty_name (struct File_spec const *f)
     299             : {
     300         177 :   return (STREQ (f->name, "-") ? "standard input" : f->name);
     301             : }
     302             : 
     303             : static void
     304          44 : xwrite_stdout (char const *buffer, size_t n_bytes)
     305             : {
     306          44 :   if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
     307           0 :     error (EXIT_FAILURE, errno, _("write error"));
     308          44 : }
     309             : 
     310             : /* Record a file F with descriptor FD, size SIZE, status ST, and
     311             :    blocking status BLOCKING.  */
     312             : 
     313             : static void
     314          12 : record_open_fd (struct File_spec *f, int fd,
     315             :                 off_t size, struct stat const *st,
     316             :                 int blocking)
     317             : {
     318          12 :   f->fd = fd;
     319          12 :   f->size = size;
     320          12 :   f->mtime = get_stat_mtime (st);
     321          12 :   f->dev = st->st_dev;
     322          12 :   f->ino = st->st_ino;
     323          12 :   f->mode = st->st_mode;
     324          12 :   f->blocking = blocking;
     325          12 :   f->n_unchanged_stats = 0;
     326          12 :   f->ignore = 0;
     327          12 : }
     328             : 
     329             : /* Close the file with descriptor FD and name FILENAME.  */
     330             : 
     331             : static void
     332          21 : close_fd (int fd, const char *filename)
     333             : {
     334          21 :   if (fd != -1 && fd != STDIN_FILENO && close (fd))
     335             :     {
     336           0 :       error (0, errno, _("closing %s (fd=%d)"), filename, fd);
     337             :     }
     338          21 : }
     339             : 
     340             : static void
     341          30 : write_header (const char *pretty_filename)
     342             : {
     343             :   static bool first_file = true;
     344             : 
     345          30 :   printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
     346          30 :   first_file = false;
     347          30 : }
     348             : 
     349             : /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
     350             :    position in FD.  If N_BYTES is COPY_TO_EOF, then copy until end of file.
     351             :    If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
     352             :    Return the number of bytes read from the file.  */
     353             : 
     354             : static uintmax_t
     355          47 : dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
     356             : {
     357             :   uintmax_t n_written;
     358          47 :   uintmax_t n_remaining = n_bytes;
     359             : 
     360          47 :   n_written = 0;
     361             :   while (1)
     362          10 :     {
     363             :       char buffer[BUFSIZ];
     364          57 :       size_t n = MIN (n_remaining, BUFSIZ);
     365          57 :       size_t bytes_read = safe_read (fd, buffer, n);
     366          57 :       if (bytes_read == SAFE_READ_ERROR)
     367             :         {
     368           1 :           if (errno != EAGAIN)
     369           1 :             error (EXIT_FAILURE, errno, _("error reading %s"),
     370             :                    quote (pretty_filename));
     371          46 :           break;
     372             :         }
     373          56 :       if (bytes_read == 0)
     374          22 :         break;
     375          34 :       xwrite_stdout (buffer, bytes_read);
     376          34 :       n_written += bytes_read;
     377          34 :       if (n_bytes != COPY_TO_EOF)
     378             :         {
     379          30 :           n_remaining -= bytes_read;
     380          30 :           if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
     381             :             break;
     382             :         }
     383             :     }
     384             : 
     385          46 :   return n_written;
     386             : }
     387             : 
     388             : /* Call lseek with the specified arguments, where file descriptor FD
     389             :    corresponds to the file, FILENAME.
     390             :    Give a diagnostic and exit nonzero if lseek fails.
     391             :    Otherwise, return the resulting offset.  */
     392             : 
     393             : static off_t
     394          98 : xlseek (int fd, off_t offset, int whence, char const *filename)
     395             : {
     396          98 :   off_t new_offset = lseek (fd, offset, whence);
     397             :   char buf[INT_BUFSIZE_BOUND (off_t)];
     398             :   char *s;
     399             : 
     400          98 :   if (0 <= new_offset)
     401         176 :     return new_offset;
     402             : 
     403          10 :   s = offtostr (offset, buf);
     404          10 :   switch (whence)
     405             :     {
     406          10 :     case SEEK_SET:
     407          10 :       error (0, errno, _("%s: cannot seek to offset %s"),
     408             :              filename, s);
     409          10 :       break;
     410           0 :     case SEEK_CUR:
     411           0 :       error (0, errno, _("%s: cannot seek to relative offset %s"),
     412             :              filename, s);
     413           0 :       break;
     414           0 :     case SEEK_END:
     415           0 :       error (0, errno, _("%s: cannot seek to end-relative offset %s"),
     416             :              filename, s);
     417           0 :       break;
     418           0 :     default:
     419           0 :       abort ();
     420             :     }
     421             : 
     422          10 :   exit (EXIT_FAILURE);
     423             : }
     424             : 
     425             : /* Print the last N_LINES lines from the end of file FD.
     426             :    Go backward through the file, reading `BUFSIZ' bytes at a time (except
     427             :    probably the first), until we hit the start of the file or have
     428             :    read NUMBER newlines.
     429             :    START_POS is the starting position of the read pointer for the file
     430             :    associated with FD (may be nonzero).
     431             :    END_POS is the file offset of EOF (one larger than offset of last byte).
     432             :    Return true if successful.  */
     433             : 
     434             : static bool
     435          26 : file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
     436             :             off_t start_pos, off_t end_pos, uintmax_t *read_pos)
     437             : {
     438             :   char buffer[BUFSIZ];
     439             :   size_t bytes_read;
     440          26 :   off_t pos = end_pos;
     441             : 
     442          26 :   if (n_lines == 0)
     443           2 :     return true;
     444             : 
     445             :   /* Set `bytes_read' to the size of the last, probably partial, buffer;
     446             :      0 < `bytes_read' <= `BUFSIZ'.  */
     447          24 :   bytes_read = (pos - start_pos) % BUFSIZ;
     448          24 :   if (bytes_read == 0)
     449           0 :     bytes_read = BUFSIZ;
     450             :   /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
     451             :      reads will be on block boundaries, which might increase efficiency.  */
     452          24 :   pos -= bytes_read;
     453          24 :   xlseek (fd, pos, SEEK_SET, pretty_filename);
     454          24 :   bytes_read = safe_read (fd, buffer, bytes_read);
     455          24 :   if (bytes_read == SAFE_READ_ERROR)
     456             :     {
     457           0 :       error (0, errno, _("error reading %s"), quote (pretty_filename));
     458           0 :       return false;
     459             :     }
     460          24 :   *read_pos = pos + bytes_read;
     461             : 
     462             :   /* Count the incomplete line on files that don't end with a newline.  */
     463          24 :   if (bytes_read && buffer[bytes_read - 1] != '\n')
     464           3 :     --n_lines;
     465             : 
     466             :   do
     467             :     {
     468             :       /* Scan backward, counting the newlines in this bufferfull.  */
     469             : 
     470          24 :       size_t n = bytes_read;
     471         221 :       while (n)
     472             :         {
     473             :           char const *nl;
     474         176 :           nl = memrchr (buffer, '\n', n);
     475         176 :           if (nl == NULL)
     476           2 :             break;
     477         174 :           n = nl - buffer;
     478         174 :           if (n_lines-- == 0)
     479             :             {
     480             :               /* If this newline isn't the last character in the buffer,
     481             :                  output the part that is after it.  */
     482           1 :               if (n != bytes_read - 1)
     483           1 :                 xwrite_stdout (nl + 1, bytes_read - (n + 1));
     484           2 :               *read_pos += dump_remainder (pretty_filename, fd,
     485           1 :                                            end_pos - (pos + bytes_read));
     486           1 :               return true;
     487             :             }
     488             :         }
     489             : 
     490             :       /* Not enough newlines in that bufferfull.  */
     491          23 :       if (pos == start_pos)
     492             :         {
     493             :           /* Not enough lines in the file; print everything from
     494             :              start_pos to the end.  */
     495          23 :           xlseek (fd, start_pos, SEEK_SET, pretty_filename);
     496          23 :           *read_pos = start_pos + dump_remainder (pretty_filename, fd,
     497             :                                                   end_pos);
     498          23 :           return true;
     499             :         }
     500           0 :       pos -= BUFSIZ;
     501           0 :       xlseek (fd, pos, SEEK_SET, pretty_filename);
     502             : 
     503           0 :       bytes_read = safe_read (fd, buffer, BUFSIZ);
     504           0 :       if (bytes_read == SAFE_READ_ERROR)
     505             :         {
     506           0 :           error (0, errno, _("error reading %s"), quote (pretty_filename));
     507           0 :           return false;
     508             :         }
     509             : 
     510           0 :       *read_pos = pos + bytes_read;
     511             :     }
     512           0 :   while (bytes_read > 0);
     513             : 
     514           0 :   return true;
     515             : }
     516             : 
     517             : /* Print the last N_LINES lines from the end of the standard input,
     518             :    open for reading as pipe FD.
     519             :    Buffer the text as a linked list of LBUFFERs, adding them as needed.
     520             :    Return true if successful.  */
     521             : 
     522             : static bool
     523          25 : pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
     524             :             uintmax_t *read_pos)
     525             : {
     526             :   struct linebuffer
     527             :   {
     528             :     char buffer[BUFSIZ];
     529             :     size_t nbytes;
     530             :     size_t nlines;
     531             :     struct linebuffer *next;
     532             :   };
     533             :   typedef struct linebuffer LBUFFER;
     534             :   LBUFFER *first, *last, *tmp;
     535          25 :   size_t total_lines = 0;       /* Total number of newlines in all buffers.  */
     536          25 :   bool ok = true;
     537             :   size_t n_read;                /* Size in bytes of most recent read */
     538             : 
     539          25 :   first = last = xmalloc (sizeof (LBUFFER));
     540          25 :   first->nbytes = first->nlines = 0;
     541          25 :   first->next = NULL;
     542          25 :   tmp = xmalloc (sizeof (LBUFFER));
     543             : 
     544             :   /* Input is always read into a fresh buffer.  */
     545             :   while (1)
     546             :     {
     547          55 :       n_read = safe_read (fd, tmp->buffer, BUFSIZ);
     548          40 :       if (n_read == 0 || n_read == SAFE_READ_ERROR)
     549             :         break;
     550          15 :       tmp->nbytes = n_read;
     551          15 :       *read_pos += n_read;
     552          15 :       tmp->nlines = 0;
     553          15 :       tmp->next = NULL;
     554             : 
     555             :       /* Count the number of newlines just read.  */
     556             :       {
     557          15 :         char const *buffer_end = tmp->buffer + n_read;
     558          15 :         char const *p = tmp->buffer;
     559         134 :         while ((p = memchr (p, '\n', buffer_end - p)))
     560             :           {
     561         104 :             ++p;
     562         104 :             ++tmp->nlines;
     563             :           }
     564             :       }
     565          15 :       total_lines += tmp->nlines;
     566             : 
     567             :       /* If there is enough room in the last buffer read, just append the new
     568             :          one to it.  This is because when reading from a pipe, `n_read' can
     569             :          often be very small.  */
     570          15 :       if (tmp->nbytes + last->nbytes < BUFSIZ)
     571             :         {
     572          15 :           memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
     573          15 :           last->nbytes += tmp->nbytes;
     574          15 :           last->nlines += tmp->nlines;
     575             :         }
     576             :       else
     577             :         {
     578             :           /* If there's not enough room, link the new buffer onto the end of
     579             :              the list, then either free up the oldest buffer for the next
     580             :              read if that would leave enough lines, or else malloc a new one.
     581             :              Some compaction mechanism is possible but probably not
     582             :              worthwhile.  */
     583           0 :           last = last->next = tmp;
     584           0 :           if (total_lines - first->nlines > n_lines)
     585             :             {
     586           0 :               tmp = first;
     587           0 :               total_lines -= first->nlines;
     588           0 :               first = first->next;
     589             :             }
     590             :           else
     591           0 :             tmp = xmalloc (sizeof (LBUFFER));
     592             :         }
     593             :     }
     594             : 
     595          25 :   free (tmp);
     596             : 
     597          25 :   if (n_read == SAFE_READ_ERROR)
     598             :     {
     599          11 :       error (0, errno, _("error reading %s"), quote (pretty_filename));
     600          11 :       ok = false;
     601          11 :       goto free_lbuffers;
     602             :     }
     603             : 
     604             :   /* If the file is empty, then bail out.  */
     605          14 :   if (last->nbytes == 0)
     606           8 :     goto free_lbuffers;
     607             : 
     608             :   /* This prevents a core dump when the pipe contains no newlines.  */
     609           6 :   if (n_lines == 0)
     610           0 :     goto free_lbuffers;
     611             : 
     612             :   /* Count the incomplete line on files that don't end with a newline.  */
     613           6 :   if (last->buffer[last->nbytes - 1] != '\n')
     614             :     {
     615           2 :       ++last->nlines;
     616           2 :       ++total_lines;
     617             :     }
     618             : 
     619             :   /* Run through the list, printing lines.  First, skip over unneeded
     620             :      buffers.  */
     621           6 :   for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
     622           0 :     total_lines -= tmp->nlines;
     623             : 
     624             :   /* Find the correct beginning, then print the rest of the file.  */
     625             :   {
     626           6 :     char const *beg = tmp->buffer;
     627           6 :     char const *buffer_end = tmp->buffer + tmp->nbytes;
     628           6 :     if (total_lines > n_lines)
     629             :       {
     630             :         /* Skip `total_lines' - `n_lines' newlines.  We made sure that
     631             :            `total_lines' - `n_lines' <= `tmp->nlines'.  */
     632             :         size_t j;
     633           0 :         for (j = total_lines - n_lines; j; --j)
     634             :           {
     635           0 :             beg = memchr (beg, '\n', buffer_end - beg);
     636           0 :             assert (beg);
     637           0 :             ++beg;
     638             :           }
     639             :       }
     640             : 
     641           6 :     xwrite_stdout (beg, buffer_end - beg);
     642             :   }
     643             : 
     644           6 :   for (tmp = tmp->next; tmp; tmp = tmp->next)
     645           0 :     xwrite_stdout (tmp->buffer, tmp->nbytes);
     646             : 
     647           6 : free_lbuffers:
     648          75 :   while (first)
     649             :     {
     650          25 :       tmp = first->next;
     651          25 :       free (first);
     652          25 :       first = tmp;
     653             :     }
     654          25 :   return ok;
     655             : }
     656             : 
     657             : /* Print the last N_BYTES characters from the end of pipe FD.
     658             :    This is a stripped down version of pipe_lines.
     659             :    Return true if successful.  */
     660             : 
     661             : static bool
     662           3 : pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
     663             :             uintmax_t *read_pos)
     664             : {
     665             :   struct charbuffer
     666             :   {
     667             :     char buffer[BUFSIZ];
     668             :     size_t nbytes;
     669             :     struct charbuffer *next;
     670             :   };
     671             :   typedef struct charbuffer CBUFFER;
     672             :   CBUFFER *first, *last, *tmp;
     673             :   size_t i;                     /* Index into buffers.  */
     674           3 :   size_t total_bytes = 0;       /* Total characters in all buffers.  */
     675           3 :   bool ok = true;
     676             :   size_t n_read;
     677             : 
     678           3 :   first = last = xmalloc (sizeof (CBUFFER));
     679           3 :   first->nbytes = 0;
     680           3 :   first->next = NULL;
     681           3 :   tmp = xmalloc (sizeof (CBUFFER));
     682             : 
     683             :   /* Input is always read into a fresh buffer.  */
     684             :   while (1)
     685             :     {
     686           7 :       n_read = safe_read (fd, tmp->buffer, BUFSIZ);
     687           5 :       if (n_read == 0 || n_read == SAFE_READ_ERROR)
     688             :         break;
     689           2 :       *read_pos += n_read;
     690           2 :       tmp->nbytes = n_read;
     691           2 :       tmp->next = NULL;
     692             : 
     693           2 :       total_bytes += tmp->nbytes;
     694             :       /* If there is enough room in the last buffer read, just append the new
     695             :          one to it.  This is because when reading from a pipe, `nbytes' can
     696             :          often be very small.  */
     697           2 :       if (tmp->nbytes + last->nbytes < BUFSIZ)
     698             :         {
     699           2 :           memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
     700           2 :           last->nbytes += tmp->nbytes;
     701             :         }
     702             :       else
     703             :         {
     704             :           /* If there's not enough room, link the new buffer onto the end of
     705             :              the list, then either free up the oldest buffer for the next
     706             :              read if that would leave enough characters, or else malloc a new
     707             :              one.  Some compaction mechanism is possible but probably not
     708             :              worthwhile.  */
     709           0 :           last = last->next = tmp;
     710           0 :           if (total_bytes - first->nbytes > n_bytes)
     711             :             {
     712           0 :               tmp = first;
     713           0 :               total_bytes -= first->nbytes;
     714           0 :               first = first->next;
     715             :             }
     716             :           else
     717             :             {
     718           0 :               tmp = xmalloc (sizeof (CBUFFER));
     719             :             }
     720             :         }
     721             :     }
     722             : 
     723           3 :   free (tmp);
     724             : 
     725           3 :   if (n_read == SAFE_READ_ERROR)
     726             :     {
     727           2 :       error (0, errno, _("error reading %s"), quote (pretty_filename));
     728           2 :       ok = false;
     729           2 :       goto free_cbuffers;
     730             :     }
     731             : 
     732             :   /* Run through the list, printing characters.  First, skip over unneeded
     733             :      buffers.  */
     734           1 :   for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
     735           0 :     total_bytes -= tmp->nbytes;
     736             : 
     737             :   /* Find the correct beginning, then print the rest of the file.
     738             :      We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'.  */
     739           1 :   if (total_bytes > n_bytes)
     740           1 :     i = total_bytes - n_bytes;
     741             :   else
     742           0 :     i = 0;
     743           1 :   xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
     744             : 
     745           1 :   for (tmp = tmp->next; tmp; tmp = tmp->next)
     746           0 :     xwrite_stdout (tmp->buffer, tmp->nbytes);
     747             : 
     748           1 : free_cbuffers:
     749           9 :   while (first)
     750             :     {
     751           3 :       tmp = first->next;
     752           3 :       free (first);
     753           3 :       first = tmp;
     754             :     }
     755           3 :   return ok;
     756             : }
     757             : 
     758             : /* Skip N_BYTES characters from the start of pipe FD, and print
     759             :    any extra characters that were read beyond that.
     760             :    Return 1 on error, 0 if ok, -1 if EOF.  */
     761             : 
     762             : static int
     763           4 : start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
     764             :              uintmax_t *read_pos)
     765             : {
     766             :   char buffer[BUFSIZ];
     767             : 
     768           8 :   while (0 < n_bytes)
     769             :     {
     770           1 :       size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
     771           1 :       if (bytes_read == 0)
     772           0 :         return -1;
     773           1 :       if (bytes_read == SAFE_READ_ERROR)
     774             :         {
     775           0 :           error (0, errno, _("error reading %s"), quote (pretty_filename));
     776           0 :           return 1;
     777             :         }
     778           1 :       read_pos += bytes_read;
     779           1 :       if (bytes_read <= n_bytes)
     780           0 :         n_bytes -= bytes_read;
     781             :       else
     782             :         {
     783           1 :           size_t n_remaining = bytes_read - n_bytes;
     784           1 :           if (n_remaining)
     785           1 :             xwrite_stdout (&buffer[n_bytes], n_remaining);
     786           1 :           break;
     787             :         }
     788             :     }
     789             : 
     790           4 :   return 0;
     791             : }
     792             : 
     793             : /* Skip N_LINES lines at the start of file or pipe FD, and print
     794             :    any extra characters that were read beyond that.
     795             :    Return 1 on error, 0 if ok, -1 if EOF.  */
     796             : 
     797             : static int
     798           2 : start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
     799             :              uintmax_t *read_pos)
     800             : {
     801           2 :   if (n_lines == 0)
     802           1 :     return 0;
     803             : 
     804             :   while (1)
     805           0 :     {
     806             :       char buffer[BUFSIZ];
     807           1 :       char *p = buffer;
     808           1 :       size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
     809           1 :       char *buffer_end = buffer + bytes_read;
     810           1 :       if (bytes_read == 0) /* EOF */
     811           1 :         return -1;
     812           1 :       if (bytes_read == SAFE_READ_ERROR) /* error */
     813             :         {
     814           0 :           error (0, errno, _("error reading %s"), quote (pretty_filename));
     815           0 :           return 1;
     816             :         }
     817             : 
     818           1 :       *read_pos += bytes_read;
     819             : 
     820           2 :       while ((p = memchr (p, '\n', buffer_end - p)))
     821             :         {
     822           1 :           ++p;
     823           1 :           if (--n_lines == 0)
     824             :             {
     825           1 :               if (p < buffer_end)
     826           1 :                 xwrite_stdout (p, buffer_end - p);
     827           1 :               return 0;
     828             :             }
     829             :         }
     830             :     }
     831             : }
     832             : 
     833             : /* FIXME: describe */
     834             : 
     835             : static void
     836          15 : recheck (struct File_spec *f, bool blocking)
     837             : {
     838             :   /* open/fstat the file and announce if dev/ino have changed */
     839             :   struct stat new_stats;
     840          15 :   bool ok = true;
     841          15 :   bool is_stdin = (STREQ (f->name, "-"));
     842          15 :   bool was_tailable = f->tailable;
     843          15 :   int prev_errnum = f->errnum;
     844             :   bool new_file;
     845          15 :   int fd = (is_stdin
     846             :             ? STDIN_FILENO
     847          15 :             : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
     848             : 
     849          15 :   assert (valid_file_spec (f));
     850             : 
     851             :   /* If the open fails because the file doesn't exist,
     852             :      then mark the file as not tailable.  */
     853          15 :   f->tailable = !(reopen_inaccessible_files && fd == -1);
     854             : 
     855          15 :   if (fd == -1 || fstat (fd, &new_stats) < 0)
     856             :     {
     857           5 :       ok = false;
     858           5 :       f->errnum = errno;
     859          10 :       if (!f->tailable)
     860             :         {
     861           0 :           if (was_tailable)
     862             :             {
     863             :               /* FIXME-maybe: detect the case in which the file first becomes
     864             :                  unreadable (perms), and later becomes readable again and can
     865             :                  be seen to be the same file (dev/ino).  Otherwise, tail prints
     866             :                  the entire contents of the file when it becomes readable.  */
     867           0 :               error (0, f->errnum, _("%s has become inaccessible"),
     868             :                      quote (pretty_name (f)));
     869             :             }
     870             :           else
     871             :             {
     872             :               /* say nothing... it's still not tailable */
     873             :             }
     874             :         }
     875           5 :       else if (prev_errnum != errno)
     876             :         {
     877           0 :           error (0, errno, "%s", pretty_name (f));
     878             :         }
     879             :     }
     880          10 :   else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
     881             :     {
     882           0 :       ok = false;
     883           0 :       f->errnum = -1;
     884           0 :       error (0, 0, _("%s has been replaced with an untailable file;\
     885             :  giving up on this name"),
     886             :              quote (pretty_name (f)));
     887           0 :       f->ignore = true;
     888             :     }
     889             :   else
     890             :     {
     891          10 :       f->errnum = 0;
     892             :     }
     893             : 
     894          15 :   new_file = false;
     895          15 :   if (!ok)
     896             :     {
     897           5 :       close_fd (fd, pretty_name (f));
     898           5 :       close_fd (f->fd, pretty_name (f));
     899           5 :       f->fd = -1;
     900             :     }
     901          10 :   else if (prev_errnum && prev_errnum != ENOENT)
     902             :     {
     903          10 :       new_file = true;
     904          10 :       assert (f->fd == -1);
     905          10 :       error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
     906             :     }
     907           0 :   else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
     908             :     {
     909           0 :       new_file = true;
     910           0 :       if (f->fd == -1)
     911             :         {
     912           0 :           error (0, 0,
     913             :                  _("%s has appeared;  following end of new file"),
     914             :                  quote (pretty_name (f)));
     915             :         }
     916             :       else
     917             :         {
     918             :           /* Close the old one.  */
     919           0 :           close_fd (f->fd, pretty_name (f));
     920             : 
     921             :           /* File has been replaced (e.g., via log rotation) --
     922             :              tail the new one.  */
     923           0 :           error (0, 0,
     924             :                  _("%s has been replaced;  following end of new file"),
     925             :                  quote (pretty_name (f)));
     926             :         }
     927             :     }
     928             :   else
     929             :     {
     930           0 :       if (f->fd == -1)
     931             :         {
     932             :           /* This happens when one iteration finds the file missing,
     933             :              then the preceding <dev,inode> pair is reused as the
     934             :              file is recreated.  */
     935           0 :           new_file = true;
     936             :         }
     937             :       else
     938             :         {
     939           0 :           close_fd (fd, pretty_name (f));
     940             :         }
     941             :     }
     942             : 
     943          15 :   if (new_file)
     944             :     {
     945             :       /* Start at the beginning of the file.  */
     946          10 :       record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
     947          10 :       xlseek (fd, 0, SEEK_SET, pretty_name (f));
     948             :     }
     949           5 : }
     950             : 
     951             : /* Return true if any of the N_FILES files in F are live, i.e., have
     952             :    open file descriptors.  */
     953             : 
     954             : static bool
     955           5 : any_live_files (const struct File_spec *f, int n_files)
     956             : {
     957             :   int i;
     958             : 
     959          11 :   for (i = 0; i < n_files; i++)
     960           6 :     if (0 <= f[i].fd)
     961           0 :       return true;
     962           5 :   return false;
     963             : }
     964             : 
     965             : /* Tail NFILES files forever, or until killed.
     966             :    The pertinent information for each file is stored in an entry of F.
     967             :    Loop over each of them, doing an fstat to see if they have changed size,
     968             :    and an occasional open/fstat to see if any dev/ino pair has changed.
     969             :    If none of them have changed size in one iteration, sleep for a
     970             :    while and try again.  Continue until the user interrupts us.  */
     971             : 
     972             : static void
     973          15 : tail_forever (struct File_spec *f, int nfiles, double sleep_interval)
     974             : {
     975             :   /* Use blocking I/O as an optimization, when it's easy.  */
     976          45 :   bool blocking = (pid == 0 && follow_mode == Follow_descriptor
     977          30 :                    && nfiles == 1 && ! S_ISREG (f[0].mode));
     978             :   int last;
     979          15 :   bool writer_is_dead = false;
     980             : 
     981          15 :   last = nfiles - 1;
     982             : 
     983             :   while (1)
     984           0 :     {
     985             :       int i;
     986          15 :       bool any_input = false;
     987             : 
     988          21 :       for (i = 0; i < nfiles; i++)
     989             :         {
     990             :           int fd;
     991             :           char const *name;
     992             :           mode_t mode;
     993             :           struct stat stats;
     994             :           uintmax_t bytes_read;
     995             : 
     996          16 :           if (f[i].ignore)
     997           7 :             continue;
     998             : 
     999          15 :           if (f[i].fd < 0)
    1000             :             {
    1001          15 :               recheck (&f[i], blocking);
    1002           5 :               continue;
    1003             :             }
    1004             : 
    1005           0 :           fd = f[i].fd;
    1006           0 :           name = pretty_name (&f[i]);
    1007           0 :           mode = f[i].mode;
    1008             : 
    1009           0 :           if (f[i].blocking != blocking)
    1010             :             {
    1011           0 :               int old_flags = fcntl (fd, F_GETFL);
    1012           0 :               int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
    1013           0 :               if (old_flags < 0
    1014           0 :                   || (new_flags != old_flags
    1015           0 :                       && fcntl (fd, F_SETFL, new_flags) == -1))
    1016             :                 {
    1017             :                   /* Don't update f[i].blocking if fcntl fails.  */
    1018           0 :                   if (S_ISREG (f[i].mode) && errno == EPERM)
    1019             :                     {
    1020             :                       /* This happens when using tail -f on a file with
    1021             :                          the append-only attribute.  */
    1022             :                     }
    1023             :                   else
    1024           0 :                     error (EXIT_FAILURE, errno,
    1025             :                            _("%s: cannot change nonblocking mode"), name);
    1026             :                 }
    1027             :               else
    1028           0 :                 f[i].blocking = blocking;
    1029             :             }
    1030             : 
    1031           0 :           if (!f[i].blocking)
    1032             :             {
    1033           0 :               if (fstat (fd, &stats) != 0)
    1034             :                 {
    1035           0 :                   f[i].fd = -1;
    1036           0 :                   f[i].errnum = errno;
    1037           0 :                   error (0, errno, "%s", name);
    1038           0 :                   continue;
    1039             :                 }
    1040             : 
    1041           0 :               if (f[i].mode == stats.st_mode
    1042           0 :                   && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
    1043           0 :                   && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
    1044             :                 {
    1045           0 :                   if ((max_n_unchanged_stats_between_opens
    1046           0 :                        <= f[i].n_unchanged_stats++)
    1047           0 :                       && follow_mode == Follow_name)
    1048             :                     {
    1049           0 :                       recheck (&f[i], f[i].blocking);
    1050           0 :                       f[i].n_unchanged_stats = 0;
    1051             :                     }
    1052           0 :                   continue;
    1053             :                 }
    1054             : 
    1055             :               /* This file has changed.  Print out what we can, and
    1056             :                  then keep looping.  */
    1057             : 
    1058           0 :               f[i].mtime = get_stat_mtime (&stats);
    1059           0 :               f[i].mode = stats.st_mode;
    1060             : 
    1061             :               /* reset counter */
    1062           0 :               f[i].n_unchanged_stats = 0;
    1063             : 
    1064           0 :               if (S_ISREG (mode) && stats.st_size < f[i].size)
    1065             :                 {
    1066           0 :                   error (0, 0, _("%s: file truncated"), name);
    1067           0 :                   last = i;
    1068           0 :                   xlseek (fd, stats.st_size, SEEK_SET, name);
    1069           0 :                   f[i].size = stats.st_size;
    1070           0 :                   continue;
    1071             :                 }
    1072             : 
    1073           0 :               if (i != last)
    1074             :                 {
    1075           0 :                   if (print_headers)
    1076           0 :                     write_header (name);
    1077           0 :                   last = i;
    1078             :                 }
    1079             :             }
    1080             : 
    1081           0 :           bytes_read = dump_remainder (name, fd,
    1082           0 :                                        (f[i].blocking
    1083             :                                         ? COPY_A_BUFFER : COPY_TO_EOF));
    1084           0 :           any_input |= (bytes_read != 0);
    1085           0 :           f[i].size += bytes_read;
    1086             :         }
    1087             : 
    1088           5 :       if (! any_live_files (f, nfiles) && ! reopen_inaccessible_files)
    1089             :         {
    1090           5 :           error (0, 0, _("no files remaining"));
    1091           5 :           break;
    1092             :         }
    1093             : 
    1094           0 :       if ((!any_input | blocking) && fflush (stdout) != 0)
    1095           0 :         error (EXIT_FAILURE, errno, _("write error"));
    1096             : 
    1097             :       /* If nothing was read, sleep and/or check for dead writers.  */
    1098           0 :       if (!any_input)
    1099             :         {
    1100           0 :           if (writer_is_dead)
    1101           0 :             break;
    1102             : 
    1103           0 :           if (xnanosleep (sleep_interval))
    1104           0 :             error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
    1105             : 
    1106             :           /* Once the writer is dead, read the files once more to
    1107             :              avoid a race condition.  */
    1108           0 :           writer_is_dead = (pid != 0
    1109           0 :                             && kill (pid, 0) != 0
    1110             :                             /* Handle the case in which you cannot send a
    1111             :                                signal to the writer, so kill fails and sets
    1112             :                                errno to EPERM.  */
    1113           0 :                             && errno != EPERM);
    1114             :         }
    1115             :     }
    1116           5 : }
    1117             : 
    1118             : /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
    1119             :    Return true if successful.  */
    1120             : 
    1121             : static bool
    1122          24 : tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
    1123             :             uintmax_t *read_pos)
    1124             : {
    1125             :   struct stat stats;
    1126             : 
    1127          24 :   if (fstat (fd, &stats))
    1128             :     {
    1129           0 :       error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
    1130           0 :       return false;
    1131             :     }
    1132             : 
    1133          24 :   if (from_start)
    1134             :     {
    1135          12 :       if ( ! presume_input_pipe
    1136          12 :            && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
    1137             :         {
    1138           8 :           xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
    1139           8 :           *read_pos += n_bytes;
    1140             :         }
    1141             :       else
    1142             :         {
    1143           4 :           int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
    1144           4 :           if (t)
    1145           0 :             return t < 0;
    1146             :         }
    1147          12 :       *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
    1148             :     }
    1149             :   else
    1150             :     {
    1151          12 :       if ( ! presume_input_pipe
    1152          12 :            && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
    1153           9 :         {
    1154           9 :           off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
    1155           9 :           off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
    1156           9 :           off_t diff = end_pos - current_pos;
    1157             :           /* Be careful here.  The current position may actually be
    1158             :              beyond the end of the file.  */
    1159           9 :           off_t bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
    1160           9 :           off_t nb = n_bytes;
    1161             : 
    1162           9 :           if (bytes_remaining <= nb)
    1163             :             {
    1164             :               /* From the current position to end of file, there are no
    1165             :                  more bytes than have been requested.  So reposition the
    1166             :                  file pointer to the incoming current position and print
    1167             :                  everything after that.  */
    1168           7 :               *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
    1169             :             }
    1170             :           else
    1171             :             {
    1172             :               /* There are more bytes remaining than were requested.
    1173             :                  Back up.  */
    1174           2 :               *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
    1175             :             }
    1176           9 :           *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
    1177             :         }
    1178             :       else
    1179           3 :         return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
    1180             :     }
    1181          20 :   return true;
    1182             : }
    1183             : 
    1184             : /* Output the last N_LINES lines of file FILENAME open for reading in FD.
    1185             :    Return true if successful.  */
    1186             : 
    1187             : static bool
    1188          53 : tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
    1189             :             uintmax_t *read_pos)
    1190             : {
    1191             :   struct stat stats;
    1192             : 
    1193          53 :   if (fstat (fd, &stats))
    1194             :     {
    1195           0 :       error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
    1196           0 :       return false;
    1197             :     }
    1198             : 
    1199          53 :   if (from_start)
    1200             :     {
    1201           2 :       int t = start_lines (pretty_filename, fd, n_lines, read_pos);
    1202           2 :       if (t)
    1203           0 :         return t < 0;
    1204           2 :       *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
    1205             :     }
    1206             :   else
    1207             :     {
    1208          51 :       off_t start_pos = -1;
    1209             :       off_t end_pos;
    1210             : 
    1211             :       /* Use file_lines only if FD refers to a regular file for
    1212             :          which lseek (... SEEK_END) works.  */
    1213          51 :       if ( ! presume_input_pipe
    1214          50 :            && S_ISREG (stats.st_mode)
    1215          32 :            && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
    1216          32 :            && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
    1217             :         {
    1218          26 :           *read_pos = end_pos;
    1219          52 :           if (end_pos != 0
    1220          26 :               && ! file_lines (pretty_filename, fd, n_lines,
    1221             :                                start_pos, end_pos, read_pos))
    1222           0 :             return false;
    1223             :         }
    1224             :       else
    1225             :         {
    1226             :           /* Under very unlikely circumstances, it is possible to reach
    1227             :              this point after positioning the file pointer to end of file
    1228             :              via the `lseek (...SEEK_END)' above.  In that case, reposition
    1229             :              the file pointer back to start_pos before calling pipe_lines.  */
    1230          25 :           if (start_pos != -1)
    1231           6 :             xlseek (fd, start_pos, SEEK_SET, pretty_filename);
    1232             : 
    1233          25 :           return pipe_lines (pretty_filename, fd, n_lines, read_pos);
    1234             :         }
    1235             :     }
    1236          28 :   return true;
    1237             : }
    1238             : 
    1239             : /* Display the last N_UNITS units of file FILENAME, open for reading
    1240             :    via FD.  Set *READ_POS to the position of the input stream pointer.
    1241             :    *READ_POS is usually the number of bytes read and corresponds to an
    1242             :    offset from the beginning of a file.  However, it may be larger than
    1243             :    OFF_T_MAX (as for an input pipe), and may also be larger than the
    1244             :    number of bytes read (when an input pointer is initially not at
    1245             :    beginning of file), and may be far greater than the number of bytes
    1246             :    actually read for an input file that is seekable.
    1247             :    Return true if successful.  */
    1248             : 
    1249             : static bool
    1250          77 : tail (const char *filename, int fd, uintmax_t n_units,
    1251             :       uintmax_t *read_pos)
    1252             : {
    1253          77 :   *read_pos = 0;
    1254          77 :   if (count_lines)
    1255          53 :     return tail_lines (filename, fd, n_units, read_pos);
    1256             :   else
    1257          24 :     return tail_bytes (filename, fd, n_units, read_pos);
    1258             : }
    1259             : 
    1260             : /* Display the last N_UNITS units of the file described by F.
    1261             :    Return true if successful.  */
    1262             : 
    1263             : static bool
    1264         105 : tail_file (struct File_spec *f, uintmax_t n_units)
    1265             : {
    1266             :   int fd;
    1267             :   bool ok;
    1268             : 
    1269         105 :   bool is_stdin = (STREQ (f->name, "-"));
    1270             : 
    1271         105 :   if (is_stdin)
    1272             :     {
    1273          70 :       have_read_stdin = true;
    1274          70 :       fd = STDIN_FILENO;
    1275             :       if (O_BINARY && ! isatty (STDIN_FILENO))
    1276             :         freopen (NULL, "rb", stdin);
    1277             :     }
    1278             :   else
    1279          35 :     fd = open (f->name, O_RDONLY | O_BINARY);
    1280             : 
    1281         105 :   f->tailable = !(reopen_inaccessible_files && fd == -1);
    1282             : 
    1283         105 :   if (fd == -1)
    1284             :     {
    1285          28 :       if (forever)
    1286             :         {
    1287           5 :           f->fd = -1;
    1288           5 :           f->errnum = errno;
    1289           5 :           f->ignore = false;
    1290           5 :           f->ino = 0;
    1291           5 :           f->dev = 0;
    1292             :         }
    1293          28 :       error (0, errno, _("cannot open %s for reading"),
    1294             :              quote (pretty_name (f)));
    1295          28 :       ok = false;
    1296             :     }
    1297             :   else
    1298             :     {
    1299             :       uintmax_t read_pos;
    1300             : 
    1301          77 :       if (print_headers)
    1302          30 :         write_header (pretty_name (f));
    1303          77 :       ok = tail (pretty_name (f), fd, n_units, &read_pos);
    1304          76 :       if (forever)
    1305             :         {
    1306             :           struct stat stats;
    1307             : 
    1308             : #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
    1309             :           /* Before the tail function provided `read_pos', there was
    1310             :              a race condition described in the URL below.  This sleep
    1311             :              call made the window big enough to exercise the problem.  */
    1312             :           sleep (1);
    1313             : #endif
    1314          13 :           f->errnum = ok - 1;
    1315          13 :           if (fstat (fd, &stats) < 0)
    1316             :             {
    1317           0 :               ok = false;
    1318           0 :               f->errnum = errno;
    1319           0 :               error (0, errno, _("error reading %s"), quote (pretty_name (f)));
    1320             :             }
    1321          13 :           else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
    1322             :             {
    1323           1 :               error (0, 0, _("%s: cannot follow end of this type of file;\
    1324             :  giving up on this name"),
    1325             :                      pretty_name (f));
    1326           1 :               ok = false;
    1327           1 :               f->errnum = -1;
    1328           1 :               f->ignore = true;
    1329             :             }
    1330             : 
    1331          13 :           if (!ok)
    1332             :             {
    1333          11 :               close_fd (fd, pretty_name (f));
    1334          11 :               f->fd = -1;
    1335             :             }
    1336             :           else
    1337             :             {
    1338             :               /* Note: we must use read_pos here, not stats.st_size,
    1339             :                  to avoid a race condition described by Ken Raeburn:
    1340             :         http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
    1341           2 :               record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
    1342             :             }
    1343             :         }
    1344             :       else
    1345             :         {
    1346          63 :           if (!is_stdin && close (fd))
    1347             :             {
    1348           0 :               error (0, errno, _("error reading %s"), quote (pretty_name (f)));
    1349           0 :               ok = false;
    1350             :             }
    1351             :         }
    1352             :     }
    1353             : 
    1354         104 :   return ok;
    1355             : }
    1356             : 
    1357             : /* If obsolete usage is allowed, and the command line arguments are of
    1358             :    the obsolete form and the option string is well-formed, set
    1359             :    *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
    1360             :    return true.  If the command line arguments are obviously incorrect
    1361             :    (e.g., because obsolete usage is not allowed and the arguments are
    1362             :    incorrect for non-obsolete usage), report an error and exit.
    1363             :    Otherwise, return false and don't modify any parameter or global
    1364             :    variable.  */
    1365             : 
    1366             : static bool
    1367         125 : parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
    1368             : {
    1369             :   const char *p;
    1370             :   const char *n_string;
    1371             :   const char *n_string_end;
    1372             :   bool obsolete_usage;
    1373         125 :   int default_count = DEFAULT_N_LINES;
    1374             :   bool t_from_start;
    1375         125 :   bool t_count_lines = true;
    1376         125 :   bool t_forever = false;
    1377             : 
    1378             :   /* With the obsolete form, there is one option string and at most
    1379             :      one file argument.  Watch out for "-" and "--", though.  */
    1380         215 :   if (! (argc == 2
    1381         102 :          || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
    1382          85 :          || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
    1383          59 :     return false;
    1384             : 
    1385          66 :   obsolete_usage = (posix2_version () < 200112);
    1386          66 :   p = argv[1];
    1387             : 
    1388          66 :   switch (*p++)
    1389             :     {
    1390           3 :     default:
    1391           3 :       return false;
    1392             : 
    1393          12 :     case '+':
    1394             :       /* Leading "+" is a file name in the non-obsolete form.  */
    1395          12 :       if (!obsolete_usage)
    1396          12 :         return false;
    1397             : 
    1398           0 :       t_from_start = true;
    1399           0 :       break;
    1400             : 
    1401          51 :     case '-':
    1402             :       /* In the non-obsolete form, "-" is standard input and "-c"
    1403             :          requires an option-argument.  The obsolete multidigit options
    1404             :          are supported as a GNU extension even when conforming to
    1405             :          POSIX 1003.1-2001, so don't complain about them.  */
    1406          51 :       if (!obsolete_usage && !p[p[0] == 'c'])
    1407           9 :         return false;
    1408             : 
    1409          42 :       t_from_start = false;
    1410          42 :       break;
    1411             :     }
    1412             : 
    1413          42 :   n_string = p;
    1414         114 :   while (ISDIGIT (*p))
    1415          30 :     p++;
    1416          42 :   n_string_end = p;
    1417             : 
    1418          42 :   switch (*p)
    1419             :     {
    1420           3 :     case 'b': default_count *= 512;     /* Fall through.  */
    1421          16 :     case 'c': t_count_lines = false;    /* Fall through.  */
    1422          27 :     case 'l': p++; break;
    1423             :     }
    1424             : 
    1425          42 :   if (*p == 'f')
    1426             :     {
    1427           9 :       t_forever = true;
    1428           9 :       ++p;
    1429             :     }
    1430             : 
    1431          42 :   if (*p)
    1432          22 :     return false;
    1433             : 
    1434          20 :   if (n_string == n_string_end)
    1435           8 :     *n_units = default_count;
    1436          24 :   else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
    1437          12 :             & ~LONGINT_INVALID_SUFFIX_CHAR)
    1438             :            != LONGINT_OK)
    1439           0 :     error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1]));
    1440             : 
    1441             :   /* Set globals.  */
    1442          20 :   from_start = t_from_start;
    1443          20 :   count_lines = t_count_lines;
    1444          20 :   forever = t_forever;
    1445             : 
    1446          20 :   return true;
    1447             : }
    1448             : 
    1449             : static void
    1450         125 : parse_options (int argc, char **argv,
    1451             :                uintmax_t *n_units, enum header_mode *header_mode,
    1452             :                double *sleep_interval)
    1453             : {
    1454             :   int c;
    1455             : 
    1456         286 :   while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789",
    1457             :                            long_options, NULL))
    1458             :          != -1)
    1459             :     {
    1460          80 :       switch (c)
    1461             :         {
    1462           3 :         case 'F':
    1463           3 :           forever = true;
    1464           3 :           follow_mode = Follow_name;
    1465           3 :           reopen_inaccessible_files = true;
    1466           3 :           break;
    1467             : 
    1468          38 :         case 'c':
    1469             :         case 'n':
    1470          38 :           count_lines = (c == 'n');
    1471          38 :           if (*optarg == '+')
    1472          23 :             from_start = true;
    1473          15 :           else if (*optarg == '-')
    1474          12 :             ++optarg;
    1475             : 
    1476             :           {
    1477             :             strtol_error s_err;
    1478          38 :             s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0");
    1479          38 :             if (s_err != LONGINT_OK)
    1480             :               {
    1481          18 :                 error (EXIT_FAILURE, 0, "%s: %s", optarg,
    1482             :                        (c == 'n'
    1483             :                         ? _("invalid number of lines")
    1484             :                         : _("invalid number of bytes")));
    1485             :               }
    1486             :           }
    1487          20 :           break;
    1488             : 
    1489          19 :         case 'f':
    1490             :         case LONG_FOLLOW_OPTION:
    1491          19 :           forever = true;
    1492          19 :           if (optarg == NULL)
    1493           5 :             follow_mode = DEFAULT_FOLLOW_MODE;
    1494             :           else
    1495          14 :             follow_mode = XARGMATCH ("--follow", optarg,
    1496             :                                      follow_mode_string, follow_mode_map);
    1497           6 :           break;
    1498             : 
    1499           0 :         case RETRY_OPTION:
    1500           0 :           reopen_inaccessible_files = true;
    1501           0 :           break;
    1502             : 
    1503           2 :         case MAX_UNCHANGED_STATS_OPTION:
    1504             :           /* --max-unchanged-stats=N */
    1505           2 :           if (xstrtoumax (optarg, NULL, 10,
    1506             :                           &max_n_unchanged_stats_between_opens,
    1507             :                           "")
    1508             :               != LONGINT_OK)
    1509             :             {
    1510           1 :               error (EXIT_FAILURE, 0,
    1511             :                _("%s: invalid maximum number of unchanged stats between opens"),
    1512             :                      optarg);
    1513             :             }
    1514           1 :           break;
    1515             : 
    1516           7 :         case PID_OPTION:
    1517             :           {
    1518             :             strtol_error s_err;
    1519             :             unsigned long int tmp_ulong;
    1520           7 :             s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
    1521           7 :             if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
    1522             :               {
    1523           4 :                 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
    1524             :               }
    1525           3 :             pid = tmp_ulong;
    1526             :           }
    1527           3 :           break;
    1528             : 
    1529           1 :         case PRESUME_INPUT_PIPE_OPTION:
    1530           1 :           presume_input_pipe = true;
    1531           1 :           break;
    1532             : 
    1533           1 :         case 'q':
    1534           1 :           *header_mode = never;
    1535           1 :           break;
    1536             : 
    1537           1 :         case 's':
    1538             :           {
    1539             :             double s;
    1540           1 :             if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
    1541           1 :               error (EXIT_FAILURE, 0,
    1542             :                      _("%s: invalid number of seconds"), optarg);
    1543           0 :             *sleep_interval = s;
    1544             :           }
    1545           0 :           break;
    1546             : 
    1547           1 :         case 'v':
    1548           1 :           *header_mode = always;
    1549           1 :           break;
    1550             : 
    1551           0 :         case_GETOPT_HELP_CHAR;
    1552             : 
    1553           0 :         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
    1554             : 
    1555           2 :         case '0': case '1': case '2': case '3': case '4':
    1556             :         case '5': case '6': case '7': case '8': case '9':
    1557           2 :           error (EXIT_FAILURE, 0,
    1558             :                  _("option used in invalid context -- %c"), c);
    1559             : 
    1560           5 :         default:
    1561           5 :           usage (EXIT_FAILURE);
    1562             :         }
    1563             :     }
    1564             : 
    1565          81 :   if (reopen_inaccessible_files && follow_mode != Follow_name)
    1566           1 :     error (0, 0, _("warning: --retry is useful mainly when following by name"));
    1567             : 
    1568          81 :   if (pid && !forever)
    1569           2 :     error (0, 0,
    1570             :            _("warning: PID ignored; --pid=PID is useful only when following"));
    1571          79 :   else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
    1572             :     {
    1573           0 :       error (0, 0, _("warning: --pid=PID is not supported on this system"));
    1574           0 :       pid = 0;
    1575             :     }
    1576          81 : }
    1577             : 
    1578             : int
    1579         125 : main (int argc, char **argv)
    1580             : {
    1581         125 :   enum header_mode header_mode = multiple_files;
    1582         125 :   bool ok = true;
    1583             :   /* If from_start, the number of items to skip before printing; otherwise,
    1584             :      the number of items at the end of the file to print.  Although the type
    1585             :      is signed, the value is never negative.  */
    1586         125 :   uintmax_t n_units = DEFAULT_N_LINES;
    1587             :   int n_files;
    1588             :   char **file;
    1589             :   struct File_spec *F;
    1590             :   int i;
    1591             :   bool obsolete_option;
    1592             : 
    1593             :   /* The number of seconds to sleep between iterations.
    1594             :      During one iteration, every file name or descriptor is checked to
    1595             :      see if it has changed.  */
    1596         125 :   double sleep_interval = 1.0;
    1597             : 
    1598             :   initialize_main (&argc, &argv);
    1599         125 :   program_name = argv[0];
    1600         125 :   setlocale (LC_ALL, "");
    1601             :   bindtextdomain (PACKAGE, LOCALEDIR);
    1602             :   textdomain (PACKAGE);
    1603             : 
    1604         125 :   atexit (close_stdout);
    1605             : 
    1606         125 :   have_read_stdin = false;
    1607             : 
    1608         125 :   count_lines = true;
    1609         125 :   forever = from_start = print_headers = false;
    1610         125 :   obsolete_option = parse_obsolete_option (argc, argv, &n_units);
    1611         125 :   argc -= obsolete_option;
    1612         125 :   argv += obsolete_option;
    1613         125 :   parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
    1614             : 
    1615             :   /* To start printing with item N_UNITS from the start of the file, skip
    1616             :      N_UNITS - 1 items.  `tail -n +0' is actually meaningless, but for Unix
    1617             :      compatibility it's treated the same as `tail -n +1'.  */
    1618          81 :   if (from_start)
    1619             :     {
    1620          14 :       if (n_units)
    1621          13 :         --n_units;
    1622             :     }
    1623             : 
    1624          81 :   if (optind < argc)
    1625             :     {
    1626          62 :       n_files = argc - optind;
    1627          62 :       file = argv + optind;
    1628             :     }
    1629             :   else
    1630             :     {
    1631             :       static char *dummy_stdin = "-";
    1632          19 :       n_files = 1;
    1633          19 :       file = &dummy_stdin;
    1634             : 
    1635             :       /* POSIX says that -f is ignored if no file operand is specified
    1636             :          and standard input is a pipe.  However, the GNU coding
    1637             :          standards say that program behavior should not depend on
    1638             :          device type, because device independence is an important
    1639             :          principle of the system's design.
    1640             : 
    1641             :          Follow the POSIX requirement only if POSIXLY_CORRECT is set.  */
    1642             : 
    1643          19 :       if (forever && getenv ("POSIXLY_CORRECT"))
    1644             :         {
    1645             :           struct stat st;
    1646           0 :           int is_a_fifo_or_pipe =
    1647           0 :             (fstat (STDIN_FILENO, &st) != 0 ? -1
    1648           0 :              : S_ISFIFO (st.st_mode) ? 1
    1649           0 :              : HAVE_FIFO_PIPES == 1 ? 0
    1650             :              : isapipe (STDIN_FILENO));
    1651           0 :           if (is_a_fifo_or_pipe < 0)
    1652           0 :             error (EXIT_FAILURE, errno, _("standard input"));
    1653           0 :           if (is_a_fifo_or_pipe)
    1654           0 :             forever = false;
    1655             :         }
    1656             :     }
    1657             : 
    1658             :   {
    1659          81 :     bool found_hyphen = false;
    1660             : 
    1661         189 :     for (i = 0; i < n_files; i++)
    1662         108 :       if (STREQ (file[i], "-"))
    1663          72 :         found_hyphen = true;
    1664             : 
    1665             :     /* When following by name, there must be a name.  */
    1666          81 :     if (found_hyphen && follow_mode == Follow_name)
    1667           2 :       error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
    1668             : 
    1669             :     /* When following forever, warn if any file is `-'.
    1670             :        This is only a warning, since tail's output (before a failing seek,
    1671             :        and that from any non-stdin files) might still be useful.  */
    1672          79 :     if (forever && found_hyphen && isatty (STDIN_FILENO))
    1673          10 :       error (0, 0, _("warning: following standard input"
    1674             :                      " indefinitely is ineffective"));
    1675             :   }
    1676             : 
    1677          79 :   F = xnmalloc (n_files, sizeof *F);
    1678         184 :   for (i = 0; i < n_files; i++)
    1679         105 :     F[i].name = file[i];
    1680             : 
    1681          79 :   if (header_mode == always
    1682          78 :       || (header_mode == multiple_files && n_files > 1))
    1683          23 :     print_headers = true;
    1684             : 
    1685             :   if (O_BINARY && ! isatty (STDOUT_FILENO))
    1686             :     freopen (NULL, "wb", stdout);
    1687             : 
    1688         183 :   for (i = 0; i < n_files; i++)
    1689         105 :     ok &= tail_file (&F[i], n_units);
    1690             : 
    1691          78 :   if (forever)
    1692          15 :     tail_forever (F, n_files, sleep_interval);
    1693             : 
    1694          68 :   if (have_read_stdin && close (STDIN_FILENO) < 0)
    1695           0 :     error (EXIT_FAILURE, errno, "-");
    1696          68 :   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
    1697             : }

Generated by: LCOV version 1.10