ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/root-tail/root-tail.c
Revision: 1.1
Committed: Sun Mar 10 00:17:30 2002 UTC (24 years, 6 months ago) by pcg
Content type: text/plain
Branch: MAIN
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     int opt_noinitial, opt_shade, opt_frame, opt_reverse, opt_nofilename,
65     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     /*
193     * redraw does a complete redraw, rather than an update (i.e. the area
194     * gets cleared first)
195     * the rest is handled by regular refresh()'es
196     */
197     void redraw(void)
198     {
199     XClearArea(disp, root, win_x, win_y, w, h + font_descent + 2, True);
200     }
201    
202     /* Just redraw everything without clearing (i.e. after an EXPOSE event) */
203     void refresh(struct linematrix *lines, int miny, int maxy)
204     {
205     int lin;
206     int offset = (listlen + 1) * font_height;
207     unsigned long black_color = GetColor("black");
208    
209     miny -= win_y + font_height;
210     maxy -= win_y - font_height;
211    
212     for (lin = listlen; lin--;) {
213     int line;
214    
215     offset -= font_height;
216     if (offset < miny || offset > maxy)
217     continue;
218    
219     if (opt_reverse)
220     line = listlen - lin - 1;
221     else
222     line = lin;
223    
224     if (opt_shade) {
225     XSetForeground(disp, WinGC, black_color);
226     XDrawString(disp, root, WinGC, win_x + 2, win_y + offset + 2,
227     lines[line].line, strlen(lines[line].line));
228     }
229     XSetForeground(disp, WinGC, lines[line].color);
230     XDrawString(disp, root, WinGC, win_x, win_y + offset,
231     lines[line].line, strlen(lines[line].line));
232     }
233    
234     if (opt_frame) {
235     int bot_y = win_y + h + font_descent + 2;
236    
237     XDrawLine(disp, root, WinGC, win_x, win_y, win_x + w, win_y);
238     XDrawLine(disp, root, WinGC, win_x + w, win_y, win_x + w, bot_y);
239     XDrawLine(disp, root, WinGC, win_x + w, bot_y, win_x, bot_y);
240     XDrawLine(disp, root, WinGC, win_x, bot_y, win_x, win_y);
241     }
242     }
243    
244     #if HAS_REGEX
245     void transform_line(char *s)
246     {
247     #ifdef I_AM_Md
248     int i;
249     if (1) {
250     for (i = 16; s[i]; i++)
251     s[i] = s[i + 11];
252     }
253     s[i + 1] = '\0';
254     #endif
255    
256     if (transformre) {
257     int i;
258     regmatch_t matched[16];
259    
260     i = regexec(&transformre, string, 16, matched, 0);
261     if (i == 0) { /* matched */
262     }
263     }
264     }
265     #endif
266    
267    
268     /*
269     * This routine should read 'width' characters and not more. However,
270     * we really want to read width + 1 charachters if the last char is a '\n',
271     * which we should remove afterwards. So, read width+1 chars and ungetc
272     * the last character if it's not a newline. This means 'string' must be
273     * width + 2 wide!
274     */
275     int lineinput(char *string, int slen, FILE *f)
276     {
277     int len;
278    
279     do {
280     if (fgets(string, slen, f) == NULL) /* EOF or Error */
281     return 0;
282    
283     len = strlen(string);
284     } while (len == 0);
285    
286     if (string[len - 1] == '\n')
287     string[len - 1] = '\0'; /* erase newline */
288     else if (len >= slen - 1) {
289     ungetc(string[len - 1], f);
290     string[len - 1] = '\0';
291     }
292    
293     #if HAS_REGEX
294     transform_line(string);
295     #endif
296     return len;
297     }
298    
299     /* input: reads file->fname
300     * output: fills file->fp, file->inode
301     * returns file->fp
302     * in case of error, file->fp is NULL
303     */
304     FILE *openlog(struct logfile_entry *file)
305     {
306     struct stat stats;
307    
308     if ((file->fp = fopen(file->fname, "r")) == NULL) {
309     file->fp = NULL;
310     return NULL;
311     }
312    
313     fstat(fileno(file->fp), &stats);
314     if (S_ISFIFO(stats.st_mode)) {
315     if (fcntl(fileno(file->fp), F_SETFL, O_NONBLOCK) < 0)
316     perror("fcntl"), exit(1);
317     file->inode = 0;
318     } else
319     file->inode = stats.st_ino;
320    
321     if (stats.st_size > (listlen + 1) * width) {
322     char dummy[255];
323    
324     fseek(file->fp, -((listlen + 2) * width), SEEK_END);
325     /* the pointer might point halfway some line. Let's
326     be nice and skip this damaged line */
327     lineinput(dummy, sizeof(dummy), file->fp);
328     }
329    
330     file->last_size = stats.st_size;
331     return file->fp;
332     }
333    
334     void reopen(void)
335     {
336     struct logfile_entry *e;
337    
338     for (e = loglist; e; e = e->next) {
339     if (!e->inode)
340     continue; /* skip stdin */
341    
342     if (e->fp)
343     fclose(e->fp);
344     /* if fp is NULL we will try again later */
345     openlog(e);
346     }
347    
348     do_reopen = 0;
349     }
350    
351     void check_open_files(void)
352     {
353     struct logfile_entry *e;
354     struct stat stats;
355    
356     for (e = loglist; e; e = e->next) {
357     if (!e->inode)
358     continue; /* skip stdin */
359    
360     if (stat(e->fname, &stats) < 0) { /* file missing? */
361     sleep(1);
362     if (e->fp)
363     fclose(e->fp);
364     if (openlog(e) == NULL)
365     break;
366     }
367    
368     if (stats.st_ino != e->inode) { /* file renamed? */
369     if (e->fp)
370     fclose(e->fp);
371     if (openlog(e) == NULL)
372     break;
373     }
374    
375     if (stats.st_size < e->last_size) { /* file truncated? */
376     fseek(e->fp, 0, SEEK_SET);
377     e->last_size = stats.st_size;
378     }
379     }
380     }
381    
382     #define SCROLL_UP(lines, listlen) \
383     { \
384     int cur_line; \
385     for (cur_line = 0; cur_line < (listlen - 1); cur_line++) { \
386     strcpy(lines[cur_line].line, lines[cur_line + 1].line); \
387     lines[cur_line].color = lines[cur_line + 1].color; \
388     } \
389     }
390    
391     void main_loop(void)
392     {
393     struct linematrix *lines = xmalloc(sizeof(struct linematrix) * listlen);
394     int lin, miny, maxy, buflen;
395     char *buf;
396     time_t lastreload;
397     Region region = XCreateRegion();
398     XEvent xev;
399    
400     maxy = 0;
401     miny = win_y + h;
402     buflen = width + 2;
403     buf = xmalloc(buflen);
404     lastreload = time(NULL);
405    
406     /* Initialize linematrix */
407     for (lin = 0; lin < listlen; lin++) {
408     lines[lin].line = xmalloc(buflen);
409     strcpy(lines[lin].line, "~");
410     lines[lin].color = GetColor(def_color);
411     }
412    
413     if (!opt_noinitial)
414     while (lineinput(buf, buflen, loglist->fp) != 0) {
415     SCROLL_UP(lines, listlen);
416     /* print the next line */
417     strcpy(lines[listlen - 1].line, buf);
418     }
419    
420     for (;;) {
421     int need_update = 0;
422     struct logfile_entry *current;
423     static struct logfile_entry *lastprinted = NULL;
424    
425     /* read logs */
426     for (current = loglist; current; current = current->next) {
427     if (!current->fp)
428     continue; /* skip missing files */
429    
430     clearerr(current->fp);
431    
432     while (lineinput(buf, buflen, current->fp) != 0) {
433     /* print filename if any, and if last line was from
434     different file */
435     if (!opt_nofilename &&
436     !(lastprinted && lastprinted == current) &&
437     current->desc[0]) {
438     SCROLL_UP(lines, listlen);
439     sprintf(lines[listlen - 1].line, "[%s]", current->desc);
440     lines[listlen - 1].color = current->color;
441     }
442    
443     SCROLL_UP(lines, listlen);
444     strcpy(lines[listlen - 1].line, buf);
445     lines[listlen - 1].color = current->color;
446    
447     lastprinted = current;
448     need_update = 1;
449     }
450     }
451    
452     if (need_update)
453     redraw();
454     else {
455     XFlush(disp);
456     if (!XPending(disp)) {
457     fd_set fdr;
458     struct timeval to = interval;
459    
460     FD_ZERO(&fdr);
461     FD_SET(ConnectionNumber(disp), &fdr);
462     select(ConnectionNumber(disp) + 1, &fdr, 0, 0, &to);
463     }
464     }
465    
466     check_open_files();
467    
468     if (do_reopen)
469     reopen();
470    
471     /* we ignore possible errors due to window resizing &c */
472     while (XPending(disp)) {
473     XNextEvent(disp, &xev);
474     switch (xev.type) {
475     case Expose:
476     {
477     XRectangle r;
478    
479     r.x = xev.xexpose.x;
480     r.y = xev.xexpose.y;
481     r.width = xev.xexpose.width;
482     r.height = xev.xexpose.height;
483     XUnionRectWithRegion(&r, region, region);
484     if (miny > r.y)
485     miny = r.y;
486     if (maxy < r.y + r.height)
487     maxy = r.y + r.height;
488     }
489     break;
490     default:
491     #ifdef DEBUGMODE
492     fprintf(stderr, "PANIC! Unknown event %d\n", xev.type);
493     #endif
494     break;
495     }
496     }
497    
498     /* reload if requested */
499     if (reload && lastreload + reload < time(NULL)) {
500     if (command)
501     system(command);
502    
503     reopen();
504     lastreload = time(NULL);
505     }
506    
507     if (!XEmptyRegion(region)) {
508     XSetRegion(disp, WinGC, region);
509     refresh(lines, miny, maxy);
510     XDestroyRegion(region);
511     region = XCreateRegion();
512     maxy = 0;
513     miny = win_y + h;
514     }
515     }
516     }
517    
518    
519     int main(int argc, char *argv[])
520     {
521     int i;
522     int opt_daemonize = 0;
523     #if HAS_REGEX
524     char *transform = NULL;
525     #endif
526    
527     /* window needs to be initialized before colorlookups can be done */
528     /* just a dummy to get the color lookups right */
529     geom_mask = NoValue;
530     InitWindow();
531    
532     for (i = 1; i < argc; i++) {
533     if (argv[i][0] == '-' && argv[i][1] != '\0' && argv[i][1] != ',') {
534     if (!strcmp(argv[i], "--?") ||
535     !strcmp(argv[i], "--help") || !strcmp(argv[i], "-h"))
536     display_help(argv[0]);
537     else if (!strcmp(argv[i], "-V"))
538     display_version();
539     else if (!strcmp(argv[i], "-g") || !strcmp(argv[i], "-geometry"))
540     geom_mask = XParseGeometry(argv[++i],
541     &win_x, &win_y, &width, &listlen);
542     else if (!strcmp(argv[i], "-display"))
543     dispname = argv[++i];
544     else if (!strcmp(argv[i], "-font") || !strcmp(argv[i], "-fn"))
545     fontname = argv[++i];
546     #if HAS_REGEX
547     else if (!strcmp(argv[i], "-t"))
548     transform = argv[++i];
549     #endif
550     else if (!strcmp(argv[i], "-fork") || !strcmp(argv[i], "-f"))
551     opt_daemonize = 1;
552     else if (!strcmp(argv[i], "-reload")) {
553     reload = atoi(argv[++i]);
554     command = argv[++i];
555     }
556     else if (!strcmp(argv[i], "-shade"))
557     opt_shade = 1;
558     else if (!strcmp(argv[i], "-frame"))
559     opt_frame = 1;
560     else if (!strcmp(argv[i], "-no-filename"))
561     opt_nofilename = 1;
562     else if (!strcmp(argv[i], "-reverse"))
563     opt_reverse = 1;
564     else if (!strcmp(argv[i], "-color"))
565     def_color = argv[++i];
566     else if (!strcmp(argv[i], "-noinitial"))
567     opt_noinitial = 1;
568     else if (!strcmp(argv[i], "-interval") || !strcmp(argv[i], "-i")) {
569     double iv = atof(argv[++i]);
570    
571     interval.tv_sec = (int) iv;
572     interval.tv_usec = (iv - interval.tv_sec) * 1e6;
573     } else {
574     fprintf(stderr, "Unknown option '%s'.\n"
575     "Try --help for more information.\n", argv[i]);
576     exit(1);
577     }
578     } else { /* it must be a filename */
579     struct logfile_entry *e;
580     const char *fname, *desc, *fcolor = def_color;
581     char *p;
582    
583     /* this is not foolproof yet (',' in filenames are not allowed) */
584     fname = desc = argv[i];
585     if ((p = strchr(argv[i], ','))) {
586     *p = '\0';
587     fcolor = p + 1;
588    
589     if ((p = strchr(fcolor, ','))) {
590     *p = '\0';
591     desc = p + 1;
592     }
593     }
594    
595     e = xmalloc(sizeof(struct logfile_entry));
596     if (argv[i][0] == '-' && argv[i][1] == '\0') {
597     if ((e->fp = fdopen(0, "r")) == NULL)
598     perror("fdopen"), exit(1);
599     if (fcntl(0, F_SETFL, O_NONBLOCK) < 0)
600     perror("fcntl"), exit(1);
601     e->fname = NULL;
602     e->inode = 0;
603     e->desc = xstrdup("stdin");
604     } else {
605     int l;
606    
607     e->fname = xstrdup(fname);
608     if (openlog(e) == NULL)
609     perror(fname), exit(1);
610    
611     l = strlen(desc);
612     if (l > width - 2) /* must account for [ ] */
613     l = width - 2;
614     e->desc = xmalloc(l + 1);
615     memcpy(e->desc, desc, l);
616     *(e->desc + l) = '\0';
617     }
618    
619     e->color = GetColor(fcolor);
620     e->next = NULL;
621    
622     if (!loglist)
623     loglist = e;
624     if (loglist_tail)
625     loglist_tail->next = e;
626     loglist_tail = e;
627     }
628     }
629    
630     if (!loglist) {
631     fprintf(stderr, "You did not specify any files to tail\n"
632     "use %s --help for help\n", argv[0]);
633     exit(1);
634     }
635    
636     #if HAS_REGEX
637     if (transform) {
638     int i;
639    
640     transformre = xmalloc(sizeof(transformre));
641     i = regcomp(&transformre, transform, REG_EXTENDED);
642     if (i != 0) {
643     char buf[512];
644    
645     regerror(i, &transformre, buf, sizeof(buf));
646     fprintf(stderr, "Cannot compile regular expression: %s\n", buf);
647     }
648     }
649     #endif
650    
651     InitWindow();
652    
653     install_signal(SIGINT, blank_window);
654     install_signal(SIGQUIT, blank_window);
655     install_signal(SIGTERM, blank_window);
656     install_signal(SIGHUP, force_reopen);
657     install_signal(SIGUSR1, list_files);
658     install_signal(SIGUSR2, force_refresh);
659    
660     if (opt_daemonize)
661     daemonize();
662    
663     main_loop();
664    
665     exit(1); /* to make gcc -Wall stop complaining */
666     }
667    
668     void install_signal(int sig, void (*handler)(int))
669     {
670     struct sigaction action;
671    
672     action.sa_handler = handler;
673     sigemptyset(&action.sa_mask);
674     action.sa_flags = SA_RESTART;
675     if (sigaction(sig, &action, NULL) < 0)
676     fprintf(stderr, "sigaction(%d): %s\n", sig, strerror(errno)), exit(1);
677     }
678    
679     void *xstrdup(const char *string)
680     {
681     void *p;
682    
683     while ((p = strdup(string)) == NULL) {
684     fprintf(stderr, "Memory exausted.");
685     sleep(10);
686     }
687     return p;
688     }
689    
690     void *xmalloc(size_t size)
691     {
692     void *p;
693    
694     while ((p = malloc(size)) == NULL) {
695     fprintf(stderr, "Memory exausted.");
696     sleep(10);
697     }
698     return p;
699     }
700    
701     void display_help(char *myname)
702     {
703     printf("Usage: %s [options] file1[,color[,desc]] "
704     "[file2[,color[,desc]] ...]\n", myname);
705     printf(" -g | -geometry geometry -g WIDTHxHEIGHT+X+Y\n"
706     " -color color use color $color as default\n"
707     " -reload sec command reload after $sec and run command\n"
708     " by default -- 3 mins\n"
709     " -font FONTSPEC (-fn) font to use\n"
710     " -f | -fork fork into background\n"
711     " -reverse print new lines at the top\n"
712     " -shade add shading to font\n"
713     " -noinitial don't display the last file lines on\n"
714     " startup\n"
715     " -i | -interval seconds interval between checks (fractional\n"
716     " values o.k.). Default 3\n"
717     " -V display version information and exit\n"
718     "\n");
719     printf("Example:\n%s -g 80x25+100+50 -font fixed /var/log/messages,green "
720     "/var/log/secure,red,'ALERT'\n", myname);
721     exit(0);
722     }
723    
724     void display_version(void) {
725     printf("root-tail version " VERSION "\n");
726     exit(0);
727     }
728    
729     int daemonize(void) {
730     switch (fork()) {
731     case -1:
732     return -1;
733     case 0:
734     break;
735     default:
736     _exit(0);
737     }
738    
739     if (setsid() == -1)
740     return -1;
741    
742     return 0;
743     }
744