File: flog.c

package info (click to toggle)
flog 1.8%2Borig-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 168 kB
  • sloc: ansic: 1,278; makefile: 48; sh: 12
file content (351 lines) | stat: -rw-r--r-- 7,614 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*
*
*	Copyright (c) 2001 Fredrik Sjoholm <fredrik@sjoholm.com>
*	All rights reserved.
*	License: GPL - The GNU General Public License
*
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <string.h>



struct {
  char* data;
  int used;
  int size;
} buf;

struct FileInfo {
  char *name;
  int fd;
  struct stat stat;	// remember info about file so we can know if it's been rotated
} out;

struct Conf {
  char timestamp;	// { 0 | 1 }
  char pidfile;	// { 0 | 1 }
  char * time_format;
  char * pidfile_name;
  int max_len;
  int zap_if_disk_full;
} conf;

#define DEFAULT_TIME_FORMAT "%Y%m%d;%T: "

volatile int gotHUP;

void growbuf(int size);
int openfile (struct FileInfo* file);
int filechanged (struct FileInfo* file);
void unlinkpidfile (struct Conf* conf);
void catchHUP (int sig);
void handleHUP ();
int dotime (char* prepend_to);

int main(int argc, char** argv)
{
  char *eol, *pos, *fifo_name;
  int done = 0, fifo = 0, fifo_fd = 0;
  int opt = 0;
  int totalwn = 0;
  int disk_is_full = 0;
  FILE *pid_fd;
  struct sigaction act;

  // look for switches
  conf.time_format = NULL;
  while (++opt < argc) {
    if (!strcmp(argv[opt], "-t")) {
      conf.timestamp = 1;
      conf.time_format = DEFAULT_TIME_FORMAT;
    }
    else if (!strcmp(argv[opt], "-T")) {
      opt++;
      if (opt < argc) {
        conf.timestamp = 1;
        conf.time_format = argv[opt];
      }
    } else if (!strcmp(argv[opt], "-p")) {
      opt++;
      if (opt < argc) {
        conf.pidfile = 1;
        conf.pidfile_name = argv[opt];
      }
    }
    else if (!strcmp(argv[opt], "-l")) {
      opt++;
      if (opt < argc) {
	conf.max_len = atoi (argv[opt]);
      }
    }
    else if (!strcmp(argv[opt], "-F")) {
      opt++;
      if (opt < argc) {
	fifo = 1;
	fifo_name = argv[opt];
      }
    }
    else if (!strcmp(argv[opt], "-z")) {
      conf.zap_if_disk_full = 1;
    }
    else {
      break;
    }
  }

  if (opt >= argc) {
    fprintf (stderr, 
	"Usage: pipeline| %s [options] {logfile|-}  # SIGHUP will reopen logfile (v1.8)\n"
	"	-t           prepend each line with \"YYYYMMDD;HH:MM:SS: \"\n"
	"	-T <format>  prepend each line with specified strftime(3) format\n"
	"	-l <number>  log file length limit (force truncation)\n"
	"	-F <fifo>    fifo name\n"
	"	-p <pidfile> pid file\n"
	"	-z           zap (truncate) log if disk gets full (default: grow buffer)\n",
	argv[0]);
    exit(1);
  }

  if (conf.pidfile) {
    if ((pid_fd = fopen(conf.pidfile_name, "w")) == NULL) {
      fprintf (stderr, "Could not open pidile: %s", conf.pidfile_name);
      exit(1);
    }
    else {
      fprintf(pid_fd, "%lu\n", (unsigned long)getpid());
      fclose(pid_fd);
    }
  }

  if (fifo) {
    if ((fifo_fd = open(fifo_name, O_RDONLY)) < 0) {
      fprintf(stderr, "Could not open fifo: %s", fifo_name);
      exit(1);
    }
  }

  out.name = argv[opt];
  openfile (&out);

  act.sa_handler = catchHUP;
  sigemptyset(&act.sa_mask);
  act.sa_flags = SA_RESTART;
  if (sigaction(SIGHUP, &act, NULL) < 0) {
         fprintf(stderr, "Could not install signal handler");
         exit(1);
  }

  growbuf (4096);

  while (!done) {
    int size;

    if (buf.used >= buf.size) growbuf (buf.size*2);

    /* if fifo is not used fifo_fd is zero so reading is done from the pipe */
    size = read(fifo_fd, buf.data + buf.used, buf.size - buf.used);
    if (size > 0)
      buf.used += size;
    else if (fifo) {
      close(fifo_fd);
      if ((fifo_fd = open(fifo_name, O_RDONLY)) < 0) {
	fprintf(stderr, "Could not re-open fifo: %s", fifo_name);
	exit(1);
      }
      continue;
    } else
      done = 1;

    for (;;) {

      if (gotHUP) {
	handleHUP();
	gotHUP = 0;
      }

      pos = buf.data;
      eol = (char*) memchr(buf.data, '\n', buf.used);
      if (eol == 0) break;
      eol ++;

      if (conf.timestamp && !disk_is_full) {
	pos -= dotime (pos);	// don't prepend time again if we already did it before disk got full.
      }

      while (pos < eol) {
	int wn = write(out.fd, pos, eol-pos);
	if (wn > 0) {
	  pos += wn;
	  totalwn += wn;
	  disk_is_full = 0;
	}
	else if (errno == ENOSPC) {
	  if (conf.zap_if_disk_full) {
	    char str[256];
	    if (ftruncate(out.fd,0)) {
	      fprintf(stderr, "truncating %s: %d %s\n", out.name, errno, strerror(errno));
	      unlinkpidfile(&conf);
	      exit(1);
	    }
	    write (out.fd, str, snprintf(str, sizeof(str), "Device full: truncating %s\n\n", out.name));
	  }
	  else {
	    disk_is_full = 1;
	    break;	// give up trying to write to disk until next input
	  }
	}
	else {
	  fprintf(stderr, "write %s: %d %s\n", out.name, errno, strerror(errno));
	  unlinkpidfile(&conf);
	  exit(1);
	}
	if (conf.max_len && (totalwn > conf.max_len)) {
	  char str[256];
	  if (ftruncate(out.fd,0)) {
	    fprintf(stderr, "truncating %s: %d %s\n", out.name, errno, strerror(errno));
	    unlinkpidfile(&conf);
	    exit(1);
	  }
	  write (out.fd, str, snprintf(str, sizeof(str), "File size limit: truncating %s\n\n", out.name));
	  totalwn = 0;
	}
      }

      buf.used = buf.data + buf.used - pos;
      memmove (buf.data, pos, buf.used);
      if (disk_is_full) { break; }
    }

  }

  unlinkpidfile(&conf);
  exit(0);
}



