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