chiark / gitweb /
log: more general error message formatting
[disorder] / lib / log.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-9, 2013 Richard Kettlewell
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file lib/log.c @brief Errors and logging
19  *
20  * All messages are initially emitted by one of the four functions
21  * below.  disorder_debug() is generally invoked via D() so that
22  * mostly you just do a test rather than a complete subroutine call.
23  *
24  * Messages are dispatched via @ref log_default.  This defaults to @ref
25  * log_stderr.  daemonize() will turn off @ref log_stderr and use @ref
26  * log_syslog instead.
27  *
28  * disorder_fatal() will call exitfn() with a nonzero status.  The
29  * default value is exit(), but it should be set to _exit() anywhere
30  * but the 'main line' of the program, to guarantee that exit() gets
31  * called at most once.
32  */
33
34 #define NO_MEMORY_ALLOCATION
35 /* because the memory allocation functions report errors */
36
37 #include "common.h"
38
39 #include <errno.h>
40 #include <sys/types.h>
41 #if HAVE_SYSLOG_H
42 # include <syslog.h>
43 #endif
44 #if HAVE_SYS_TIME_H
45 # include <sys/time.h>
46 #endif
47 #if HAVE_SYS_SOCKET_H
48 # include <sys/socket.h>
49 #endif
50 #if HAVE_NETDB_H
51 # include <netdb.h>
52 #endif
53 #include <time.h>
54
55 #include "log.h"
56 #include "disorder.h"
57 #include "printf.h"
58
59 /** @brief Definition of a log output */
60 struct log_output {
61   /** @brief Function to call */
62   void (*fn)(int pri, const char *msg, void *user);
63   /** @brief User data */
64   void *user;
65 };
66
67 /** @brief Function to call on a fatal error
68  *
69  * This is normally @c exit() but in the presence of @c fork() it
70  * sometimes gets set to @c _exit(). */
71 void (*exitfn)(int) attribute((noreturn)) = exit;
72
73 /** @brief Debug flag */
74 int debugging;
75
76 /** @brief Program name */
77 const char *progname;
78
79 /** @brief Filename for debug messages */
80 const char *debug_filename;
81
82 /** @brief Set to include timestamps in log messages */
83 int logdate;
84
85 /** @brief Line number for debug messages */
86 int debug_lineno;
87
88 /** @brief Pointer to chosen log output structure */
89 struct log_output *log_default = &log_stderr;
90
91 /** @brief Filename to debug for */
92 static const char *debug_only;
93
94 /** @brief Construct log line, encoding special characters
95  *
96  * We might be receiving things in any old encoding, or binary rubbish
97  * in no encoding at all, so escape anything we don't like the look
98  * of.  We limit the log message to a kilobyte.
99  */
100 static void format(char buffer[], size_t bufsize, const char *fmt, va_list ap) {
101   char t[1024];
102   const char *p;
103   int ch;
104   size_t n = 0;
105   
106   if(byte_vsnprintf(t, sizeof t, fmt, ap) < 0) {
107     strcpy(t, "[byte_vsnprintf failed: ");
108     strncat(t, fmt, sizeof t - strlen(t) - 1);
109   }
110   p = t;
111   while((ch = (unsigned char)*p++)) {
112     if(ch >= ' ' && ch <= 126) {
113       if(n < bufsize) buffer[n++] = ch;
114     } else {
115       if(n < bufsize) buffer[n++] = '\\';
116       if(n < bufsize) buffer[n++] = '0' + ((ch >> 6) & 7);
117       if(n < bufsize) buffer[n++] = '0' + ((ch >> 3) & 7);
118       if(n < bufsize) buffer[n++] = '0' + ((ch >> 0) & 7);
119     }
120   }
121   if(n >= bufsize)
122     n = bufsize - 1;
123   buffer[n] = 0;
124 }
125
126 /** @brief Log to a file
127  * @param pri Message priority (as per syslog)
128  * @param msg Messagge to log
129  * @param user The @c FILE @c * to log to or NULL for @c stderr
130  */
131 static void logfp(int pri, const char *msg, void *user) {
132   struct timeval tv;
133   FILE *fp = user ? user : stderr;
134   /* ...because stderr is not a constant so we can't initialize log_stderr
135    * sanely */
136   const char *p;
137   
138   if(logdate) {
139     char timebuf[64];
140     struct tm *tm;
141     gettimeofday(&tv, 0);
142     tm = localtime(&tv.tv_sec);
143     strftime(timebuf, sizeof timebuf, "%Y-%m-%d %H:%M:%S %Z", tm);
144     fprintf(fp, "%s: ", timebuf);
145   } 
146  if(progname)
147     fprintf(fp, "%s: ", progname);
148   if(pri <= LOG_ERR)
149     fputs("ERROR: ", fp);
150   else if(pri < LOG_DEBUG)
151     fputs("INFO: ", fp);
152   else {
153     if(!debug_only) {
154       if(!(debug_only = getenv("DISORDER_DEBUG_ONLY")))
155         debug_only = "";
156     }
157     gettimeofday(&tv, 0);
158     p = debug_filename;
159     while(!strncmp(p, "../", 3)) p += 3;
160     if(*debug_only && strcmp(p, debug_only))
161       return;
162     fprintf(fp, "%llu.%06lu: %s:%d: ",
163             (unsigned long long)tv.tv_sec, (unsigned long)tv.tv_usec,
164             p, debug_lineno);
165   }
166   fputs(msg, fp);
167   fputc('\n', fp);
168 }
169
170 #if HAVE_SYSLOG_H
171 /** @brief Log to syslog */
172 static void logsyslog(int pri, const char *msg,
173                       void attribute((unused)) *user) {
174   if(pri < LOG_DEBUG)
175     syslog(pri, "%s", msg);
176   else
177     syslog(pri, "%s:%d: %s", debug_filename, debug_lineno, msg);
178 }
179 #endif
180
181 /** @brief Log output that writes to @c stderr */
182 struct log_output log_stderr = { logfp, 0 };
183
184 #if HAVE_SYSLOG_H
185 /** @brief Log output that sends to syslog */
186 struct log_output log_syslog = { logsyslog, 0 };
187 #endif
188
189 /** @brief Format and log a message */
190 static void vlogger(int pri, const char *fmt, va_list ap) {
191   char buffer[1024];
192
193   format(buffer, sizeof buffer, fmt, ap);
194   log_default->fn(pri, buffer, log_default->user);
195 }
196
197 /** @brief Format and log a message */
198 static void logger(int pri, const char *fmt, ...) {
199   va_list ap;
200
201   va_start(ap, fmt);
202   vlogger(pri, fmt, ap);
203   va_end(ap);
204 }
205
206 /** @brief Format and log a message
207  * @param pri Message priority (as per syslog)
208  * @param ec Error class
209  * @param fmt Format string
210  * @param errno_value Errno value to include as a string, or 0
211  * @param ap Argument list
212  */
213 void elog(int pri, enum error_class ec, int errno_value, const char *fmt, va_list ap) {
214   char buffer[1024];
215   char errbuf[1024];
216
217   if(errno_value == 0)
218     vlogger(pri, fmt, ap);
219   else {
220     memset(buffer, 0, sizeof buffer);
221     byte_vsnprintf(buffer, sizeof buffer, fmt, ap);
222     buffer[sizeof buffer - 1] = 0;
223     logger(pri, "%s: %s", buffer,
224            format_error(ec, errno_value, errbuf, sizeof errbuf));
225   }
226 }
227
228 /** @brief Log an error and quit
229  *
230  * If @c ${DISORDER_FATAL_ABORT} is defined (as anything) then the process
231  * is aborted, so you can get a backtrace.
232  */
233 void disorder_fatal(int errno_value, const char *msg, ...) {
234   va_list ap;
235
236   va_start(ap, msg);
237   elog(LOG_CRIT, ec_errno, errno_value, msg, ap);
238   va_end(ap);
239   if(getenv("DISORDER_FATAL_ABORT")) abort();
240   exitfn(EXIT_FAILURE);
241 }
242
243 /** @brief Log an error and quit
244  *
245  * If @c ${DISORDER_FATAL_ABORT} is defined (as anything) then the process
246  * is aborted, so you can get a backtrace.
247  */
248 void disorder_fatal_ec(enum error_class ec, int errno_value, const char *msg, ...) {
249   va_list ap;
250
251   va_start(ap, msg);
252   elog(LOG_CRIT, ec, errno_value, msg, ap);
253   va_end(ap);
254   if(getenv("DISORDER_FATAL_ABORT")) abort();
255   exitfn(EXIT_FAILURE);
256 }
257
258 /** @brief Log an error */
259 void disorder_error(int errno_value, const char *msg, ...) {
260   va_list ap;
261
262   va_start(ap, msg);
263   elog(LOG_ERR, ec_errno, errno_value, msg, ap);
264   va_end(ap);
265 }
266
267 /** @brief Log an error */
268 void disorder_error_ec(enum error_class ec, int errno_value, const char *msg, ...) {
269   va_list ap;
270
271   va_start(ap, msg);
272   elog(LOG_ERR, ec, errno_value, msg, ap);
273   va_end(ap);
274 }
275
276 /** @brief Log an informational message */
277 void disorder_info(const char *msg, ...) {
278   va_list ap;
279
280   va_start(ap, msg);
281   elog(LOG_INFO, ec_none, 0, msg, ap);
282   va_end(ap);
283 }
284
285 /** @brief Log a debug message */
286 void disorder_debug(const char *msg, ...) {
287   va_list ap;
288
289   va_start(ap, msg);
290   vlogger(LOG_DEBUG, msg, ap);
291   va_end(ap);
292 }
293
294 /** @brief Set the program name from @c argc */
295 void set_progname(char **argv) {
296   if((progname = strrchr(argv[0], '/')))
297     ++progname;
298   else
299     progname = argv[0];
300 }
301
302 /** @brief Format an error string
303  * @param ec Error class
304  * @param err Error code (interpretation defined by @p ec)
305  * @param buffer Output buffer
306  * @param bufsize Size of output buffer
307  * @return Pointer to error string
308  *
309  * The return value may or may not be @p buffer.
310  */
311 #pragma GCC diagnostic ignored "-Wunused-parameter"
312 const char *format_error(enum error_class ec, int err, char buffer[], size_t bufsize) {
313   switch(ec) {
314   default:
315     return strerror(err);
316   case ec_getaddrinfo:
317     return gai_strerror(err);
318   case ec_none:
319     return "(none)";
320   }
321 }
322
323 /*
324 Local Variables:
325 c-basic-offset:2
326 comment-column:40
327 End:
328 */