2 * util/log.c - implementation of the log code
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above copyright notice,
16 * this list of conditions and the following disclaimer in the documentation
17 * and/or other materials provided with the distribution.
19 * Neither the name of the NLNET LABS nor the names of its contributors may
20 * be used to endorse or promote products derived from this software without
21 * specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
37 * Implementation of log.h.
42 #include "util/locks.h"
49 /**define LOG_ constants */
52 # define LOG_WARNING 4
58 # include "winrc/win_svc.h"
61 /* default verbosity */
62 enum verbosity_value verbosity = 0;
63 /** the file logged to. */
64 static FILE* logfile = 0;
65 /** if key has been created */
66 static int key_created = 0;
67 /** pthread key for thread ids in logfile */
68 static ub_thread_key_t logkey;
69 /** the identity of this executable/process */
70 static const char* ident="unbound";
71 #if defined(HAVE_SYSLOG_H) || defined(UB_ON_WINDOWS)
72 /** are we using syslog(3) to log to */
73 static int logging_to_syslog = 0;
74 #endif /* HAVE_SYSLOG_H */
75 /** time to print in log, if NULL, use time(2) */
76 static uint32_t* log_now = NULL;
77 /** print time in UTC or in secondsfrom1970 */
78 static int log_time_asc = 0;
81 log_init(const char* filename, int use_syslog, const char* chrootdir)
86 ub_thread_key_create(&logkey, NULL);
89 #if defined(HAVE_SYSLOG_H) || defined(UB_ON_WINDOWS)
93 verbose(VERB_QUERY, "switching log to %s",
94 use_syslog?"syslog":(filename&&filename[0]?filename:"stderr"));
95 if(logfile && logfile != stderr)
98 if(logging_to_syslog) {
100 logging_to_syslog = 0;
103 /* do not delay opening until first write, because we may
104 * chroot and no longer be able to access dev/log and so on */
105 openlog(ident, LOG_NDELAY, LOG_DAEMON);
106 logging_to_syslog = 1;
109 #elif defined(UB_ON_WINDOWS)
110 if(logging_to_syslog) {
111 logging_to_syslog = 0;
114 logging_to_syslog = 1;
117 #endif /* HAVE_SYSLOG_H */
118 if(!filename || !filename[0]) {
122 /* open the file for logging */
123 if(chrootdir && chrootdir[0] && strncmp(filename, chrootdir,
124 strlen(chrootdir)) == 0)
125 filename += strlen(chrootdir);
126 f = fopen(filename, "a");
128 log_err("Could not open logfile %s: %s", filename,
132 #ifndef UB_ON_WINDOWS
133 /* line buffering does not work on windows */
134 setvbuf(f, NULL, (int)_IOLBF, 0);
139 void log_file(FILE *f)
144 void log_thread_set(int* num)
146 ub_thread_key_set(logkey, num);
149 void log_ident_set(const char* id)
154 void log_set_time(uint32_t* t)
159 void log_set_time_asc(int use_asc)
161 log_time_asc = use_asc;
165 log_vmsg(int pri, const char* type,
166 const char *format, va_list args)
168 char message[MAXSYSLOGMSGLEN];
169 unsigned int* tid = (unsigned int*)ub_thread_key_get(logkey);
171 #if defined(HAVE_STRFTIME) && defined(HAVE_LOCALTIME_R)
174 #elif defined(UB_ON_WINDOWS)
175 char tmbuf[128], dtbuf[128];
178 vsnprintf(message, sizeof(message), format, args);
180 if(logging_to_syslog) {
181 syslog(pri, "[%d:%x] %s: %s",
182 (int)getpid(), tid?*tid:0, type, message);
185 #elif defined(UB_ON_WINDOWS)
186 if(logging_to_syslog) {
190 DWORD tp = MSG_GENERIC_ERR;
191 WORD wt = EVENTLOG_ERROR_TYPE;
192 if(strcmp(type, "info") == 0) {
194 wt=EVENTLOG_INFORMATION_TYPE;
195 } else if(strcmp(type, "warning") == 0) {
197 wt=EVENTLOG_WARNING_TYPE;
198 } else if(strcmp(type, "notice") == 0
199 || strcmp(type, "debug") == 0) {
200 tp=MSG_GENERIC_SUCCESS;
203 snprintf(m, sizeof(m), "[%s:%x] %s: %s",
204 ident, tid?*tid:0, type, message);
205 s = RegisterEventSource(NULL, SERVICE_NAME);
207 ReportEvent(s, wt, 0, tp, NULL, 1, 0, &str, NULL);
208 DeregisterEventSource(s);
211 #endif /* HAVE_SYSLOG_H */
214 now = (time_t)*log_now;
215 else now = (time_t)time(NULL);
216 #if defined(HAVE_STRFTIME) && defined(HAVE_LOCALTIME_R)
217 if(log_time_asc && strftime(tmbuf, sizeof(tmbuf), "%b %d %H:%M:%S",
218 localtime_r(&now, &tm))%(sizeof(tmbuf)) != 0) {
219 /* %sizeof buf!=0 because old strftime returned max on error */
220 fprintf(logfile, "%s %s[%d:%x] %s: %s\n", tmbuf,
221 ident, (int)getpid(), tid?*tid:0, type, message);
223 #elif defined(UB_ON_WINDOWS)
224 if(log_time_asc && GetTimeFormat(LOCALE_USER_DEFAULT, 0, NULL, NULL,
225 tmbuf, sizeof(tmbuf)) && GetDateFormat(LOCALE_USER_DEFAULT, 0,
226 NULL, NULL, dtbuf, sizeof(dtbuf))) {
227 fprintf(logfile, "%s %s %s[%d:%x] %s: %s\n", dtbuf, tmbuf,
228 ident, (int)getpid(), tid?*tid:0, type, message);
231 fprintf(logfile, "[%u] %s[%d:%x] %s: %s\n", (unsigned)now,
232 ident, (int)getpid(), tid?*tid:0, type, message);
234 /* line buffering does not work on windows */
240 * implementation of log_info
241 * @param format: format string printf-style.
244 log_info(const char *format, ...)
247 va_start(args, format);
248 log_vmsg(LOG_INFO, "info", format, args);
253 * implementation of log_err
254 * @param format: format string printf-style.
257 log_err(const char *format, ...)
260 va_start(args, format);
261 log_vmsg(LOG_ERR, "error", format, args);
266 * implementation of log_warn
267 * @param format: format string printf-style.
270 log_warn(const char *format, ...)
273 va_start(args, format);
274 log_vmsg(LOG_WARNING, "warning", format, args);
279 * implementation of fatal_exit
280 * @param format: format string printf-style.
283 fatal_exit(const char *format, ...)
286 va_start(args, format);
287 log_vmsg(LOG_CRIT, "fatal error", format, args);
293 * implementation of verbose
294 * @param level: verbose level for the message.
295 * @param format: format string printf-style.
298 verbose(enum verbosity_value level, const char* format, ...)
301 va_start(args, format);
302 if(verbosity >= level) {
303 if(level == VERB_OPS)
304 log_vmsg(LOG_NOTICE, "notice", format, args);
305 else if(level == VERB_DETAIL)
306 log_vmsg(LOG_INFO, "info", format, args);
307 else log_vmsg(LOG_DEBUG, "debug", format, args);
314 log_hex_f(enum verbosity_value v, const char* msg, void* data, size_t length)
317 uint8_t* data8 = (uint8_t*)data;
318 const char* hexchar = "0123456789ABCDEF";
319 char buf[1024+1]; /* alloc blocksize hex chars + \0 */
320 const size_t blocksize = 512;
324 verbose(v, "%s[%u]", msg, (unsigned)length);
328 for(i=0; i<length; i+=blocksize/2) {
330 if(length - i < blocksize/2)
332 for(j=0; j<len; j++) {
333 buf[j*2] = hexchar[ data8[i+j] >> 4 ];
334 buf[j*2 + 1] = hexchar[ data8[i+j] & 0xF ];
337 verbose(v, "%s[%u:%u] %.*s", msg, (unsigned)length,
338 (unsigned)i, (int)len*2, buf);
343 log_hex(const char* msg, void* data, size_t length)
345 log_hex_f(verbosity, msg, data, length);
348 void log_buf(enum verbosity_value level, const char* msg, ldns_buffer* buf)
350 if(verbosity < level)
352 log_hex_f(level, msg, ldns_buffer_begin(buf), ldns_buffer_limit(buf));
356 char* wsa_strerror(DWORD err)
358 static char unknown[32];
361 case WSA_INVALID_HANDLE: return "Specified event object handle is invalid.";
362 case WSA_NOT_ENOUGH_MEMORY: return "Insufficient memory available.";
363 case WSA_INVALID_PARAMETER: return "One or more parameters are invalid.";
364 case WSA_OPERATION_ABORTED: return "Overlapped operation aborted.";
365 case WSA_IO_INCOMPLETE: return "Overlapped I/O event object not in signaled state.";
366 case WSA_IO_PENDING: return "Overlapped operations will complete later.";
367 case WSAEINTR: return "Interrupted function call.";
368 case WSAEBADF: return "File handle is not valid.";
369 case WSAEACCES: return "Permission denied.";
370 case WSAEFAULT: return "Bad address.";
371 case WSAEINVAL: return "Invalid argument.";
372 case WSAEMFILE: return "Too many open files.";
373 case WSAEWOULDBLOCK: return "Resource temporarily unavailable.";
374 case WSAEINPROGRESS: return "Operation now in progress.";
375 case WSAEALREADY: return "Operation already in progress.";
376 case WSAENOTSOCK: return "Socket operation on nonsocket.";
377 case WSAEDESTADDRREQ: return "Destination address required.";
378 case WSAEMSGSIZE: return "Message too long.";
379 case WSAEPROTOTYPE: return "Protocol wrong type for socket.";
380 case WSAENOPROTOOPT: return "Bad protocol option.";
381 case WSAEPROTONOSUPPORT: return "Protocol not supported.";
382 case WSAESOCKTNOSUPPORT: return "Socket type not supported.";
383 case WSAEOPNOTSUPP: return "Operation not supported.";
384 case WSAEPFNOSUPPORT: return "Protocol family not supported.";
385 case WSAEAFNOSUPPORT: return "Address family not supported by protocol family.";
386 case WSAEADDRINUSE: return "Address already in use.";
387 case WSAEADDRNOTAVAIL: return "Cannot assign requested address.";
388 case WSAENETDOWN: return "Network is down.";
389 case WSAENETUNREACH: return "Network is unreachable.";
390 case WSAENETRESET: return "Network dropped connection on reset.";
391 case WSAECONNABORTED: return "Software caused connection abort.";
392 case WSAECONNRESET: return "Connection reset by peer.";
393 case WSAENOBUFS: return "No buffer space available.";
394 case WSAEISCONN: return "Socket is already connected.";
395 case WSAENOTCONN: return "Socket is not connected.";
396 case WSAESHUTDOWN: return "Cannot send after socket shutdown.";
397 case WSAETOOMANYREFS: return "Too many references.";
398 case WSAETIMEDOUT: return "Connection timed out.";
399 case WSAECONNREFUSED: return "Connection refused.";
400 case WSAELOOP: return "Cannot translate name.";
401 case WSAENAMETOOLONG: return "Name too long.";
402 case WSAEHOSTDOWN: return "Host is down.";
403 case WSAEHOSTUNREACH: return "No route to host.";
404 case WSAENOTEMPTY: return "Directory not empty.";
405 case WSAEPROCLIM: return "Too many processes.";
406 case WSAEUSERS: return "User quota exceeded.";
407 case WSAEDQUOT: return "Disk quota exceeded.";
408 case WSAESTALE: return "Stale file handle reference.";
409 case WSAEREMOTE: return "Item is remote.";
410 case WSASYSNOTREADY: return "Network subsystem is unavailable.";
411 case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range.";
412 case WSANOTINITIALISED: return "Successful WSAStartup not yet performed.";
413 case WSAEDISCON: return "Graceful shutdown in progress.";
414 case WSAENOMORE: return "No more results.";
415 case WSAECANCELLED: return "Call has been canceled.";
416 case WSAEINVALIDPROCTABLE: return "Procedure call table is invalid.";
417 case WSAEINVALIDPROVIDER: return "Service provider is invalid.";
418 case WSAEPROVIDERFAILEDINIT: return "Service provider failed to initialize.";
419 case WSASYSCALLFAILURE: return "System call failure.";
420 case WSASERVICE_NOT_FOUND: return "Service not found.";
421 case WSATYPE_NOT_FOUND: return "Class type not found.";
422 case WSA_E_NO_MORE: return "No more results.";
423 case WSA_E_CANCELLED: return "Call was canceled.";
424 case WSAEREFUSED: return "Database query was refused.";
425 case WSAHOST_NOT_FOUND: return "Host not found.";
426 case WSATRY_AGAIN: return "Nonauthoritative host not found.";
427 case WSANO_RECOVERY: return "This is a nonrecoverable error.";
428 case WSANO_DATA: return "Valid name, no data record of requested type.";
429 case WSA_QOS_RECEIVERS: return "QOS receivers.";
430 case WSA_QOS_SENDERS: return "QOS senders.";
431 case WSA_QOS_NO_SENDERS: return "No QOS senders.";
432 case WSA_QOS_NO_RECEIVERS: return "QOS no receivers.";
433 case WSA_QOS_REQUEST_CONFIRMED: return "QOS request confirmed.";
434 case WSA_QOS_ADMISSION_FAILURE: return "QOS admission error.";
435 case WSA_QOS_POLICY_FAILURE: return "QOS policy failure.";
436 case WSA_QOS_BAD_STYLE: return "QOS bad style.";
437 case WSA_QOS_BAD_OBJECT: return "QOS bad object.";
438 case WSA_QOS_TRAFFIC_CTRL_ERROR: return "QOS traffic control error.";
439 case WSA_QOS_GENERIC_ERROR: return "QOS generic error.";
440 case WSA_QOS_ESERVICETYPE: return "QOS service type error.";
441 case WSA_QOS_EFLOWSPEC: return "QOS flowspec error.";
442 case WSA_QOS_EPROVSPECBUF: return "Invalid QOS provider buffer.";
443 case WSA_QOS_EFILTERSTYLE: return "Invalid QOS filter style.";
444 case WSA_QOS_EFILTERTYPE: return "Invalid QOS filter type.";
445 case WSA_QOS_EFILTERCOUNT: return "Incorrect QOS filter count.";
446 case WSA_QOS_EOBJLENGTH: return "Invalid QOS object length.";
447 case WSA_QOS_EFLOWCOUNT: return "Incorrect QOS flow count.";
448 /*case WSA_QOS_EUNKOWNPSOBJ: return "Unrecognized QOS object.";*/
449 case WSA_QOS_EPOLICYOBJ: return "Invalid QOS policy object.";
450 case WSA_QOS_EFLOWDESC: return "Invalid QOS flow descriptor.";
451 case WSA_QOS_EPSFLOWSPEC: return "Invalid QOS provider-specific flowspec.";
452 case WSA_QOS_EPSFILTERSPEC: return "Invalid QOS provider-specific filterspec.";
453 case WSA_QOS_ESDMODEOBJ: return "Invalid QOS shape discard mode object.";
454 case WSA_QOS_ESHAPERATEOBJ: return "Invalid QOS shaping rate object.";
455 case WSA_QOS_RESERVED_PETYPE: return "Reserved policy QOS element type.";
457 snprintf(unknown, sizeof(unknown),
458 "unknown WSA error code %d", (int)err);
462 #endif /* USE_WINSOCK */