void growbuf (int size)
{
  if (size > buf.size) {
    // pad beginning of buffer with 100 bytes used by dotime()
    // pad end with the same, so the memmove() at end of loop above is always safe
    // even in case of a full disk while writing a prepended timestamp.
    buf.data = (char*) realloc (buf.data ? buf.data-100 : 0, size+100*2) + 100;
    buf.size = size;
  }
}




int openfile (struct FileInfo* file)
{
  int fd;
  if (strcmp(file->name,"-") != 0) {
#ifdef O_LARGEFILE
    fd = open (file->name, O_CREAT|O_APPEND|O_WRONLY|O_LARGEFILE, 0666);
#else
    fd = open (file->name, O_CREAT|O_APPEND|O_WRONLY, 0666);
#endif
  } else {
    fd = 2;
  }
  if (fd < 0) {
    fprintf (stderr, "open write %s: %s\n", file->name, strerror(errno));
    exit(1);
  }
  file->fd = fd;
  stat (file->name, &file->stat);	// update stat buffer
  return fd;
}


int reopenfile (struct FileInfo* file)
{
  if (strcmp(file->name,"-") != 0) {
    close (file->fd);
    return openfile (file);
  } else {
    return file->fd;
  }
}





int filechanged (struct FileInfo* file)
{
  struct stat stat2;

  if (strcmp(file->name,"-") == 0) { return 0; }

  if (stat (file->name, &stat2) < 0) {
    return 1;	// file removed or something
  }

  if (stat2.st_ino != file->stat.st_ino || stat2.st_dev != file->stat.st_dev) {
    // file changed or was moved to a different device
    return 1;
  }
  
  return 0;
}



void catchHUP (int sig)
{
  gotHUP = 1;
}



void handleHUP ()
{
  char str[256];
  if (filechanged(&out)) {
    // only reopen file and print msg if the file on disk was changed or removed
    write (out.fd, str, snprintf (str, sizeof(str), "Caught SIGHUP: Reopening %s (closed)\n\n", out.name));
    reopenfile (&out);
    write (out.fd, str, snprintf (str, sizeof(str), "Caught SIGHUP: Reopening %s (opened)\n\n", out.name));
  }
}



// format: "YYYYMMDD;HH.MM.SS: "
// make sure it's safe to prepend before the prepend_to pointer.
int dotime (char* prepend_to)
{
  time_t now;
  struct tm *t;
  static char buf[100];
  int len;

  time (&now);
  t = localtime (&now);
  len = strftime(buf, sizeof(buf), conf.time_format, t);
  memcpy (prepend_to-len, buf, len);
  return len;
}




void unlinkpidfile (struct Conf* conf)
{
  if (conf->pidfile) {
	  unlink(conf->pidfile_name);
  }
}