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