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