ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/root-tail/root-tail.c
Revision: 1.3
Committed: Sun May 5 19:10:39 2002 UTC (24 years, 5 months ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.2: +5 -2 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 pcg 1.1 /*
2     * Copyright 2001 by Marco d'Itri <md@linux.it>
3     *
4     * Original version by Mike Baker, then maintained by pcg@goof.com.
5     *
6     * This program is free software; you can redistribute it and/or modify
7     * it under the terms of the GNU General Public License as published by
8     * the Free Software Foundation; either version 2 of the License, or
9     * (at your option) any later version.
10     *
11     * This program is distributed in the hope that it will be useful,
12     * but WITHOUT ANY WARRANTY; without even the implied warranty of
13     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14     * GNU General Public License for more details.
15     *
16     * You should have received a copy of the GNU General Public License
17     * along with this program; if not, write to the Free Software
18     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
19     */
20    
21     #include "config.h"
22     #include <stdlib.h>
23     #include <stdio.h>
24     #include <unistd.h>
25     #include <string.h>
26     #include <signal.h>
27     #include <time.h>
28     #include <fcntl.h>
29     #include <errno.h>
30     #include <sys/time.h>
31     #include <sys/stat.h>
32     #include <sys/types.h>
33     #if HAS_REGEX
34     #include <regex.h>
35     #endif
36     #include <X11/Xlib.h>
37     #include <X11/Xutil.h>
38    
39     /* data structures */
40     struct logfile_entry {
41     char *fname; /* name of file */
42     char *desc; /* alternative description */
43     FILE *fp; /* FILE struct associated with file */
44     ino_t inode; /* inode of the file opened */
45     off_t last_size; /* file size at the last check */
46     unsigned long color; /* color to be used for printing */
47     struct logfile_entry *next;
48     };
49    
50     struct linematrix {
51     char *line;
52     unsigned long color;
53     };
54    
55    
56     /* global variables */
57     unsigned int width = STD_WIDTH, listlen = STD_HEIGHT;
58     int win_x = LOC_X, win_y = LOC_Y;
59     int w = -1, h = -1, font_width, font_height, font_descent;
60     int do_reopen;
61     struct timeval interval = { 2, 400000 }; /* see Knuth */
62    
63     /* command line options */
64 pcg 1.3 int opt_noinitial, opt_shade, opt_frame, opt_reverse=0, opt_nofilename,
65 pcg 1.1 geom_mask, reload = 3600;
66     const char *command = NULL,
67     *fontname = USE_FONT, *dispname = NULL, *def_color = DEF_COLOR;
68    
69     struct logfile_entry *loglist = NULL, *loglist_tail = NULL;
70    
71     Display *disp;
72     Window root;
73     GC WinGC;
74    
75     #if HAS_REGEX
76     struct re_list {
77     regex_t from;
78     const char *to;
79     struct re_list *next;
80     };
81     struct re_list *re_head, *re_tail;
82     #endif
83    
84    
85     /* prototypes */
86     void list_files(int);
87     void force_reopen(int);
88     void force_refresh(int);
89     void blank_window(int);
90    
91     void InitWindow(void);
92     unsigned long GetColor(const char *);
93     void redraw(void);
94     void refresh(struct linematrix *, int, int);
95    
96     void transform_line(char *s);
97     int lineinput(char *, int, FILE *);
98     void reopen(void);
99     void check_open_files(void);
100     FILE *openlog(struct logfile_entry *);
101     void main_loop(void);
102    
103     void display_version(void);
104     void display_help(char *);
105     void install_signal(int, void (*)(int));
106     void *xstrdup(const char *);
107     void *xmalloc(size_t);
108     int daemonize(void);
109    
110     /* signal handlers */
111     void list_files(int dummy)
112     {
113     struct logfile_entry *e;
114    
115     fprintf(stderr, "Files opened:\n");
116     for (e = loglist; e; e = e->next)
117     fprintf(stderr, "\t%s (%s)\n", e->fname, e->desc);
118     }
119    
120     void force_reopen(int dummy)
121     {
122     do_reopen = 1;
123     }
124    
125     void force_refresh(int dummy)
126     {
127     XClearWindow(disp, root);
128     redraw();
129     }
130    
131     void blank_window(int dummy)
132     {
133     XClearWindow(disp, root);
134     XFlush(disp);
135     exit(0);
136     }
137    
138     /* X related functions */
139     unsigned long GetColor(const char *ColorName)
140     {
141     XColor Color;
142     XWindowAttributes Attributes;
143    
144     XGetWindowAttributes(disp, root, &Attributes);
145     Color.pixel = 0;
146     if (!XParseColor(disp, Attributes.colormap, ColorName, &Color))
147     fprintf(stderr, "can't parse %s\n", ColorName);
148     else if (!XAllocColor(disp, Attributes.colormap, &Color))
149     fprintf(stderr, "can't allocate %s\n", ColorName);
150     return Color.pixel;
151     }
152    
153     void InitWindow(void)
154     {
155     XGCValues gcv;
156     Font font;
157     unsigned long gcm;
158     XFontStruct *info;
159     int screen, ScreenWidth, ScreenHeight;
160    
161     if (!(disp = XOpenDisplay(dispname))) {
162     fprintf(stderr, "Can't open display %s.\n", dispname);
163     exit(1);
164     }
165     screen = DefaultScreen(disp);
166     ScreenHeight = DisplayHeight(disp, screen);
167     ScreenWidth = DisplayWidth(disp, screen);
168     root = RootWindow(disp, screen);
169     gcm = GCBackground;
170     gcv.graphics_exposures = True;
171     WinGC = XCreateGC(disp, root, gcm, &gcv);
172     XMapWindow(disp, root);
173     XSetForeground(disp, WinGC, GetColor(DEF_COLOR));
174    
175     font = XLoadFont(disp, fontname);
176     XSetFont(disp, WinGC, font);
177     info = XQueryFont(disp, font);
178     font_width = info->max_bounds.width;
179     font_descent = info->max_bounds.descent;
180     font_height = info->max_bounds.ascent + font_descent;
181    
182     w = width * font_width;
183     h = listlen * font_height;
184     if (geom_mask & XNegative)
185     win_x = win_x + ScreenWidth - w;
186     if (geom_mask & YNegative)
187     win_y = win_y + ScreenHeight - h;
188    
189     XSelectInput(disp, root, ExposureMask|FocusChangeMask);
190     }
191    
192 pcg 1.2 char *
193     detabificate (char *s)
194     {
195     char * out;
196     int i, j;
197    
198     out = malloc (8 * strlen (s) + 1);
199    
200     for(i = 0, j = 0; s[i]; i++)
201     {
202     if (s[i] == '\t')
203     do
204     out[j++] = ' ';
205     while (j % 8);
206     else
207     out[j++] = s[i];
208     }
209    
210     out[j] = '\0';
211     return out;
212     }
213    
214 pcg 1.1 /*
215     * redraw does a complete redraw, rather than an update (i.e. the area
216     * gets cleared first)
217     * the rest is handled by regular refresh()'es
218     */
219     void redraw(void)
220     {
221     XClearArea(disp, root, win_x, win_y, w, h + font_descent + 2, True);
222     }
223    
224     /* Just redraw everything without clearing (i.e. after an EXPOSE event) */
225     void refresh(struct linematrix *lines, int miny, int maxy)
226     {
227     int lin;
228     int offset = (listlen + 1) * font_height;
229     unsigned long black_color = GetColor("black");
230    
231     miny -= win_y + font_height;
232     maxy -= win_y - font_height;
233    
234 pcg 1.2 for (lin = listlen; lin--;)
235     {
236     char *temp;
237    
238     offset -= font_height;
239    
240     if (offset < miny || offset > maxy)
241     continue;
242    
243 pcg 1.3 if (opt_reverse)
244     temp = detabificate (lines[listlen-lin-1].line);
245     else
246     temp = detabificate (lines[lin].line);
247 pcg 1.2
248     if (opt_shade)
249     {
250     XSetForeground (disp, WinGC, black_color);
251     XDrawString (disp, root, WinGC, win_x + 2, win_y + offset + 2,
252     temp, strlen (temp));
253     }
254    
255     XSetForeground (disp, WinGC, lines[lin].color);
256     XDrawString (disp, root, WinGC, win_x, win_y + offset,
257     temp, strlen (temp));
258    
259     free (temp);
260 pcg 1.1 }
261    
262     if (opt_frame) {
263     int bot_y = win_y + h + font_descent + 2;
264    
265     XDrawLine(disp, root, WinGC, win_x, win_y, win_x + w, win_y);
266     XDrawLine(disp, root, WinGC, win_x + w, win_y, win_x + w, bot_y);
267     XDrawLine(disp, root, WinGC, win_x + w, bot_y, win_x, bot_y);
268     XDrawLine(disp, root, WinGC, win_x, bot_y, win_x, win_y);
269     }
270     }
271    
272     #if HAS_REGEX
273     void transform_line(char *s)
274     {
275     #ifdef I_AM_Md
276     int i;
277     if (1) {
278     for (i = 16; s[i]; i++)
279     s[i] = s[i + 11];
280     }
281     s[i + 1] = '\0';
282     #endif
283    
284     if (transformre) {
285     int i;
286     regmatch_t matched[16];
287    
288     i = regexec(&transformre, string, 16, matched, 0);
289     if (i == 0) { /* matched */
290     }
291     }
292     }
293     #endif
294    
295    
296     /*
297     * This routine should read 'width' characters and not more. However,
298     * we really want to read width + 1 charachters if the last char is a '\n',
299     * which we should remove afterwards. So, read width+1 chars and ungetc
300     * the last character if it's not a newline. This means 'string' must be
301     * width + 2 wide!
302     */
303     int lineinput(char *string, int slen, FILE *f)
304     {
305     int len;
306    
307     do {
308     if (fgets(string, slen, f) == NULL) /* EOF or Error */
309     return 0;
310    
311     len = strlen(string);
312     } while (len == 0);
313    
314     if (string[len - 1] == '\n')
315     string[len - 1] = '\0'; /* erase newline */
316     else if (len >= slen - 1) {
317     ungetc(string[len - 1], f);
318     string[len - 1] = '\0';
319     }
320    
321     #if HAS_REGEX
322     transform_line(string);
323     #endif
324     return len;
325     }
326    
327     /* input: reads file->fname
328     * output: fills file->fp, file->inode
329     * returns file->fp
330     * in case of error, file->fp is NULL
331     */
332     FILE *openlog(struct logfile_entry *file)
333     {
334     struct stat stats;
335    
336     if ((file->fp = fopen(file->fname, "r")) == NULL) {
337     file->fp = NULL;
338     return NULL;
339     }
340    
341     fstat(fileno(file->fp), &stats);
342     if (S_ISFIFO(stats.st_mode)) {
343     if (fcntl(fileno(file->fp), F_SETFL, O_NONBLOCK) < 0)
344     perror("fcntl"), exit(1);
345     file->inode = 0;
346     } else
347     file->inode = stats.st_ino;
348    
349 pcg 1.2 if (opt_noinitial)
350     fseek (file->fp, 0, SEEK_END);
351     else if (stats.st_size > (listlen + 1) * width)
352     {
353     char dummy[255];
354    
355     fseek(file->fp, -((listlen + 2) * width), SEEK_END);
356     /* the pointer might point halfway some line. Let's
357     be nice and skip this damaged line */
358     lineinput(dummy, sizeof(dummy), file->fp);
359     }
360 pcg 1.1
361     file->last_size = stats.st_size;
362     return file->fp;
363     }
364    
365     void reopen(void)
366     {
367     struct logfile_entry *e;
368    
369     for (e = loglist; e; e = e->next) {
370     if (!e->inode)
371     continue; /* skip stdin */
372    
373     if (e->fp)
374     fclose(e->fp);
375     /* if fp is NULL we will try again later */
376     openlog(e);
377     }
378    
379     do_reopen = 0;
380     }
381    
382     void check_open_files(void)
383     {
384     struct logfile_entry *e;
385     struct stat stats;
386    
387     for (e = loglist; e; e = e->next) {
388     if (!e->inode)
389     continue; /* skip stdin */
390    
391     if (stat(e->fname, &stats) < 0) { /* file missing? */
392     sleep(1);
393     if (e->fp)
394     fclose(e->fp);
395     if (openlog(e) == NULL)
396     break;
397     }
398    
399     if (stats.st_ino != e->inode) { /* file renamed? */
400     if (e->fp)
401     fclose(e->fp);
402     if (openlog(e) == NULL)
403     break;
404     }
405    
406     if (stats.st_size < e->last_size) { /* file truncated? */
407     fseek(e->fp, 0, SEEK_SET);
408     e->last_size = stats.st_size;
409     }
410     }
411     }
412    
413     #define SCROLL_UP(lines, listlen) \
414     { \
415     int cur_line; \
416     for (cur_line = 0; cur_line < (listlen - 1); cur_line++) { \
417     strcpy(lines[cur_line].line, lines[cur_line + 1].line); \
418     lines[cur_line].color = lines[cur_line + 1].color; \
419     } \
420     }
421    
422     void main_loop(void)
423     {
424     struct linematrix *lines = xmalloc(sizeof(struct linematrix) * listlen);
425     int lin, miny, maxy, buflen;
426     char *buf;
427     time_t lastreload;
428     Region region = XCreateRegion();
429     XEvent xev;
430    
431     maxy = 0;
432     miny = win_y + h;
433     buflen = width + 2;
434     buf = xmalloc(buflen);
435     lastreload = time(NULL);
436    
437     /* Initialize linematrix */
438     for (lin = 0; lin < listlen; lin++) {
439     lines[lin].line = xmalloc(buflen);
440     strcpy(lines[lin].line, "~");
441     lines[lin].color = GetColor(def_color);
442     }
443    
444     if (!opt_noinitial)
445     while (lineinput(buf, buflen, loglist->fp) != 0) {
446     SCROLL_UP(lines, listlen);
447     /* print the next line */
448     strcpy(lines[listlen - 1].line, buf);
449     }
450    
451     for (;;) {
452     int need_update = 0;
453     struct logfile_entry *current;
454     static struct logfile_entry *lastprinted = NULL;
455    
456     /* read logs */
457     for (current = loglist; current; current = current->next) {
458     if (!current->fp)
459     continue; /* skip missing files */
460    
461     clearerr(current->fp);
462    
463     while (lineinput(buf, buflen, current->fp) != 0) {
464     /* print filename if any, and if last line was from
465     different file */
466     if (!opt_nofilename &&
467     !(lastprinted && lastprinted == current) &&
468     current->desc[0]) {
469     SCROLL_UP(lines, listlen);
470     sprintf(lines[listlen - 1].line, "[%s]", current->desc);
471     lines[listlen - 1].color = current->color;
472     }
473    
474     SCROLL_UP(lines, listlen);
475     strcpy(lines[listlen - 1].line, buf);
476     lines[listlen - 1].color = current->color;
477    
478     lastprinted = current;
479     need_update = 1;
480     }
481     }
482    
483     if (need_update)
484     redraw();
485     else {
486     XFlush(disp);
487     if (!XPending(disp)) {
488     fd_set fdr;
489     struct timeval to = interval;
490    
491     FD_ZERO(&fdr);
492     FD_SET(ConnectionNumber(disp), &fdr);
493     select(ConnectionNumber(disp) + 1, &fdr, 0, 0, &to);
494     }
495     }
496    
497     check_open_files();
498    
499     if (do_reopen)
500     reopen();
501    
502     /* we ignore possible errors due to window resizing &c */
503     while (XPending(disp)) {
504     XNextEvent(disp, &xev);
505     switch (xev.type) {
506     case Expose:
507     {
508     XRectangle r;
509    
510     r.x = xev.xexpose.x;
511     r.y = xev.xexpose.y;
512     r.width = xev.xexpose.width;
513     r.height = xev.xexpose.height;
514     XUnionRectWithRegion(&r, region, region);
515     if (miny > r.y)
516     miny = r.y;
517     if (maxy < r.y + r.height)
518     maxy = r.y + r.height;
519     }
520     break;
521     default:
522     #ifdef DEBUGMODE
523     fprintf(stderr, "PANIC! Unknown event %d\n", xev.type);
524     #endif
525     break;
526     }
527     }
528    
529     /* reload if requested */
530     if (reload && lastreload + reload < time(NULL)) {
531     if (command)
532     system(command);
533    
534     reopen();
535     lastreload = time(NULL);
536     }
537    
538     if (!XEmptyRegion(region)) {
539     XSetRegion(disp, WinGC, region);
540     refresh(lines, miny, maxy);
541     XDestroyRegion(region);
542     region = XCreateRegion();
543     maxy = 0;
544     miny = win_y + h;
545     }
546     }
547     }
548    
549    
550     int main(int argc, char *argv[])
551     {
552     int i;
553     int opt_daemonize = 0;
554     #if HAS_REGEX
555     char *transform = NULL;
556     #endif
557    
558     /* window needs to be initialized before colorlookups can be done */
559     /* just a dummy to get the color lookups right */
560     geom_mask = NoValue;
561     InitWindow();
562    
563     for (i = 1; i < argc; i++) {
564     if (argv[i][0] == '-' && argv[i][1] != '\0' && argv[i][1] != ',') {
565     if (!strcmp(argv[i], "--?") ||
566     !strcmp(argv[i], "--help") || !strcmp(argv[i], "-h"))
567     display_help(argv[0]);
568     else if (!strcmp(argv[i], "-V"))
569     display_version();
570     else if (!strcmp(argv[i], "-g") || !strcmp(argv[i], "-geometry"))
571     geom_mask = XParseGeometry(argv[++i],
572     &win_x, &win_y, &width, &listlen);
573     else if (!strcmp(argv[i], "-display"))
574     dispname = argv[++i];
575     else if (!strcmp(argv[i], "-font") || !strcmp(argv[i], "-fn"))
576     fontname = argv[++i];
577     #if HAS_REGEX
578     else if (!strcmp(argv[i], "-t"))
579     transform = argv[++i];
580     #endif
581     else if (!strcmp(argv[i], "-fork") || !strcmp(argv[i], "-f"))
582     opt_daemonize = 1;
583     else if (!strcmp(argv[i], "-reload")) {
584     reload = atoi(argv[++i]);
585     command = argv[++i];
586     }
587     else if (!strcmp(argv[i], "-shade"))
588     opt_shade = 1;
589     else if (!strcmp(argv[i], "-frame"))
590     opt_frame = 1;
591     else if (!strcmp(argv[i], "-no-filename"))
592     opt_nofilename = 1;
593     else if (!strcmp(argv[i], "-reverse"))
594     opt_reverse = 1;
595     else if (!strcmp(argv[i], "-color"))
596     def_color = argv[++i];
597     else if (!strcmp(argv[i], "-noinitial"))
598     opt_noinitial = 1;
599     else if (!strcmp(argv[i], "-interval") || !strcmp(argv[i], "-i")) {
600     double iv = atof(argv[++i]);
601    
602     interval.tv_sec = (int) iv;
603     interval.tv_usec = (iv - interval.tv_sec) * 1e6;
604     } else {
605     fprintf(stderr, "Unknown option '%s'.\n"
606     "Try --help for more information.\n", argv[i]);
607     exit(1);
608     }
609     } else { /* it must be a filename */
610     struct logfile_entry *e;
611     const char *fname, *desc, *fcolor = def_color;
612     char *p;
613    
614     /* this is not foolproof yet (',' in filenames are not allowed) */
615     fname = desc = argv[i];
616     if ((p = strchr(argv[i], ','))) {
617     *p = '\0';
618     fcolor = p + 1;
619    
620     if ((p = strchr(fcolor, ','))) {
621     *p = '\0';
622     desc = p + 1;
623     }
624     }
625    
626     e = xmalloc(sizeof(struct logfile_entry));
627     if (argv[i][0] == '-' && argv[i][1] == '\0') {
628     if ((e->fp = fdopen(0, "r")) == NULL)
629     perror("fdopen"), exit(1);
630     if (fcntl(0, F_SETFL, O_NONBLOCK) < 0)
631     perror("fcntl"), exit(1);
632     e->fname = NULL;
633     e->inode = 0;
634     e->desc = xstrdup("stdin");
635     } else {
636     int l;
637    
638     e->fname = xstrdup(fname);
639     if (openlog(e) == NULL)
640     perror(fname), exit(1);
641    
642     l = strlen(desc);
643     if (l > width - 2) /* must account for [ ] */
644     l = width - 2;
645     e->desc = xmalloc(l + 1);
646     memcpy(e->desc, desc, l);
647     *(e->desc + l) = '\0';
648     }
649    
650     e->color = GetColor(fcolor);
651     e->next = NULL;
652    
653     if (!loglist)
654     loglist = e;
655     if (loglist_tail)
656     loglist_tail->next = e;
657     loglist_tail = e;
658     }
659     }
660    
661     if (!loglist) {
662     fprintf(stderr, "You did not specify any files to tail\n"
663     "use %s --help for help\n", argv[0]);
664     exit(1);
665     }
666    
667     #if HAS_REGEX
668     if (transform) {
669     int i;
670    
671     transformre = xmalloc(sizeof(transformre));
672     i = regcomp(&transformre, transform, REG_EXTENDED);
673     if (i != 0) {
674     char buf[512];
675    
676     regerror(i, &transformre, buf, sizeof(buf));
677     fprintf(stderr, "Cannot compile regular expression: %s\n", buf);
678     }
679     }
680     #endif
681    
682     InitWindow();
683    
684     install_signal(SIGINT, blank_window);
685     install_signal(SIGQUIT, blank_window);
686     install_signal(SIGTERM, blank_window);
687     install_signal(SIGHUP, force_reopen);
688     install_signal(SIGUSR1, list_files);
689     install_signal(SIGUSR2, force_refresh);
690    
691     if (opt_daemonize)
692     daemonize();
693    
694     main_loop();
695    
696     exit(1); /* to make gcc -Wall stop complaining */
697     }
698    
699     void install_signal(int sig, void (*handler)(int))
700     {
701     struct sigaction action;
702    
703     action.sa_handler = handler;
704     sigemptyset(&action.sa_mask);
705     action.sa_flags = SA_RESTART;
706     if (sigaction(sig, &action, NULL) < 0)
707     fprintf(stderr, "sigaction(%d): %s\n", sig, strerror(errno)), exit(1);
708     }
709    
710     void *xstrdup(const char *string)
711     {
712     void *p;
713    
714     while ((p = strdup(string)) == NULL) {
715     fprintf(stderr, "Memory exausted.");
716     sleep(10);
717     }
718     return p;
719     }
720    
721     void *xmalloc(size_t size)
722     {
723     void *p;
724    
725     while ((p = malloc(size)) == NULL) {
726     fprintf(stderr, "Memory exausted.");
727     sleep(10);
728     }
729     return p;
730     }
731    
732     void display_help(char *myname)
733     {
734     printf("Usage: %s [options] file1[,color[,desc]] "
735     "[file2[,color[,desc]] ...]\n", myname);
736     printf(" -g | -geometry geometry -g WIDTHxHEIGHT+X+Y\n"
737     " -color color use color $color as default\n"
738     " -reload sec command reload after $sec and run command\n"
739     " by default -- 3 mins\n"
740     " -font FONTSPEC (-fn) font to use\n"
741     " -f | -fork fork into background\n"
742     " -reverse print new lines at the top\n"
743     " -shade add shading to font\n"
744     " -noinitial don't display the last file lines on\n"
745     " startup\n"
746     " -i | -interval seconds interval between checks (fractional\n"
747     " values o.k.). Default 3\n"
748     " -V display version information and exit\n"
749     "\n");
750     printf("Example:\n%s -g 80x25+100+50 -font fixed /var/log/messages,green "
751     "/var/log/secure,red,'ALERT'\n", myname);
752     exit(0);
753     }
754    
755     void display_version(void) {
756     printf("root-tail version " VERSION "\n");
757     exit(0);
758     }
759    
760     int daemonize(void) {
761     switch (fork()) {
762     case -1:
763     return -1;
764     case 0:
765     break;
766     default:
767     _exit(0);
768     }
769    
770     if (setsid() == -1)
771     return -1;
772    
773     return 0;
774     }
775