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