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