chiark / gitweb /
cleanup: Replace a few calls to malloc/realloc with safe_malloc
[secnet.git] / log.c
1 #include "secnet.h"
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <time.h>
6 #include <errno.h>
7 #include <syslog.h>
8 #include <assert.h>
9 #include <unistd.h>
10 #include "process.h"
11 #include "util.h"
12
13 bool_t secnet_is_daemon=False;
14 uint32_t message_level=M_WARNING|M_ERR|M_SECURITY|M_FATAL;
15 struct log_if *system_log=NULL;
16
17 static void vMessageFallback(uint32_t class, const char *message, va_list args)
18     FORMAT(printf,2,0);
19 static void vMessageFallback(uint32_t class, const char *message, va_list args)
20 {
21     FILE *dest=stdout;
22     /* Messages go to stdout/stderr */
23     if (class & message_level) {
24         if (class&M_FATAL || class&M_ERR || class&M_WARNING) {
25             dest=stderr;
26         }
27         vfprintf(dest,message,args);
28     }
29 }
30
31 static void vMessage(uint32_t class, const char *message, va_list args)
32 {
33
34     if (system_log) {
35         /* Messages go to the system log interface */
36         vslilog_part(system_log, class, message, args);
37     } else {
38         vMessageFallback(class,message,args);
39     }
40 }  
41
42 void Message(uint32_t class, const char *message, ...)
43 {
44     va_list ap;
45
46     va_start(ap,message);
47     vMessage(class,message,ap);
48     va_end(ap);
49 }
50
51 static void MessageFallback(uint32_t class, const char *message, ...)
52     FORMAT(printf,2,3);
53 static void MessageFallback(uint32_t class, const char *message, ...)
54 {
55     va_list ap;
56
57     va_start(ap,message);
58     vMessageFallback(class,message,ap);
59     va_end(ap);
60 }
61
62 static NORETURN(vfatal(int status, bool_t perror, const char *message,
63                        va_list args));
64
65 static void vfatal(int status, bool_t perror, const char *message,
66                    va_list args)
67 {
68     int err;
69
70     err=errno;
71
72     enter_phase(PHASE_SHUTDOWN);
73     Message(M_FATAL, "secnet fatal error: ");
74     vMessage(M_FATAL, message, args);
75     if (perror)
76         Message(M_FATAL, ": %s\n",strerror(err));
77     else
78         Message(M_FATAL, "\n");
79     exit(status);
80 }
81
82 void fatal(const char *message, ...)
83 {
84     va_list args;
85     va_start(args,message);
86     vfatal(current_phase,False,message,args);
87     va_end(args);
88 }
89
90 void fatal_status(int status, const char *message, ...)
91 {
92     va_list args;
93     va_start(args,message);
94     vfatal(status,False,message,args);
95     va_end(args);
96 }
97
98 void fatal_perror(const char *message, ...)
99 {
100     va_list args;
101     va_start(args,message);
102     vfatal(current_phase,True,message,args);
103     va_end(args);
104 }
105
106 void fatal_perror_status(int status, const char *message, ...)
107 {
108     va_list args;
109     va_start(args,message);
110     vfatal(status,True,message,args);
111     va_end(args);
112 }
113
114 void vcfgfatal_maybefile(FILE *maybe_f /* or 0 */, struct cloc loc,
115                          cstring_t facility, const char *message, va_list args)
116 {
117     enter_phase(PHASE_SHUTDOWN);
118
119     if (maybe_f && ferror(maybe_f)) {
120         assert(loc.file);
121         Message(M_FATAL, "error reading config file (%s, %s): %s",
122                 facility, loc.file, strerror(errno));
123     } else if (maybe_f && feof(maybe_f)) {
124         assert(loc.file);
125         Message(M_FATAL, "unexpected end of config file (%s, %s)",
126                 facility, loc.file);
127     } else if (loc.file && loc.line) {
128         Message(M_FATAL, "config error (%s, %s:%d): ",facility,loc.file,
129                 loc.line);
130     } else if (!loc.file && loc.line) {
131         Message(M_FATAL, "config error (%s, line %d): ",facility,loc.line);
132     } else {
133         Message(M_FATAL, "config error (%s): ",facility);
134     }
135     
136     vMessage(M_FATAL,message,args);
137     exit(current_phase);
138 }
139
140 void cfgfatal_maybefile(FILE *maybe_f, struct cloc loc, cstring_t facility,
141                         const char *message, ...)
142 {
143     va_list args;
144
145     va_start(args,message);
146     vcfgfatal_maybefile(maybe_f,loc,facility,message,args);
147     va_end(args);
148 }    
149
150 void cfgfatal(struct cloc loc, cstring_t facility, const char *message, ...)
151 {
152     va_list args;
153
154     va_start(args,message);
155     vcfgfatal_maybefile(0,loc,facility,message,args);
156     va_end(args);
157 }
158
159 void cfgfile_postreadcheck(struct cloc loc, FILE *f)
160 {
161     assert(loc.file);
162     if (ferror(f)) {
163         Message(M_FATAL, "error reading config file (%s): %s\n",
164                 loc.file, strerror(errno));
165         exit(current_phase);
166     } else if (feof(f)) {
167         Message(M_FATAL, "unexpected end of config file (%s)\n", loc.file);
168         exit(current_phase);
169     }
170 }
171
172 /* Take a list of log closures and merge them */
173 struct loglist {
174     struct log_if *l;
175     struct loglist *next;
176 };
177
178 static void log_vmulti(void *sst, int class, const char *message, va_list args)
179 {
180     struct loglist *st=sst, *i;
181
182     if (secnet_is_daemon) {
183         for (i=st; i; i=i->next) {
184             vslilog(i->l,class,message,args);
185         }
186     } else {
187         vMessage(class,message,args);
188         Message(class,"\n");
189     }
190 }
191
192 void lg_vperror(struct log_if *lg, const char *desc, struct cloc *loc,
193                 int class, int errnoval, const char *fmt, va_list al)
194 {
195     int status=current_phase;
196     int esave=errno;
197
198     if (!lg)
199         lg=system_log;
200
201     if (class & M_FATAL)
202         enter_phase(PHASE_SHUTDOWN);
203
204     slilog_part(lg,class,"%s",desc);
205     if (loc)
206         slilog_part(lg,class," (%s:%d)",loc->file,loc->line);
207     slilog_part(lg,class,": ");
208     vslilog_part(lg,class,fmt,al);
209     if (errnoval)
210         slilog_part(lg,class,": %s",strerror(errnoval));
211     slilog_part(lg,class,"\n");
212
213     if (class & M_FATAL)
214         exit(status);
215
216     errno=esave;
217 }
218
219 void lg_perror(struct log_if *lg, const char *desc, struct cloc *loc,
220                int class, int errnoval, const char *fmt, ...)
221 {
222     va_list al;
223     va_start(al,fmt);
224     lg_vperror(lg,desc,loc,class,errnoval,fmt,al);
225     va_end(al);
226 }
227
228 void lg_exitstatus(struct log_if *lg, const char *desc, struct cloc *loc,
229                    int class, int status, const char *progname)
230 {
231     if (!status)
232         lg_perror(lg,desc,loc,class,0,"%s exited",progname);
233     else if (WIFEXITED(status))
234         lg_perror(lg,desc,loc,class,0,"%s exited with error exit status %d",
235                   progname,WEXITSTATUS(status));
236     else if (WIFSIGNALED(status))
237         lg_perror(lg,desc,loc,class,0,"%s died due to fatal signal %s (%d)%s",
238                   progname,strsignal(WTERMSIG(status)),WTERMSIG(status),
239                   WCOREDUMP(status)?" (core dumped)":"");
240     else
241         lg_perror(lg,desc,loc,class,0,"%s died with unknown wait status %d",
242                   progname,status);
243 }
244
245 struct log_if *init_log(list_t *ll)
246 {
247     int i=0;
248     item_t *item;
249     closure_t *cl;
250     struct loglist *l=NULL, *n;
251     struct log_if *r;
252
253     if (list_length(ll)==1) {
254         item=list_elem(ll,0);
255         cl=item->data.closure;
256         if (cl->type!=CL_LOG) {
257             cfgfatal(item->loc,"init_log","closure is not a logger");
258         }
259         return cl->interface;
260     }
261     while ((item=list_elem(ll,i++))) {
262         if (item->type!=t_closure) {
263             cfgfatal(item->loc,"init_log","item is not a closure");
264         }
265         cl=item->data.closure;
266         if (cl->type!=CL_LOG) {
267             cfgfatal(item->loc,"init_log","closure is not a logger");
268         }
269         n=safe_malloc(sizeof(*n),"init_log");
270         n->l=cl->interface;
271         n->next=l;
272         l=n;
273     }
274     if (!l) {
275         fatal("init_log: no log");
276     }
277     r=safe_malloc(sizeof(*r), "init_log");
278     r->st=l;
279     r->vlogfn=log_vmulti;
280     r->buff[0]=0;
281     return r;
282 }
283
284 struct logfile {
285     closure_t cl;
286     struct log_if ops;
287     struct cloc loc;
288     string_t logfile;
289     uint32_t level;
290     FILE *f;
291 };
292
293 static cstring_t months[]={
294     "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
295
296 static void logfile_vlog(void *sst, int class, const char *message,
297                          va_list args)
298 {
299     struct logfile *st=sst;
300     time_t t;
301     struct tm *tm;
302
303     if (secnet_is_daemon && st->f) {
304         if (class&st->level) {
305             t=time(NULL);
306             tm=localtime(&t);
307             fprintf(st->f,"%s %2d %02d:%02d:%02d ",
308                     months[tm->tm_mon],tm->tm_mday,tm->tm_hour,tm->tm_min,
309                     tm->tm_sec);
310             vfprintf(st->f,message,args);
311             fprintf(st->f,"\n");
312             fflush(st->f);
313         }
314     } else {
315         vMessageFallback(class,message,args);
316         MessageFallback(class,"\n");
317     }
318 }
319
320 static void logfile_log(void *state, int class, const char *message, ...)
321     FORMAT(printf,3,4);
322 static void logfile_log(void *state, int class, const char *message, ...)
323 {
324     va_list ap;
325
326     va_start(ap,message);
327     logfile_vlog(state,class,message,ap);
328     va_end(ap);
329 }
330
331 static void logfile_hup_notify(void *sst, int signum)
332 {
333     struct logfile *st=sst;
334     FILE *f;
335     f=fopen(st->logfile,"a");
336     if (!f) {
337         logfile_log(st,M_FATAL,"received SIGHUP, but could not reopen "
338                     "logfile: %s",strerror(errno));
339     } else {
340         fclose(st->f);
341         st->f=f;
342         logfile_log(st,M_INFO,"received SIGHUP");
343     }
344 }
345
346 static void logfile_phase_hook(void *sst, uint32_t new_phase)
347 {
348     struct logfile *st=sst;
349     FILE *f;
350
351     if (background) {
352         f=fopen(st->logfile,"a");
353         if (!f) fatal_perror("logfile (%s:%d): cannot open \"%s\"",
354                              st->loc.file,st->loc.line,st->logfile);
355         st->f=f;
356         request_signal_notification(SIGHUP, logfile_hup_notify,st);
357     }
358 }
359
360 static struct flagstr message_class_table[]={
361     { "debug-config", M_DEBUG_CONFIG },
362     { "debug-phase", M_DEBUG_PHASE },
363     { "debug", M_DEBUG },
364     { "all-debug", M_DEBUG|M_DEBUG_PHASE|M_DEBUG_CONFIG },
365     { "info", M_INFO },
366     { "notice", M_NOTICE },
367     { "warning", M_WARNING },
368     { "error", M_ERR },
369     { "security", M_SECURITY },
370     { "fatal", M_FATAL },
371     { "default", M_WARNING|M_ERR|M_SECURITY|M_FATAL },
372     { "verbose", M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|M_FATAL },
373     { "quiet", M_FATAL },
374     { NULL, 0 }
375 };
376
377 static list_t *logfile_apply(closure_t *self, struct cloc loc, dict_t *context,
378                              list_t *args)
379 {
380     struct logfile *st;
381     item_t *item;
382     dict_t *dict;
383
384     /* We should defer opening the logfile until the getresources
385        phase.  We should defer writing into the logfile until after we
386        become a daemon. */
387     
388     st=safe_malloc(sizeof(*st),"logfile_apply");
389     st->cl.description="logfile";
390     st->cl.type=CL_LOG;
391     st->cl.apply=NULL;
392     st->cl.interface=&st->ops;
393     st->ops.st=st;
394     st->ops.vlogfn=logfile_vlog;
395     st->ops.buff[0]=0;
396     st->loc=loc;
397     st->f=NULL;
398
399     item=list_elem(args,0);
400     if (!item || item->type!=t_dict) {
401         cfgfatal(loc,"logfile","argument must be a dictionary\n");
402     }
403     dict=item->data.dict;
404
405     st->logfile=dict_read_string(dict,"filename",True,"logfile",loc);
406     st->level=string_list_to_word(dict_lookup(dict,"class"),
407                                        message_class_table,"logfile");
408
409     add_hook(PHASE_GETRESOURCES,logfile_phase_hook,st);
410
411     return new_closure(&st->cl);
412 }
413
414 struct syslog {
415     closure_t cl;
416     struct log_if ops;
417     string_t ident;
418     int facility;
419     bool_t open;
420 };
421
422 static int msgclass_to_syslogpriority(uint32_t m)
423 {
424     switch (m) {
425     case M_DEBUG_CONFIG: return LOG_DEBUG;
426     case M_DEBUG_PHASE: return LOG_DEBUG;
427     case M_DEBUG: return LOG_DEBUG;
428     case M_INFO: return LOG_INFO;
429     case M_NOTICE: return LOG_NOTICE;
430     case M_WARNING: return LOG_WARNING;
431     case M_ERR: return LOG_ERR;
432     case M_SECURITY: return LOG_CRIT;
433     case M_FATAL: return LOG_EMERG;
434     default: return LOG_NOTICE;
435     }
436 }
437     
438 static void syslog_vlog(void *sst, int class, const char *message,
439                          va_list args)
440     FORMAT(printf,3,0);
441 static void syslog_vlog(void *sst, int class, const char *message,
442                          va_list args)
443 {
444     struct syslog *st=sst;
445
446     if (st->open)
447         vsyslog(msgclass_to_syslogpriority(class),message,args);
448     else {
449         vMessageFallback(class,message,args);
450         MessageFallback(class,"\n");
451     }
452 }
453
454 static struct flagstr syslog_facility_table[]={
455 #ifdef LOG_AUTH
456     { "auth", LOG_AUTH },
457 #endif
458 #ifdef LOG_AUTHPRIV
459     { "authpriv", LOG_AUTHPRIV },
460 #endif
461     { "cron", LOG_CRON },
462     { "daemon", LOG_DAEMON },
463     { "kern", LOG_KERN },
464     { "local0", LOG_LOCAL0 },
465     { "local1", LOG_LOCAL1 },
466     { "local2", LOG_LOCAL2 },
467     { "local3", LOG_LOCAL3 },
468     { "local4", LOG_LOCAL4 },
469     { "local5", LOG_LOCAL5 },
470     { "local6", LOG_LOCAL6 },
471     { "local7", LOG_LOCAL7 },
472     { "lpr", LOG_LPR },
473     { "mail", LOG_MAIL },
474     { "news", LOG_NEWS },
475     { "syslog", LOG_SYSLOG },
476     { "user", LOG_USER },
477     { "uucp", LOG_UUCP },
478     { NULL, 0 }
479 };
480
481 static void syslog_phase_hook(void *sst, uint32_t newphase)
482 {
483     struct syslog *st=sst;
484
485     if (background) {
486         openlog(st->ident,0,st->facility);
487         st->open=True;
488     }
489 }
490
491 static list_t *syslog_apply(closure_t *self, struct cloc loc, dict_t *context,
492                             list_t *args)
493 {
494     struct syslog *st;
495     dict_t *d;
496     item_t *item;
497     string_t facstr;
498
499     st=safe_malloc(sizeof(*st),"syslog_apply");
500     st->cl.description="syslog";
501     st->cl.type=CL_LOG;
502     st->cl.apply=NULL;
503     st->cl.interface=&st->ops;
504     st->ops.st=st;
505     st->ops.vlogfn=syslog_vlog;
506     st->ops.buff[0]=0;
507
508     item=list_elem(args,0);
509     if (!item || item->type!=t_dict)
510         cfgfatal(loc,"syslog","parameter must be a dictionary\n");
511     d=item->data.dict;
512
513     st->ident=dict_read_string(d, "ident", False, "syslog", loc);
514     facstr=dict_read_string(d, "facility", True, "syslog", loc);
515     st->facility=string_to_word(facstr,loc,
516                                 syslog_facility_table,"syslog");
517     st->open=False;
518     add_hook(PHASE_GETRESOURCES,syslog_phase_hook,st);
519
520     return new_closure(&st->cl);
521 }    
522
523 /* Read from a fd and output to a log.  This is a quick hack to
524    support logging stderr, and needs code adding to tidy up before it
525    can be used for anything else. */
526 #define FDLOG_BUFSIZE 1024
527 struct fdlog {
528     struct log_if *log;
529     int fd;
530     cstring_t prefix;
531     string_t buffer;
532     int i;
533     bool_t finished;
534 };
535
536 static int log_from_fd_beforepoll(void *sst, struct pollfd *fds, int *nfds_io,
537                                   int *timeout_io)
538 {
539     struct fdlog *st=sst;
540     if (!st->finished) {
541         BEFOREPOLL_WANT_FDS(1);
542         fds[0].fd=st->fd;
543         fds[0].events=POLLIN;
544     } else {
545         BEFOREPOLL_WANT_FDS(0);
546     }
547     return 0;
548 }
549
550 static void log_from_fd_afterpoll(void *sst, struct pollfd *fds, int nfds)
551 {
552     struct fdlog *st=sst;
553     int r,remain,i;
554
555     if (nfds==0) return;
556     if (fds[0].revents&POLLERR) {
557         st->finished=True;
558     }
559     if (fds[0].revents&POLLIN) {
560         remain=FDLOG_BUFSIZE-st->i-1;
561         if (remain<=0) {
562             st->buffer[FDLOG_BUFSIZE-1]=0;
563             slilog(st->log,M_WARNING,"%s: overlong line: %s",
564                          st->prefix,st->buffer);
565             st->i=0;
566             remain=FDLOG_BUFSIZE-1;
567         }
568         r=read(st->fd,st->buffer+st->i,remain);
569         if (r>0) {
570             st->i+=r;
571             for (i=0; i<st->i; i++) {
572                 if (st->buffer[i]=='\n') {
573                     st->buffer[i]=0;
574                     slilog(st->log,M_INFO,"%s: %s",
575                                  st->prefix,st->buffer);
576                     i++;
577                     memmove(st->buffer,st->buffer+i,st->i-i);
578                     st->i-=i;
579                     i=-1;
580                 }
581             }
582         } else if (errno==EINTR || iswouldblock(errno)) {
583         } else {
584             Message(M_WARNING,"log_from_fd: %s\n",strerror(errno));
585             st->finished=True;
586         }
587     }
588 }
589                 
590 void log_from_fd(int fd, cstring_t prefix, struct log_if *log)
591 {
592     struct fdlog *st;
593
594     st=safe_malloc(sizeof(*st),"log_from_fd");
595     st->log=log;
596     st->fd=fd;
597     st->prefix=prefix;
598     st->buffer=safe_malloc(FDLOG_BUFSIZE,"log_from_fd");
599     st->i=0;
600     st->finished=False;
601
602     setnonblock(st->fd);
603
604     register_for_poll(st,log_from_fd_beforepoll,log_from_fd_afterpoll,
605                       prefix);
606 }
607
608 void log_module(dict_t *dict)
609 {
610     add_closure(dict,"logfile",logfile_apply);
611     add_closure(dict,"syslog",syslog_apply);
612 }