This repository has been archived by the owner on Apr 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
filelogger.c
1822 lines (1565 loc) · 52.4 KB
/
filelogger.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* filelogger v1.0
*
* Copyright 2014 Yahoo! Inc.
* This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (GPL), version 2 or later. This library is distributed WITHOUT ANY WARRANTY, whether express or implied. See the GNU GPL for more details (http://www.gnu.org/licenses/gpl.html)
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the disclaimer that appears below.
* - Redistributions of source code must also retain the original copyright notices
* from tail.c and logger.c as given below.
* - Redistributions in binary form must reproduce the above copyright notice,
* along with the original copyright notices from tail.c and logger.c, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
* - You may not use the name of Yahoo Inc. to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
*
* COPYRIGHT NOTICE FROM TAIL.C:
* Copyright (C) 1989-1991, 1995-2006, 2008-2011 Free Software Foundation, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* COPYRIGHT NOTICE FROM LOGGER.C:
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*To do:
* get rid of the compile warnings
* depending on how a file is truncated or rotated, it does not capture the text
* or at least the first line that was written as part of the
* truncation, eg echo test > file. it also does not detect
* every truncation
*
/* This combines logger.c from util-linux-2.20.1
* and tail.c from core-utils-8.9
* into a program that continuously tails one or
* more files and logs each line to local or
* remote syslog.
*
* This effort performed by Michael Martinez [email protected]
*/
/* tail: all original command-line options removed
* except q, v, and s. tail -F is assumed.
* stdin is not allowed. must specify a file
* by name.
*/
/* logger: an additional command line option
* --add which allows additional text to be
* inserted at the beginning of the line before
* sent to the syslog server.
* The previous hardcoded 400 character limit
* for the log message has been increased to 8096.
*/
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <getopt.h>
#include "c.h"
#include "nls.h"
#include "strutils.h"
#define SYSLOG_NAMES
#include <syslog.h>
/* from tail.c */
#include "xstrtol.h"
#include "xstrtod.h"
#include "c-strtod.h"
#include "binary-io.h"
#include "isapipe.h"
#include "quotearg.h"
#include "quote.h"
#include <stddef.h>
#include "stat-time.h"
#include "safe-read.h"
#include <assert.h>
#include "xnanosleep.h"
#include "time.h"
#if HAVE_INOTIFY
# include "hash.h"
# include <sys/inotify.h>
/* `select' is used by tail_forever_inotify. */
# include <sys/select.h>
/* inotify needs to know if a file is local. */
# include "fs.h"
# if HAVE_SYS_STATFS_H
# include <sys/statfs.h>
# elif HAVE_SYS_VFS_H
# include <sys/vfs.h>
# endif
#endif
/* The official name of this program (e.g., no `g' prefix). */
#define PROGRAM_NAME "filelogger"
#define AUTHORS \
proper_name ("Paul Rubin"), \
proper_name ("David MacKenzie"), \
proper_name ("Ian Lance Taylor"), \
proper_name ("Jim Meyering"), \
proper_name ("Michael Martinez")
/* Number of items to tail. */
#define DEFAULT_N_LINES 0
#define STREQ(s1, s2) (strcmp (s1, s2) == 0)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
#define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
#define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
#define ATTRIBUTE_NORETURN __attribute__ ((__noreturn__))
# define xalloc_oversized(n, s) \
((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
/* True if the arithmetic type T is signed. */
# define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
# if __GNUC__ >= 2
# define signed_type_or_expr__(t) TYPE_SIGNED (__typeof__ (t))
# else
# define signed_type_or_expr__(t) 1
# endif
/* Bound on length of the string representing an unsigned integer
* value representable in B bits. log10 (2.0) < 146/485. The
* smallest value of B where this bound is not tight is 2621. */
# define INT_BITS_STRLEN_BOUND(b) (((b) * 146 + 484) / 485)
/* Bound on length of the string representing an integer type or expression T.
* Subtract 1 for the sign bit if T is signed, and then add 1 more for
* a minus sign if needed. */
# define INT_STRLEN_BOUND(t) \
(INT_BITS_STRLEN_BOUND (sizeof (t) * CHAR_BIT - signed_type_or_expr__ (t)) \
+ signed_type_or_expr__ (t))
/* Bound on buffer size needed to represent an integer type or expression T,
* including the terminating null. */
# define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND (t) + 1)
extern void xalloc_die (void) ATTRIBUTE_NORETURN;
static inline void * xnmalloc (size_t n, size_t s)
{
if (xalloc_oversized (n, s))
xalloc_die ();
return xmalloc (n * s);
}
static inline int
timespec_cmp (struct timespec a, struct timespec b)
{
return (a.tv_sec < b.tv_sec ? -1
: a.tv_sec > b.tv_sec ? 1
: (int) (a.tv_nsec - b.tv_nsec));
}
/* Special values for dump_remainder's N_BYTES parameter. */
#define COPY_TO_EOF UINTMAX_MAX
#define COPY_A_BUFFER (UINTMAX_MAX - 1)
/* FIXME: make Follow_name the default? */
#define DEFAULT_FOLLOW_MODE Follow_descriptor
enum Follow_mode
{
/* Follow the name of each file: if the file is renamed, try to reopen
that name and track the end of the new file if/when it's recreated.
This is useful for tracking logs that are occasionally rotated. */
Follow_name = 1,
/* Follow each descriptor obtained upon opening a file.
That means we'll continue to follow the end of a file even after
it has been renamed or unlinked. */
Follow_descriptor = 2
};
/* The types of files for which tail works. */
#define IS_TAILABLE_FILE_TYPE(Mode) \
(S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
static char const *const follow_mode_string[] =
{
"descriptor", "name", NULL
};
static enum Follow_mode const follow_mode_map[] =
{
Follow_descriptor, Follow_name,
};
struct File_spec
{
/* The actual file name, or "-" for stdin. */
char *name;
/* Attributes of the file the last time we checked. */
off_t size;
struct timespec mtime;
dev_t dev;
ino_t ino;
mode_t mode;
/* The specified name initially referred to a directory or some other
type for which tail isn't meaningful. Unlike for a permission problem
(tailable, below) once this is set, the name is not checked ever again. */
bool ignore;
/* See the description of fremote. */
bool remote;
/* A file is tailable if it exists, is readable, and is of type
IS_TAILABLE_FILE_TYPE. */
bool tailable;
/* File descriptor on which the file is open; -1 if it's not open. */
int fd;
/* The value of errno seen last time we checked this file. */
int errnum;
/* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
int blocking;
#if HAVE_INOTIFY
/* The watch descriptor used by inotify. */
int wd;
/* The parent directory watch descriptor. It is used only
* when Follow_name is used. */
int parent_wd;
/* Offset in NAME of the basename part. */
size_t basename_start;
#endif
/* See description of DEFAULT_MAX_N_... below. */
uintmax_t n_unchanged_stats;
};
#if HAVE_INOTIFY
/* The events mask used with inotify on files. This mask is not used on
directories. */
const uint32_t inotify_wd_mask = (IN_MODIFY | IN_ATTRIB | IN_DELETE_SELF
| IN_MOVE_SELF);
#endif
static bool reopen_inaccessible_files = true;
/* Always assume reading via lines */
static bool count_lines;
/* Whether we follow the name of each file or the file descriptor
that is initially associated with each name. */
static enum Follow_mode follow_mode = Follow_descriptor;
/* If true, read from the ends of all specified files until killed. */
static bool forever;
/* If true, print filename headers. */
static bool print_headers;
/* When to print the filename banners. */
enum header_mode
{
multiple_files, always, never
};
/* When tailing a file by name, if there have been this many consecutive
iterations for which the file has not changed, then open/fstat
parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
the file to determine if that file name is still associated with the
same device/inode-number pair as before. This option is meaningful only
when following by name. --max-unchanged-stats=N */
#define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
static uintmax_t max_n_unchanged_stats_between_opens =
DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
/* The process ID of the process (presumably on the current host)
that is writing to all followed files. */
static pid_t pid;
/* True if we have ever read standard input. */
static bool have_read_stdin;
/* If nonzero then don't use inotify even if available. */
static bool disable_inotify;
/* ** END from tail.c ** */
int decode __P((char *, CODE *));
int pencode __P((char *));
static int optd = 0;
static int udpport = 514;
static int LogSock = -1;
static int logflags = 0;
static int pri = LOG_NOTICE;
static char *tag = NULL;
static char *add = NULL;
static char *usock = NULL;
static char logthis[4096];
static int logthis_offset = 0; // where to begin writing in logthis[]
static int
myopenlog(const char *sock) {
int fd;
static struct sockaddr_un s_addr; /* AF_UNIX address of local logger */
if (strlen(sock) >= sizeof(s_addr.sun_path))
errx(EXIT_FAILURE, _("openlog %s: pathname too long"), sock);
s_addr.sun_family = AF_UNIX;
(void)strcpy(s_addr.sun_path, sock);
if ((fd = socket(AF_UNIX, optd ? SOCK_DGRAM : SOCK_STREAM, 0)) == -1)
err(EXIT_FAILURE, _("socket %s"), sock);
if (connect(fd, (struct sockaddr *) &s_addr, sizeof(s_addr)) == -1)
err(EXIT_FAILURE, _("connect %s"), sock);
return fd;
}
static int
udpopenlog(const char *servername,int port) {
int fd;
struct sockaddr_in s_addr;
struct hostent *serverhost;
if ((serverhost = gethostbyname(servername)) == NULL )
errx(EXIT_FAILURE, _("unable to resolve '%s'"), servername);
if ((fd = socket(AF_INET, SOCK_DGRAM , 0)) == -1)
err(EXIT_FAILURE, _("socket"));
bcopy(serverhost->h_addr,&s_addr.sin_addr,serverhost->h_length);
s_addr.sin_family=AF_INET;
s_addr.sin_port=htons(port);
if (connect(fd, (struct sockaddr *) &s_addr, sizeof(s_addr)) == -1)
err(EXIT_FAILURE, _("connect"));
return fd;
}
/* these used to be passed as paramters: LogSock, logflags, pri, tag, add, logthis
* but now are global variables
*/
/* write add + logthis to Logsock with logflags, pri, tag
* and then memset logthis and its counter */
static void
mysyslog() {
char buf[4096], pid[30], *cp, *pc, *tp;
time_t now;
/* to do: check and print file header if needed.
* this is probably not the appropriate function to do it in */
if (LogSock > -1) {
if (logflags & LOG_PID)
snprintf (pid, sizeof(pid), "[%d]", getpid());
else
pid[0] = 0;
if (tag)
cp = tag;
else {
cp = getlogin();
if (!cp)
cp = "<someone>";
}
(void)time(&now);
tp = ctime(&now)+4;
if (add)
pc = add;
else {
pc = "";
}
snprintf(buf, sizeof(buf), "<%d>%.15s %.200s%s: %.30s %.4096s",
pri, tp, cp, pid, pc, logthis);
if (write(LogSock, buf, strlen(buf)+1) < 0)
{
error (errno, errno, _("mysyslog(): error writing to socket. \
premature exit.\n"));
exit (errno); /* to do: terminate program or just return ? */
} else {
memset(logthis,'\0',4096);
logthis_offset = 0;
}
}
}
/* TAIL routines */
/* Call lseek with the specified arguments, where file descriptor FD
corresponds to the file, FILENAME.
Give a diagnostic and exit nonzero if lseek fails.
Otherwise, return the resulting offset. */
static off_t
xlseek (int fd, off_t offset, int whence, char const *filename)
{
off_t new_offset = lseek (fd, offset, whence);
char buf[INT_BUFSIZE_BOUND (offset)];
char *s;
if (0 <= new_offset)
return new_offset;
s = offtostr (offset, buf);
switch (whence)
{
case SEEK_SET:
error (0, errno, _("%s: cannot seek to offset %s"),
filename, s);
break;
case SEEK_CUR:
error (0, errno, _("%s: cannot seek to relative offset %s"),
filename, s);
break;
case SEEK_END:
error (0, errno, _("%s: cannot seek to end-relative offset %s"),
filename, s);
break;
default:
abort ();
}
exit (EXIT_FAILURE);
}
/* Record a file F with descriptor FD, size SIZE, status ST, and
blocking status BLOCKING. */
static void
record_open_fd (struct File_spec *f, int fd,
off_t size, struct stat const *st,
int blocking)
{
f->fd = fd;
f->size = size;
f->mtime = get_stat_mtime (st);
f->dev = st->st_dev;
f->ino = st->st_ino;
f->mode = st->st_mode;
f->blocking = blocking;
f->n_unchanged_stats = 0;
f->ignore = false;
}
/* Close the file with descriptor FD and name FILENAME. */
static void
close_fd (int fd, const char *filename)
{
if (fd != -1 && fd != STDIN_FILENO && close (fd))
{
error (0, errno, _("closing %s (fd=%d)"), filename, fd);
}
}
static bool
valid_file_spec (struct File_spec const *f)
{
/* Exactly one of the following subexpressions must be true. */
return ((f->fd == -1) ^ (f->errnum == 0));
}
static char const *
pretty_name (struct File_spec const *f)
{
return ( (strcmp (f->name, "-") == 0) ? _("standard input") : f->name);
// return (STREQ (f->name, "-") ? _("standard input") : f->name);
}
static void
xwrite_logger (char const *buffer, size_t n_bytes)
{
int i;
for (i = 1; i <= n_bytes; i++)
{
if (logthis_offset < 4096) {
logthis[logthis_offset] = *buffer++;
logthis_offset++;
}
if (logthis[logthis_offset - 1] == '\0')
{
logthis[logthis_offset - 1] = '\n';
}
if (logthis[logthis_offset - 1] == '\n' || logthis_offset >= 4096) {
if (!usock) {
syslog(pri, "%s", logthis);
} else {
mysyslog();
}
}
} //end for
}
#if HAVE_INOTIFY
/* Without inotify support, always return false. Otherwise, return false
when FD is open on a file known to reside on a local file system.
If fstatfs fails, give a diagnostic and return true.
If fstatfs cannot be called, return true. */
static bool
fremote (int fd, const char *name)
{
bool remote = true; /* be conservative (poll by default). */
# if HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE && defined __linux__
struct statfs buf;
int err = fstatfs (fd, &buf);
if (err != 0)
{
error (0, errno, _("cannot determine location of %s. "
"reverting to polling"), quote (name));
}
else
{
switch (buf.f_type)
{
case S_MAGIC_AFS:
case S_MAGIC_CIFS:
case S_MAGIC_CODA:
case S_MAGIC_FUSEBLK:
case S_MAGIC_FUSECTL:
case S_MAGIC_GFS:
case S_MAGIC_KAFS:
case S_MAGIC_LUSTRE:
case S_MAGIC_NCP:
case S_MAGIC_NFS:
case S_MAGIC_NFSD:
case S_MAGIC_OCFS2:
case S_MAGIC_SMB:
break;
default:
remote = false;
}
}
# endif
return remote;
}
#else
/* Without inotify support, whether a file is remote is irrelevant.
Always return "false" in that case. */
# define fremote(fd, name) false
#endif
/* Print the last N_LINES lines from the end of file FD.
Go backward through the file, reading `BUFSIZ' bytes at a time (except
probably the first), until we hit the start of the file or have
read NUMBER newlines.
START_POS is the starting position of the read pointer for the file
associated with FD (may be nonzero).
END_POS is the file offset of EOF (one larger than offset of last byte).
Return true if successful. */
static bool
file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
off_t start_pos, off_t end_pos, uintmax_t *read_pos)
{
char buffer[BUFSIZ];
size_t bytes_read;
off_t pos = end_pos;
/* for purpose of this program n_lines is always 0 */
return true;
}
/* Write the last N_LINES lines of file FILENAME open for reading in FD.
Return true if successful. */
static bool
tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
uintmax_t *read_pos)
{
struct stat stats;
if (fstat (fd, &stats))
{
error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
return false;
}
off_t start_pos = -1;
off_t end_pos;
/* Use file_lines only if FD refers to a regular file for
* which lseek (... SEEK_END) works. */
if ( S_ISREG (stats.st_mode)
&& (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
&& start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
{
*read_pos = end_pos;
if (end_pos != 0
&& ! file_lines (pretty_filename, fd, n_lines,
start_pos, end_pos, read_pos))
return false;
}
else
{
error (errno, errno, _("tail_lines(): unable to lseek. potential pipe\n"));
exit (errno); /* to do: terminate program or just return ? */
}
return true;
}
static bool
tail (const char *filename, int fd, uintmax_t n_units,
uintmax_t *read_pos)
{
*read_pos = 0;
return tail_lines (filename, fd, n_units, read_pos);
}
/* Write the last N_UNITS units of the file described by F.
Return true if successful. */
static bool
tail_file (struct File_spec *f, uintmax_t n_units)
{
int fd;
bool ok;
/* Exit if file is stdin */
bool is_stdin = (STREQ (f->name, "-"));
if (is_stdin) {
error (EXIT_FAILURE, errno, _("Please specify a real file, not stdin."));
exit(EXIT_FAILURE);
}
fd = open (f->name, O_RDONLY | O_BINARY);
f->tailable = !(reopen_inaccessible_files && fd == -1);
if (fd == -1)
{
if (forever)
{
f->fd = -1;
f->errnum = errno;
f->ignore = false;
f->ino = 0;
f->dev = 0;
}
error (0, errno, _("cannot open %s for reading"),
quote (pretty_name (f)));
ok = false;
}
else
{
uintmax_t read_pos;
ok = tail (pretty_name (f), fd, n_units, &read_pos);
if (forever)
{
struct stat stats;
#if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
xnanosleep (1);
#endif
f->errnum = ok - 1;
if (fstat (fd, &stats) < 0)
{
ok = false;
f->errnum = errno;
error (0, errno, _("error reading %s"), quote (pretty_name (f)));
}
else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
{
error (0, 0, _("%s: cannot follow end of this type of file;\
giving up on this name"),
pretty_name (f));
ok = false;
f->errnum = -1;
f->ignore = true;
}
if (!ok)
{
close_fd (fd, pretty_name (f));
f->fd = -1;
}
else
{
record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
f->remote = fremote (fd, pretty_name (f));
}
}
else
{
if (!is_stdin && close (fd))
{
error (0, errno, _("error reading %s"), quote (pretty_name (f)));
ok = false;
}
}
}
return ok;
}
/* Mark as '.ignore'd each member of F that corresponds to a
pipe or fifo, and return the number of non-ignored members. */
static size_t
ignore_fifo_and_pipe (struct File_spec *f, size_t n_files)
{
/* When there is no FILE operand and stdin is a pipe or FIFO
POSIX requires that tail ignore the -f option.
Since we allow multiple FILE operands, we extend that to say: with -f,
ignore any "-" operand that corresponds to a pipe or FIFO. */
size_t n_viable = 0;
size_t i;
for (i = 0; i < n_files; i++)
{
bool is_a_fifo_or_pipe =
(STREQ (f[i].name, "-")
&& !f[i].ignore
&& 0 <= f[i].fd
&& (S_ISFIFO (f[i].mode)
|| (HAVE_FIFO_PIPES != 1 && isapipe (f[i].fd))));
if (is_a_fifo_or_pipe)
f[i].ignore = true;
else
++n_viable;
}
return n_viable;
}
static void
recheck (struct File_spec *f, bool blocking)
{
/* open/fstat the file and announce if dev/ino have changed */
struct stat new_stats;
bool ok = true;
bool is_stdin = (STREQ (f->name, "-"));
bool was_tailable = f->tailable;
int prev_errnum = f->errnum;
bool new_file;
int fd = (is_stdin
? STDIN_FILENO
: open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
assert (valid_file_spec (f));
/* If the open fails because the file doesn't exist,
then mark the file as not tailable. */
f->tailable = !(reopen_inaccessible_files && fd == -1);
if (fd == -1 || fstat (fd, &new_stats) < 0)
{
ok = false;
f->errnum = errno;
if (!f->tailable)
{
if (was_tailable)
{
/* FIXME-maybe: detect the case in which the file first becomes
unreadable (perms), and later becomes readable again and can
be seen to be the same file (dev/ino). Otherwise, tail prints
the entire contents of the file when it becomes readable. */
error (0, f->errnum, _("%s has become inaccessible"),
quote (pretty_name (f)));
}
else
{
/* say nothing... it's still not tailable */
}
}
else if (prev_errnum != errno)
{
error (0, errno, "%s", pretty_name (f));
}
}
else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
{
ok = false;
f->errnum = -1;
error (0, 0, _("%s has been replaced with an untailable file;\
giving up on this name"),
quote (pretty_name (f)));
f->ignore = true;
}
else if (!disable_inotify && fremote (fd, pretty_name (f)))
{
ok = false;
f->errnum = -1;
error (0, 0, _("%s has been replaced with a remote file. "
"giving up on this name"), quote (pretty_name (f)));
f->ignore = true;
f->remote = true;
}
else
{
f->errnum = 0;
}
new_file = false;
if (!ok)
{
close_fd (fd, pretty_name (f));
close_fd (f->fd, pretty_name (f));
f->fd = -1;
}
else if (prev_errnum && prev_errnum != ENOENT)
{
new_file = true;
assert (f->fd == -1);
error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
}
else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
{
new_file = true;
if (f->fd == -1)
{
error (0, 0,
_("%s has appeared; following end of new file"),
quote (pretty_name (f)));
}
else
{
/* Close the old one. */
close_fd (f->fd, pretty_name (f));
/* File has been replaced (e.g., via log rotation) --
tail the new one. */
error (0, 0,
_("%s has been replaced; following end of new file"),
quote (pretty_name (f)));
}
}
else
{
if (f->fd == -1)
{
/* This happens when one iteration finds the file missing,
then the preceding <dev,inode> pair is reused as the
file is recreated. */
new_file = true;
}
else
{
close_fd (fd, pretty_name (f));
}
}
if (new_file)
{
/* Start at the beginning of the file. */
record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
xlseek (fd, 0, SEEK_SET, pretty_name (f));
}
}
/* Return true if any of the N_FILES files in F are live, i.e., have
open file descriptors. */
static bool
any_live_files (const struct File_spec *f, size_t n_files)
{
size_t i;
for (i = 0; i < n_files; i++)
if (0 <= f[i].fd)
return true;
return false;
}
/* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
Return the number of bytes read from the file. */
static uintmax_t
dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
{
uintmax_t n_written;
uintmax_t n_remaining = n_bytes;
n_written = 0;
while (1)
{
char buffer[BUFSIZ];
size_t n = MIN (n_remaining, BUFSIZ);
size_t bytes_read = safe_read (fd, buffer, n);
if (bytes_read == SAFE_READ_ERROR)
{
if (errno != EAGAIN)
error (EXIT_FAILURE, errno, _("error reading %s"),
quote (pretty_filename));
break;
}
if (bytes_read == 0)
break;
xwrite_logger (buffer, bytes_read);
n_written += bytes_read;
if (n_bytes != COPY_TO_EOF)
{
n_remaining -= bytes_read;
if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
break;
}
}
return n_written;
}
/* Tail N_FILES files forever, or until killed.
The pertinent information for each file is stored in an entry of F.
Loop over each of them, doing an fstat to see if they have changed size,
and an occasional open/fstat to see if any dev/ino pair has changed.
If none of them have changed size in one iteration, sleep for a
while and try again. Continue until the user interrupts us. */