ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/root-tail/root-tail.c
(Generate patch)

Comparing root-tail/root-tail.c (file contents):
Revision 1.3 by pcg, Sun May 5 19:10:39 2002 UTC vs.
Revision 1.39 by pcg, Wed Mar 31 01:59:19 2004 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines