ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/root-tail/root-tail.c
Revision: 1.26
Committed: Sun Mar 28 21:53:09 2004 UTC (22 years, 5 months ago) by chris_moore
Content type: text/plain
Branch: MAIN
Changes since 1.25: +51 -10 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 pcg 1.7 #include <locale.h>
34 pcg 1.11 #include <ctype.h>
35     #include <stdarg.h>
36 chris_moore 1.26 #include <X11/Xlib.h>
37     #include <X11/Xatom.h>
38     #include <X11/Xutil.h>
39    
40 pcg 1.1 #if HAS_REGEX
41     #include <regex.h>
42     #endif
43    
44     /* data structures */
45 pcg 1.11 struct logfile_entry
46     {
47     struct logfile_entry *next;
48    
49     char *fname; /* name of file */
50     char *desc; /* alternative description */
51     char *buf; /* text read but not yet displayed */
52     FILE *fp; /* FILE struct associated with file */
53     ino_t inode; /* inode of the file opened */
54     off_t last_size; /* file size at the last check */
55     unsigned long color; /* color to be used for printing */
56     int partial; /* true if the last line isn't complete */
57     int lastpartial; /* true if the previous output wasn't complete */
58     int index; /* index into linematrix of a partial line */
59 pcg 1.1 };
60    
61 pcg 1.11 struct linematrix
62     {
63     char *line;
64 pcg 1.12 int len;
65 pcg 1.11 unsigned long color;
66 pcg 1.1 };
67    
68     /* global variables */
69 pcg 1.12 struct linematrix *lines;
70 pcg 1.11 int width = STD_WIDTH, height = STD_HEIGHT, listlen;
71 pcg 1.1 int win_x = LOC_X, win_y = LOC_Y;
72 pcg 1.22 int font_ascent, font_height;
73 pcg 1.1 int do_reopen;
74 pcg 1.21 struct timeval interval = { 2, 400000 };
75 pcg 1.7 XFontSet fontset;
76 pcg 1.1
77     /* command line options */
78 pcg 1.5 int opt_noinitial, opt_shade, opt_frame, opt_reverse, opt_nofilename,
79 chris_moore 1.24 opt_outline, opt_noflicker, opt_whole, opt_update, opt_wordwrap,
80     geom_mask, reload = 0;
81 pcg 1.1 const char *command = NULL,
82 pcg 1.11 *fontname = USE_FONT, *dispname = NULL, *def_color = DEF_COLOR,
83     *continuation = "[+]";
84 pcg 1.1
85     struct logfile_entry *loglist = NULL, *loglist_tail = NULL;
86    
87     Display *disp;
88     Window root;
89     GC WinGC;
90    
91     #if HAS_REGEX
92 pcg 1.11 struct re_list
93     {
94     regex_t from;
95     const char *to;
96     struct re_list *next;
97 pcg 1.1 };
98     struct re_list *re_head, *re_tail;
99 chris_moore 1.26 char *transform_to = NULL;
100     regex_t *transformre;
101 pcg 1.1 #endif
102    
103    
104     /* prototypes */
105 pcg 1.11 void list_files (int);
106     void force_reopen (int);
107     void force_refresh (int);
108     void blank_window (int);
109    
110     void InitWindow (void);
111     unsigned long GetColor (const char *);
112     void redraw (void);
113 pcg 1.22 void refresh (int, int, int);
114 pcg 1.11
115     void transform_line (char *s);
116     int lineinput (struct logfile_entry *);
117     void reopen (void);
118     void check_open_files (void);
119     FILE *openlog (struct logfile_entry *);
120 pcg 1.12 static void main_loop (void);
121 pcg 1.11
122     void display_version (void);
123     void display_help (char *);
124     void install_signal (int, void (*)(int));
125     void *xstrdup (const char *);
126     void *xmalloc (size_t);
127     int daemonize (void);
128 pcg 1.1
129     /* signal handlers */
130 pcg 1.11 void
131     list_files (int dummy)
132 pcg 1.1 {
133 pcg 1.11 struct logfile_entry *e;
134 pcg 1.1
135 pcg 1.11 fprintf (stderr, "Files opened:\n");
136     for (e = loglist; e; e = e->next)
137     fprintf (stderr, "\t%s (%s)\n", e->fname, e->desc);
138 pcg 1.1 }
139    
140 pcg 1.11 void
141     force_reopen (int dummy)
142 pcg 1.1 {
143 pcg 1.11 do_reopen = 1;
144 pcg 1.1 }
145    
146 pcg 1.11 void
147     force_refresh (int dummy)
148 pcg 1.1 {
149 pcg 1.11 redraw ();
150 pcg 1.1 }
151    
152 pcg 1.11 void
153     blank_window (int dummy)
154 pcg 1.1 {
155 pcg 1.19 XClearArea (disp, root, win_x - 2, win_y - 2, width + 5, height + 5, False);
156 pcg 1.11 XFlush (disp);
157     exit (0);
158 pcg 1.1 }
159    
160     /* X related functions */
161 pcg 1.11 unsigned long
162     GetColor (const char *ColorName)
163 pcg 1.1 {
164 pcg 1.11 XColor Color;
165     XWindowAttributes Attributes;
166 pcg 1.1
167 pcg 1.11 XGetWindowAttributes (disp, root, &Attributes);
168     Color.pixel = 0;
169 pcg 1.8
170 pcg 1.11 if (!XParseColor (disp, Attributes.colormap, ColorName, &Color))
171     fprintf (stderr, "can't parse %s\n", ColorName);
172     else if (!XAllocColor (disp, Attributes.colormap, &Color))
173     fprintf (stderr, "can't allocate %s\n", ColorName);
174 pcg 1.8
175 pcg 1.11 return Color.pixel;
176 pcg 1.1 }
177    
178 pcg 1.11 static Window
179     root_window (Display * display, int screen_number)
180 pcg 1.7 {
181 pcg 1.11 Atom SWM_VROOT = XInternAtom (display, "__SWM_VROOT", False);
182 pcg 1.7 Window real_root_window = RootWindow (display, screen_number);
183    
184 pcg 1.11 if (root) /* root window set via option */
185 pcg 1.8 return root;
186    
187 pcg 1.11 if (SWM_VROOT != None)
188 pcg 1.7 {
189     Window unused, *windows;
190     unsigned int count;
191    
192     if (XQueryTree (display, real_root_window, &unused, &unused, &windows,
193 pcg 1.11 &count))
194     {
195     int i;
196    
197     for (i = 0; i < count; i++)
198     {
199     Atom type;
200     int format;
201     unsigned long nitems, bytes_after_return;
202     unsigned char *virtual_root_window;
203    
204     if (XGetWindowProperty (display, windows[i], SWM_VROOT,
205     0, 1, False, XA_WINDOW, &type, &format,
206     &nitems, &bytes_after_return,
207     &virtual_root_window) == Success)
208     {
209     if (type != None)
210     {
211     if (type == XA_WINDOW)
212     {
213     XFree (windows);
214     return (Window) virtual_root_window;
215     }
216     else
217     fprintf (stderr,
218     "__SWM_VROOT property type mismatch");
219     }
220     }
221     else
222     fprintf (stderr,
223     "failed to get __SWM_VROOT property on window 0x%lx",
224     windows[i]);
225     }
226    
227     if (count)
228     XFree (windows);
229     }
230 pcg 1.7 else
231 pcg 1.11 fprintf (stderr, "Can't query tree on root window 0x%lx",
232     real_root_window);
233 pcg 1.7 }
234     else
235     /* This shouldn't happen. The Xlib documentation is wrong BTW. */
236     fprintf (stderr, "Can't intern atom __SWM_VROOT");
237    
238     return real_root_window;
239     }
240    
241 pcg 1.11 void
242     InitWindow (void)
243 pcg 1.1 {
244 pcg 1.11 XGCValues gcv;
245     unsigned long gcm;
246     int screen, ScreenWidth, ScreenHeight;
247    
248     if (!(disp = XOpenDisplay (dispname)))
249     {
250     fprintf (stderr, "Can't open display %s.\n", dispname);
251     exit (1);
252     }
253    
254     screen = DefaultScreen (disp);
255     ScreenHeight = DisplayHeight (disp, screen);
256     ScreenWidth = DisplayWidth (disp, screen);
257    
258     root = root_window (disp, screen);
259    
260     gcm = GCBackground;
261     gcv.graphics_exposures = True;
262     WinGC = XCreateGC (disp, root, gcm, &gcv);
263     XMapWindow (disp, root);
264     XSetForeground (disp, WinGC, GetColor (DEF_COLOR));
265    
266     {
267     char **missing_charset_list;
268     int missing_charset_count;
269     char *def_string;
270    
271     fontset = XCreateFontSet (disp, fontname,
272     &missing_charset_list, &missing_charset_count,
273     &def_string);
274    
275     if (missing_charset_count)
276     {
277     fprintf (stderr,
278     "Missing charsets in String to FontSet conversion (%s)\n",
279     missing_charset_list[0]);
280     XFreeStringList (missing_charset_list);
281     }
282     }
283    
284     if (!fontset)
285     {
286     fprintf (stderr, "unable to create fontset, exiting.\n");
287     exit (1);
288     }
289    
290     {
291     XFontSetExtents *xfe = XExtentsOfFontSet (fontset);
292    
293     font_height = xfe->max_logical_extent.height;
294 pcg 1.22 font_ascent = -xfe->max_logical_extent.y;
295 pcg 1.11 }
296    
297     if (geom_mask & XNegative)
298     win_x = win_x + ScreenWidth - width;
299     if (geom_mask & YNegative)
300     win_y = win_y + ScreenHeight - height;
301    
302     listlen = height / font_height;
303 pcg 1.1
304 pcg 1.11 if (!listlen)
305     {
306     fprintf (stderr, "height too small for a single line, setting to %d\n",
307     font_height);
308     listlen = 1;
309     }
310    
311     height = listlen * font_height;
312    
313     XSelectInput (disp, root, ExposureMask | FocusChangeMask);
314 pcg 1.1 }
315    
316     /*
317     * redraw does a complete redraw, rather than an update (i.e. the area
318     * gets cleared first)
319     * the rest is handled by regular refresh()'es
320     */
321 pcg 1.11 void
322     redraw (void)
323 pcg 1.1 {
324 pcg 1.20 XSetClipMask (disp, WinGC, None);
325 pcg 1.22 refresh (0, 32768, 1);
326 pcg 1.1 }
327    
328     /* Just redraw everything without clearing (i.e. after an EXPOSE event) */
329 pcg 1.11 void
330 pcg 1.22 refresh (int miny, int maxy, int clear)
331 pcg 1.1 {
332 pcg 1.11 int lin;
333     int offset = (listlen + 1) * font_height;
334     unsigned long black_color = GetColor ("black");
335 pcg 1.1
336 pcg 1.11 miny -= win_y + font_height;
337     maxy -= win_y - font_height;
338 pcg 1.1
339 pcg 1.22 if (clear && !opt_noflicker)
340     XClearArea (disp, root, win_x, win_y, width, height, False);
341    
342 pcg 1.11 for (lin = listlen; lin--;)
343     {
344 pcg 1.12 struct linematrix *line = lines + (opt_reverse ? listlen - lin - 1 : lin);
345 pcg 1.7
346 pcg 1.11 offset -= font_height;
347 pcg 1.7
348 pcg 1.11 if (offset < miny || offset > maxy)
349     continue;
350 jebusbfb 1.4
351 pcg 1.22 if (clear && opt_noflicker)
352     XClearArea (disp, root, win_x, win_y + offset - font_ascent, width, font_height, False);
353    
354 pcg 1.21 if (opt_outline)
355     {
356     XSetForeground (disp, WinGC, black_color);
357     XmbDrawString (disp, root, fontset, WinGC, win_x - 1,
358     win_y + offset + 1, line->line, line->len);
359     XmbDrawString (disp, root, fontset, WinGC, win_x + 1,
360     win_y + offset + 1, line->line, line->len);
361     XmbDrawString (disp, root, fontset, WinGC, win_x - 1,
362     win_y + offset - 1, line->line, line->len);
363     XmbDrawString (disp, root, fontset, WinGC, win_x + 1,
364     win_y + offset - 1, line->line, line->len);
365     }
366     else if (opt_shade)
367 pcg 1.11 {
368     XSetForeground (disp, WinGC, black_color);
369     XmbDrawString (disp, root, fontset, WinGC, win_x + 2,
370 pcg 1.12 win_y + offset + 2, line->line, line->len);
371 pcg 1.11 }
372    
373     XSetForeground (disp, WinGC, line->color);
374     XmbDrawString (disp, root, fontset, WinGC, win_x, win_y + offset,
375 pcg 1.12 line->line, line->len);
376 pcg 1.1 }
377    
378 pcg 1.11 if (opt_frame)
379 pcg 1.15 {
380     XSetForeground (disp, WinGC, GetColor (def_color));
381     XDrawRectangle (disp, root, WinGC, win_x - 2, win_y - 2, width + 4, height + 4);
382     }
383 pcg 1.1 }
384    
385     #if HAS_REGEX
386 pcg 1.11 void
387     transform_line (char *s)
388 pcg 1.1 {
389     #ifdef I_AM_Md
390 pcg 1.11 int i;
391     if (1)
392     {
393     for (i = 16; s[i]; i++)
394     s[i] = s[i + 11];
395 pcg 1.1 }
396 pcg 1.11 s[i + 1] = '\0';
397 pcg 1.1 #endif
398    
399 pcg 1.11 if (transformre)
400     {
401     int i;
402     regmatch_t matched[16];
403    
404 chris_moore 1.26 i = regexec (transformre, s, 16, matched, 0);
405 pcg 1.11 if (i == 0)
406     { /* matched */
407 chris_moore 1.26 int match_start = matched[0].rm_so;
408     int match_end = matched[0].rm_eo;
409     int old_len = match_end - match_start;
410     int new_len = strlen(transform_to);
411     int old_whole_len = strlen(s);
412     printf("regexp was matched by '%s' - replace with '%s'\n", s, transform_to);
413     printf("match is from %d to %d\n",
414     match_start, match_end);
415     if (new_len > old_len) {
416     s = realloc(s, old_whole_len + new_len - old_len);
417     }
418     if (new_len != old_len) {
419     memcpy(s + match_end + new_len - old_len,
420     s + match_end,
421     old_whole_len - match_end);
422     s[old_whole_len + new_len - old_len] = '\0';
423     }
424     memcpy(s + match_start,
425     transform_to,
426     new_len);
427     printf("transformed to '%s'\n", s);
428 pcg 1.11 }
429 chris_moore 1.26 else
430     {
431     printf("regexp was not matched by '%s'\n", s);
432     }
433 pcg 1.1 }
434     }
435     #endif
436    
437 pcg 1.12 char *
438     concat_line (const char *p1, const char *p2)
439     {
440     int l1 = p1 ? strlen (p1) : 0;
441     int l2 = strlen (p2);
442     char *r = xmalloc (l1 + l2 + 1);
443    
444     memcpy (r, p1, l1);
445     memcpy (r + l1, p2, l2);
446     r[l1 + l2] = 0;
447    
448     return r;
449     }
450 pcg 1.1
451     /*
452 pcg 1.12 * This routine should read a single line, no matter how long.
453 pcg 1.1 */
454 pcg 1.11 int
455     lineinput (struct logfile_entry *logfile)
456 pcg 1.1 {
457 pcg 1.12 char buff[1024], *p = buff;
458     int ch;
459 chris_moore 1.26 /* HACK this - to add on the length of any partial line which we will be appending to */
460 pcg 1.12 int ofs = logfile->buf ? strlen (logfile->buf) : 0;
461 pcg 1.1
462 pcg 1.11 do
463     {
464 pcg 1.12 ch = fgetc (logfile->fp);
465 pcg 1.1
466 pcg 1.18 if (ch == '\n' || ch == EOF)
467     break;
468 pcg 1.17 else if (ch == '\r')
469 pcg 1.18 continue; /* skip */
470 pcg 1.12 else if (ch == '\t')
471     {
472     do
473     {
474     *p++ = ' ';
475     ofs++;
476     }
477     while (ofs & 7);
478     }
479     else
480     {
481     *p++ = ch;
482     ofs++;
483     }
484 pcg 1.11 }
485 pcg 1.12 while (p < buff + (sizeof buff) - 8 - 1);
486 pcg 1.1
487 pcg 1.19 if (p == buff && ch == EOF)
488 pcg 1.12 return 0;
489    
490     *p = 0;
491    
492     p = concat_line (logfile->buf, buff);
493     free (logfile->buf); logfile->buf = p;
494 chris_moore 1.9
495 pcg 1.12 logfile->lastpartial = logfile->partial;
496 chris_moore 1.25 /* there are 3 ways we could have exited the loop: reading '\n',
497     * reaching EOF, or filling the buffer; the 2nd and 3rd of these
498     * both result in a partial line */
499     logfile->partial = ch != '\n';
500 pcg 1.12
501     if (logfile->partial && opt_whole)
502 pcg 1.11 return 0;
503 pcg 1.1
504     #if HAS_REGEX
505 pcg 1.12 transform_line (logfile->buf);
506 pcg 1.1 #endif
507 pcg 1.12 return 1;
508 pcg 1.1 }
509    
510     /* input: reads file->fname
511     * output: fills file->fp, file->inode
512     * returns file->fp
513     * in case of error, file->fp is NULL
514     */
515 pcg 1.11 FILE *
516     openlog (struct logfile_entry * file)
517     {
518     struct stat stats;
519    
520     if ((file->fp = fopen (file->fname, "r")) == NULL)
521     {
522     file->fp = NULL;
523     return NULL;
524     }
525    
526     fstat (fileno (file->fp), &stats);
527     if (S_ISFIFO (stats.st_mode))
528     {
529     if (fcntl (fileno (file->fp), F_SETFL, O_NONBLOCK) < 0)
530     perror ("fcntl"), exit (1);
531     file->inode = 0;
532     }
533     else
534     file->inode = stats.st_ino;
535    
536     if (opt_noinitial)
537     fseek (file->fp, 0, SEEK_END);
538     else if (stats.st_size > (listlen + 1) * width)
539     fseek (file->fp, -((listlen + 2) * width), SEEK_END);
540    
541     file->last_size = stats.st_size;
542     return file->fp;
543     }
544    
545     void
546     reopen (void)
547 pcg 1.1 {
548 pcg 1.11 struct logfile_entry *e;
549    
550     for (e = loglist; e; e = e->next)
551     {
552     if (!e->inode)
553     continue; /* skip stdin */
554 pcg 1.1
555 pcg 1.11 if (e->fp)
556     fclose (e->fp);
557     /* if fp is NULL we will try again later */
558     openlog (e);
559     }
560    
561     do_reopen = 0;
562     }
563 pcg 1.1
564 pcg 1.11 void
565     check_open_files (void)
566     {
567     struct logfile_entry *e;
568     struct stat stats;
569 pcg 1.1
570 pcg 1.11 for (e = loglist; e; e = e->next)
571     {
572     if (!e->inode)
573     continue; /* skip stdin */
574 pcg 1.1
575 pcg 1.11 if (stat (e->fname, &stats) < 0)
576     { /* file missing? */
577     sleep (1);
578     if (e->fp)
579     fclose (e->fp);
580     if (openlog (e) == NULL)
581 chris_moore 1.23 continue;
582 pcg 1.11 }
583    
584 chris_moore 1.23 /* HACK this - stats can be uninitialised here (if the file
585     * didn't exist when stat() was called, but was recreated during
586     * the sleep(1)) */
587 pcg 1.11 if (stats.st_ino != e->inode)
588     { /* file renamed? */
589     if (e->fp)
590     fclose (e->fp);
591     if (openlog (e) == NULL)
592 chris_moore 1.23 continue;
593 pcg 1.11 }
594    
595     if (stats.st_size < e->last_size)
596     { /* file truncated? */
597     fseek (e->fp, 0, SEEK_SET);
598     e->last_size = stats.st_size;
599     }
600 pcg 1.1 }
601     }
602    
603 pcg 1.14 /*
604     * insert a single physical line (that must be short enough to fit)
605     * at position "idx" by pushing up lines above it. the caller
606     * MUST then fill in lines[idx] with valid data.
607     */
608 pcg 1.12 static void
609     insert_line (int idx)
610     {
611     int cur_line;
612     struct logfile_entry *current;
613    
614     free (lines[0].line);
615    
616     for (cur_line = 0; cur_line < idx; cur_line++)
617     lines[cur_line] = lines[cur_line + 1];
618    
619     for (current = loglist; current; current = current->next)
620 pcg 1.16 if (current->index <= idx)
621 pcg 1.12 current->index--;
622 pcg 1.11 }
623    
624 pcg 1.14 /*
625     * remove a single physical line at position "idx" by moving the lines above it
626     * down and inserting a "~" line at the top.
627     */
628 pcg 1.12 static void
629     delete_line (int idx)
630     {
631     int cur_line;
632     struct logfile_entry *current;
633    
634     for (cur_line = idx; cur_line > 0; cur_line--)
635     lines[cur_line] = lines[cur_line - 1];
636    
637     lines[0].line = strdup ("~");
638    
639     for (current = loglist; current; current = current->next)
640 pcg 1.16 if (current->index >= 0 && current->index <= idx)
641 pcg 1.12 current->index++;
642     }
643    
644 pcg 1.14 /*
645 chris_moore 1.24 * takes a logical log file line and splits it into multiple physical
646 pcg 1.14 * screen lines by splitting it whenever a part becomes too long.
647     * lal lines will be inserted at position "idx".
648     */
649 pcg 1.12 static void
650     split_line (int idx, const char *str, unsigned long color)
651     {
652     int l = strlen (str);
653     const char *p = str;
654    
655     do
656     {
657     const char *beg = p;
658 chris_moore 1.24 int w = 0, wrapped = 0;
659     const char *break_p = NULL;
660 pcg 1.12
661     while (*p)
662     {
663 chris_moore 1.24 /* find the length in bytes of the next multibyte character */
664 pcg 1.12 int len = mblen (p, l);
665     if (len <= 0)
666 chris_moore 1.24 len = 1; /* ignore (don't skip) illegal character sequences */
667 pcg 1.12
668 chris_moore 1.24 /* find the width in pixels of the next character */
669 pcg 1.12 int cw = XmbTextEscapement (fontset, p, len);
670     if (cw + w >= width)
671 chris_moore 1.24 {
672     wrapped = 1;
673     break;
674     }
675    
676     if (opt_wordwrap && len == 1 && p[0] == ' ')
677     break_p = p;
678 pcg 1.12
679     w += cw;
680     p += len;
681     l -= len;
682     }
683    
684 chris_moore 1.24 /* if we're wrapping at spaces, and the line is long enough to
685     * wrap, and we've seen a space already, and the space wasn't
686     * the first character on the line, then wrap at the space */
687     if (opt_wordwrap && wrapped && break_p && break_p != beg)
688     {
689     l += p - break_p;
690     p = break_p;
691     }
692    
693 pcg 1.12 {
694     char *s = xmalloc (p - beg + 1);
695     memcpy (s, beg, p - beg);
696     s[p - beg] = 0;
697     insert_line (idx);
698     lines[idx].line = s;
699     lines[idx].len = p - beg;
700     lines[idx].color = color;
701     }
702 chris_moore 1.24
703     /* if we wrapped at a space, don't display the space */
704     if (opt_wordwrap && wrapped && break_p && break_p != beg)
705     {
706     l--;
707     p++;
708     }
709 pcg 1.12 }
710     while (l);
711     }
712    
713 pcg 1.14 /*
714     * append something to an existing physical line. this is done
715     * by deleting the file on-screen, concatenating the new data to it
716     * and splitting it again.
717     */
718 pcg 1.12 static void
719     append_line (int idx, const char *str)
720     {
721     unsigned long color = lines[idx].color;
722     char *old = lines[idx].line;
723     char *new = concat_line (old, str);
724    
725     free (old);
726    
727     delete_line (idx);
728     split_line (idx, new, color);
729     }
730    
731     static void
732 pcg 1.11 main_loop (void)
733     {
734 pcg 1.12 lines = xmalloc (sizeof (struct linematrix) * listlen);
735 pcg 1.20 int lin;
736 pcg 1.11 time_t lastreload;
737     Region region = XCreateRegion ();
738     XEvent xev;
739     struct logfile_entry *lastprinted = NULL;
740     struct logfile_entry *current;
741 pcg 1.18 int need_update = 1;
742 pcg 1.11
743     lastreload = time (NULL);
744    
745     /* Initialize linematrix */
746     for (lin = 0; lin < listlen; lin++)
747     {
748 pcg 1.12 lines[lin].line = strdup ("~");
749     lines[lin].len = 1;
750 pcg 1.11 lines[lin].color = GetColor (def_color);
751     }
752    
753     for (;;)
754     {
755     /* read logs */
756     for (current = loglist; current; current = current->next)
757     {
758     if (!current->fp)
759     continue; /* skip missing files */
760    
761     clearerr (current->fp);
762    
763 pcg 1.12 while (lineinput (current))
764 pcg 1.11 {
765 pcg 1.12 need_update = 1;
766 pcg 1.11 /* if we're trying to update old partial lines in
767     * place, and the last time this file was updated the
768     * output was partial, and that partial line is not
769     * too close to the top of the screen, then update
770     * that partial line */
771 pcg 1.16 if (opt_update && current->lastpartial && current->index >= 0)
772 pcg 1.11 {
773 pcg 1.16 int idx = current->index;
774     append_line (idx, current->buf);
775     current->index = idx;
776 pcg 1.13 free (current->buf), current->buf = 0;
777 pcg 1.12 continue;
778 pcg 1.11 }
779    
780     /* print filename if any, and if last line was from
781     * different file */
782 pcg 1.13 if (!opt_nofilename && lastprinted != current && current->desc[0])
783 pcg 1.11 {
784 pcg 1.12 char buf[1024]; /* HACK */
785     snprintf (buf, sizeof (buf), "[%s]", current->desc);
786     split_line (listlen - 1, buf, current->color);
787 pcg 1.11 }
788    
789     /* if this is the same file we showed last, and the
790     * last time we showed it, it wasn't finished, then
791     * append to the last line shown */
792     if (lastprinted == current && current->lastpartial)
793 chris_moore 1.23 append_line (listlen - 1, current->buf);
794     else if (current->lastpartial)
795     {
796     split_line (listlen - 1, continuation, current->color);
797 pcg 1.12 append_line (listlen - 1, current->buf);
798 chris_moore 1.23 }
799 pcg 1.11 else
800 chris_moore 1.23 split_line (listlen - 1, current->buf, current->color);
801 pcg 1.11
802 chris_moore 1.23 free (current->buf), current->buf = 0;
803 pcg 1.11 current->index = listlen - 1;
804     lastprinted = current;
805     }
806     }
807    
808     if (need_update)
809 pcg 1.18 {
810     redraw ();
811     need_update = 0;
812     }
813 pcg 1.11 else
814     {
815     XFlush (disp);
816    
817     if (!XPending (disp))
818     {
819     fd_set fdr;
820     struct timeval to = interval;
821    
822     FD_ZERO (&fdr);
823     FD_SET (ConnectionNumber (disp), &fdr);
824     select (ConnectionNumber (disp) + 1, &fdr, 0, 0, &to);
825     }
826     }
827    
828     check_open_files ();
829    
830     if (do_reopen)
831     reopen ();
832    
833     /* we ignore possible errors due to window resizing &c */
834     while (XPending (disp))
835     {
836     XNextEvent (disp, &xev);
837    
838     switch (xev.type)
839     {
840     case Expose:
841     {
842     XRectangle r;
843    
844     r.x = xev.xexpose.x;
845     r.y = xev.xexpose.y;
846     r.width = xev.xexpose.width;
847     r.height = xev.xexpose.height;
848 pcg 1.20
849 pcg 1.11 XUnionRectWithRegion (&r, region, region);
850     }
851     break;
852     default:
853     #ifdef DEBUGMODE
854     fprintf (stderr, "PANIC! Unknown event %d\n", xev.type);
855     #endif
856     break;
857     }
858     }
859    
860     /* reload if requested */
861     if (reload && lastreload + reload < time (NULL))
862     {
863     if (command && command[0])
864     system (command);
865    
866     reopen ();
867     lastreload = time (NULL);
868     }
869    
870     if (!XEmptyRegion (region))
871     {
872 pcg 1.20 XRectangle r;
873    
874 pcg 1.11 XSetRegion (disp, WinGC, region);
875 pcg 1.20 XClipBox (region, &r);
876    
877 pcg 1.22 refresh (r.y, r.y + r.height, 0);
878 pcg 1.11
879     XDestroyRegion (region);
880     region = XCreateRegion ();
881     }
882     }
883     }
884 pcg 1.1
885 pcg 1.11
886     int
887     main (int argc, char *argv[])
888 pcg 1.1 {
889 pcg 1.11 int i;
890     int opt_daemonize = 0;
891     int opt_partial = 0, file_count = 0;
892 pcg 1.1 #if HAS_REGEX
893 pcg 1.11 char *transform = NULL;
894 pcg 1.1 #endif
895    
896 pcg 1.11 setlocale (LC_CTYPE, ""); /* try to initialize the locale. */
897    
898     /* window needs to be initialized before colorlookups can be done */
899     /* just a dummy to get the color lookups right */
900     geom_mask = NoValue;
901     InitWindow ();
902    
903     for (i = 1; i < argc; i++)
904     {
905     const char *arg = argv[i];
906 pcg 1.7
907 pcg 1.11 if (arg[0] == '-' && arg[1] != '\0' && arg[1] != ',')
908     {
909     if (arg[1] == '-')
910     arg++;
911    
912     if (!strcmp (arg, "-?") ||
913     !strcmp (arg, "-help") || !strcmp (arg, "-h"))
914     display_help (argv[0]);
915     else if (!strcmp (arg, "-V"))
916     display_version ();
917     else if (!strcmp (arg, "-g") || !strcmp (arg, "-geometry"))
918     geom_mask =
919     XParseGeometry (argv[++i], &win_x, &win_y, &width, &height);
920     else if (!strcmp (arg, "-display"))
921     dispname = argv[++i];
922     else if (!strcmp (arg, "-cont"))
923     continuation = argv[++i];
924     else if (!strcmp (arg, "-font") || !strcmp (arg, "-fn"))
925     fontname = argv[++i];
926 pcg 1.1 #if HAS_REGEX
927 pcg 1.11 else if (!strcmp (arg, "-t"))
928 chris_moore 1.26 {
929     transform = argv[++i];
930     transform_to = argv[++i];
931     printf("transform: '%s' to '%s'\n", transform, transform_to);
932     }
933 pcg 1.1 #endif
934 pcg 1.11 else if (!strcmp (arg, "-fork") || !strcmp (arg, "-f"))
935     opt_daemonize = 1;
936     else if (!strcmp (arg, "-reload"))
937     {
938     reload = atoi (argv[++i]);
939     command = argv[++i];
940     }
941     else if (!strcmp (arg, "-shade"))
942     opt_shade = 1;
943 pcg 1.21 else if (!strcmp (arg, "-outline"))
944     opt_outline = 1;
945 pcg 1.22 else if (!strcmp (arg, "-noflicker"))
946     opt_noflicker = 1;
947 pcg 1.11 else if (!strcmp (arg, "-frame"))
948     opt_frame = 1;
949     else if (!strcmp (arg, "-no-filename"))
950     opt_nofilename = 1;
951     else if (!strcmp (arg, "-reverse"))
952     opt_reverse = 1;
953     else if (!strcmp (arg, "-whole"))
954     opt_whole = 1;
955     else if (!strcmp (arg, "-partial"))
956     opt_partial = 1;
957     else if (!strcmp (arg, "-update"))
958     opt_update = opt_partial = 1;
959 chris_moore 1.24 else if (!strcmp (arg, "-wordwrap"))
960     opt_wordwrap = 1;
961 pcg 1.11 else if (!strcmp (arg, "-color"))
962     def_color = argv[++i];
963     else if (!strcmp (arg, "-noinitial"))
964     opt_noinitial = 1;
965     else if (!strcmp (arg, "-id"))
966     root = atoi (argv[++i]);
967     else if (!strcmp (arg, "-interval") || !strcmp (arg, "-i"))
968     {
969     double iv = atof (argv[++i]);
970    
971     interval.tv_sec = (int) iv;
972     interval.tv_usec = (iv - interval.tv_sec) * 1e6;
973     }
974     else
975     {
976     fprintf (stderr, "Unknown option '%s'.\n"
977     "Try --help for more information.\n", arg);
978     exit (1);
979     }
980     }
981     else
982     { /* it must be a filename */
983     struct logfile_entry *e;
984     const char *fname, *desc, *fcolor = def_color;
985     char *p;
986    
987     file_count++;
988    
989     /* this is not foolproof yet (',' in filenames are not allowed) */
990     fname = desc = arg;
991     if ((p = strchr (arg, ',')))
992     {
993     *p = '\0';
994     fcolor = p + 1;
995    
996     if ((p = strchr (fcolor, ',')))
997     {
998     *p = '\0';
999     desc = p + 1;
1000     }
1001     }
1002    
1003     e = xmalloc (sizeof (struct logfile_entry));
1004 pcg 1.12 e->partial = 0;
1005     e->buf = 0;
1006 pcg 1.16 e->index = -1;
1007 pcg 1.12
1008 pcg 1.11 if (arg[0] == '-' && arg[1] == '\0')
1009     {
1010     if ((e->fp = fdopen (0, "r")) == NULL)
1011     perror ("fdopen"), exit (1);
1012     if (fcntl (0, F_SETFL, O_NONBLOCK) < 0)
1013     perror ("fcntl"), exit (1);
1014     e->fname = NULL;
1015     e->inode = 0;
1016     e->desc = xstrdup ("stdin");
1017     }
1018     else
1019     {
1020     int l;
1021    
1022     e->fname = xstrdup (fname);
1023     if (openlog (e) == NULL)
1024     perror (fname), exit (1);
1025    
1026     l = strlen (desc);
1027     if (l > width - 2) /* must account for [ ] */
1028     l = width - 2;
1029     e->desc = xmalloc (l + 1);
1030     memcpy (e->desc, desc, l);
1031     *(e->desc + l) = '\0';
1032     }
1033    
1034     e->color = GetColor (fcolor);
1035     e->partial = 0;
1036     e->next = NULL;
1037    
1038     if (!loglist)
1039     loglist = e;
1040     if (loglist_tail)
1041     loglist_tail->next = e;
1042     loglist_tail = e;
1043     }
1044     }
1045    
1046     if (!loglist)
1047     {
1048     fprintf (stderr, "You did not specify any files to tail\n"
1049     "use %s --help for help\n", argv[0]);
1050     exit (1);
1051     }
1052    
1053     if (opt_partial && opt_whole)
1054     {
1055     fprintf (stderr, "Specify at most one of -partial and -whole\n");
1056     exit (1);
1057 chris_moore 1.9 }
1058    
1059 pcg 1.11 if (opt_partial)
1060 chris_moore 1.9 /* if we specifically requested to see partial lines then don't insist on whole lines */
1061 pcg 1.11 opt_whole = 0;
1062     else if (file_count > 1)
1063 chris_moore 1.9 /* otherwise, if we've viewing multiple files, default to showing whole lines */
1064 pcg 1.11 opt_whole = 1;
1065 chris_moore 1.9
1066 pcg 1.1 #if HAS_REGEX
1067 pcg 1.11 if (transform)
1068     {
1069     int i;
1070 pcg 1.1
1071 chris_moore 1.26 printf("compiling regexp '%s'\n", transform);
1072     transformre = xmalloc (sizeof (regex_t));
1073     i = regcomp (transformre, transform, REG_EXTENDED);
1074 pcg 1.11 if (i != 0)
1075     {
1076     char buf[512];
1077    
1078 chris_moore 1.26 regerror (i, transformre, buf, sizeof (buf));
1079 pcg 1.11 fprintf (stderr, "Cannot compile regular expression: %s\n", buf);
1080     }
1081 chris_moore 1.26 else
1082     {
1083     printf("compiled '%s' OK to %x\n", transform, (int)transformre);
1084     }
1085 pcg 1.1 }
1086     #endif
1087    
1088 pcg 1.11 InitWindow ();
1089 pcg 1.1
1090 pcg 1.11 install_signal (SIGINT, blank_window);
1091     install_signal (SIGQUIT, blank_window);
1092     install_signal (SIGTERM, blank_window);
1093     install_signal (SIGHUP, force_reopen);
1094     install_signal (SIGUSR1, list_files);
1095     install_signal (SIGUSR2, force_refresh);
1096 pcg 1.1
1097 pcg 1.11 if (opt_daemonize)
1098     daemonize ();
1099 pcg 1.1
1100 pcg 1.11 main_loop ();
1101 pcg 1.1
1102 pcg 1.11 exit (1); /* to make gcc -Wall stop complaining */
1103 pcg 1.1 }
1104    
1105 pcg 1.11 void
1106     install_signal (int sig, void (*handler) (int))
1107 pcg 1.1 {
1108 pcg 1.11 struct sigaction action;
1109    
1110     action.sa_handler = handler;
1111     sigemptyset (&action.sa_mask);
1112     action.sa_flags = SA_RESTART;
1113 pcg 1.1
1114 pcg 1.11 if (sigaction (sig, &action, NULL) < 0)
1115     fprintf (stderr, "sigaction(%d): %s\n", sig, strerror (errno)), exit (1);
1116 pcg 1.1 }
1117    
1118 pcg 1.11 void *
1119     xstrdup (const char *string)
1120 pcg 1.1 {
1121 pcg 1.11 void *p;
1122 pcg 1.1
1123 pcg 1.11 while ((p = strdup (string)) == NULL)
1124     {
1125     fprintf (stderr, "Memory exausted.");
1126     sleep (10);
1127 pcg 1.1 }
1128 pcg 1.11
1129     return p;
1130 pcg 1.1 }
1131    
1132 pcg 1.11 void *
1133     xmalloc (size_t size)
1134 pcg 1.1 {
1135 pcg 1.11 void *p;
1136 pcg 1.1
1137 pcg 1.11 while ((p = malloc (size)) == NULL)
1138     {
1139     fprintf (stderr, "Memory exausted.");
1140     sleep (10);
1141 pcg 1.1 }
1142 pcg 1.12
1143 pcg 1.11 return p;
1144 pcg 1.1 }
1145    
1146 pcg 1.11 void
1147     display_help (char *myname)
1148     {
1149     printf ("Usage: %s [options] file1[,color[,desc]] "
1150     "[file2[,color[,desc]] ...]\n", myname);
1151     printf (" -g | -geometry geometry -g WIDTHxHEIGHT+X+Y\n"
1152     " -color color use color $color as default\n"
1153     " -reload sec command reload after $sec and run command\n"
1154     " -id id window id to use instead of the root window\n"
1155     " -font FONTSPEC (-fn) font to use\n"
1156     " -f | -fork fork into background\n"
1157     " -reverse print new lines at the top\n"
1158     " -whole wait for \\n before showing a line\n"
1159     " -partial show lines even if they don't end with a \\n\n"
1160     " -update allow updates to old partial lines\n"
1161     " -cont string to prefix continued partial lines with\n"
1162 chris_moore 1.24 " -wordwrap wrap long lines at spaces to avoid breaking words\n"
1163 pcg 1.11 " defaults to \"[+]\"\n"
1164     " -shade add shading to font\n"
1165     " -noinitial don't display the last file lines on\n"
1166     " startup\n"
1167     " -i | -interval seconds interval between checks (fractional\n"
1168 pcg 1.21 " values o.k.). Default 2.4 seconds\n"
1169 pcg 1.11 " -V display version information and exit\n"
1170     "\n");
1171     printf ("Example:\n%s -g 80x25+100+50 -font fixed /var/log/messages,green "
1172     "/var/log/secure,red,'ALERT'\n", myname);
1173     exit (0);
1174     }
1175    
1176     void
1177     display_version (void)
1178 pcg 1.1 {
1179 pcg 1.11 printf ("root-tail version " VERSION "\n");
1180     exit (0);
1181 pcg 1.1 }
1182    
1183 pcg 1.11 int
1184     daemonize (void)
1185     {
1186 chris_moore 1.26 pid_t pid;
1187    
1188     switch (pid = fork ())
1189 pcg 1.11 {
1190 pcg 1.1 case -1:
1191 pcg 1.11 return -1;
1192 pcg 1.1 case 0:
1193 pcg 1.11 break;
1194 pcg 1.1 default:
1195 chris_moore 1.26 printf("%d\n", pid);
1196     exit (0);
1197 pcg 1.1 }
1198    
1199 pcg 1.11 if (setsid () == -1)
1200     return -1;
1201 pcg 1.1
1202 pcg 1.11 return 0;
1203 pcg 1.1 }