xref: /openbsd-src/sbin/unwind/libunbound/util/log.c (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /*
2  * util/log.c - implementation of the log code
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
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.
18  *
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.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 /**
36  * \file
37  * Implementation of log.h.
38  */
39 
40 #include "config.h"
41 #include "util/log.h"
42 #include "util/locks.h"
43 #include "sldns/sbuffer.h"
44 #include <stdarg.h>
45 #ifdef HAVE_TIME_H
46 #include <time.h>
47 #endif
48 #ifdef HAVE_SYSLOG_H
49 #  include <syslog.h>
50 #else
51 /**define LOG_ constants */
52 #  define LOG_CRIT 2
53 #  define LOG_ERR 3
54 #  define LOG_WARNING 4
55 #  define LOG_NOTICE 5
56 #  define LOG_INFO 6
57 #  define LOG_DEBUG 7
58 #endif
59 #ifdef UB_ON_WINDOWS
60 #  include "winrc/win_svc.h"
61 #endif
62 
63 /* default verbosity */
64 enum verbosity_value verbosity = NO_VERBOSE;
65 /** the file logged to. */
66 static FILE* logfile = 0;
67 /** if key has been created */
68 static int key_created = 0;
69 /** pthread key for thread ids in logfile */
70 static ub_thread_key_type logkey;
71 #ifndef THREADS_DISABLED
72 /** pthread mutex to protect FILE* */
73 static lock_basic_type log_lock;
74 #endif
75 /** the identity of this executable/process */
76 static const char* ident="unbound";
77 static const char* default_ident="unbound";
78 #if defined(HAVE_SYSLOG_H) || defined(UB_ON_WINDOWS)
79 /** are we using syslog(3) to log to */
80 static int logging_to_syslog = 0;
81 #endif /* HAVE_SYSLOG_H */
82 /** print time in UTC or in secondsfrom1970 */
83 static int log_time_asc = 0;
84 
85 void
86 log_init(const char* filename, int use_syslog, const char* chrootdir)
87 {
88 	FILE *f;
89 	if(!key_created) {
90 		key_created = 1;
91 		ub_thread_key_create(&logkey, NULL);
92 		lock_basic_init(&log_lock);
93 	}
94 	lock_basic_lock(&log_lock);
95 	if(logfile
96 #if defined(HAVE_SYSLOG_H) || defined(UB_ON_WINDOWS)
97 	|| logging_to_syslog
98 #endif
99 	) {
100 		lock_basic_unlock(&log_lock); /* verbose() needs the lock */
101 		verbose(VERB_QUERY, "switching log to %s",
102 			use_syslog?"syslog":(filename&&filename[0]?filename:"stderr"));
103 		lock_basic_lock(&log_lock);
104 	}
105 	if(logfile && logfile != stderr) {
106 		FILE* cl = logfile;
107 		logfile = NULL; /* set to NULL before it is closed, so that
108 			other threads have a valid logfile or NULL */
109 		fclose(cl);
110 	}
111 #ifdef HAVE_SYSLOG_H
112 #if 0	/* unwind handles syslog for us */
113 	if(logging_to_syslog) {
114 		closelog();
115 		logging_to_syslog = 0;
116 	}
117 #endif
118 	if(use_syslog) {
119 		/* do not delay opening until first write, because we may
120 		 * chroot and no longer be able to access dev/log and so on */
121 		/* the facility is LOG_DAEMON by default, but
122 		 * --with-syslog-facility=LOCAL[0-7] can override it */
123 #if 0	/* unwind handles syslog for us */
124 		openlog(ident, LOG_NDELAY, UB_SYSLOG_FACILITY);
125 #endif
126 		logging_to_syslog = 1;
127 		lock_basic_unlock(&log_lock);
128 		return;
129 	}
130 #elif defined(UB_ON_WINDOWS)
131 	if(logging_to_syslog) {
132 		logging_to_syslog = 0;
133 	}
134 	if(use_syslog) {
135 		logging_to_syslog = 1;
136 		lock_basic_unlock(&log_lock);
137 		return;
138 	}
139 #endif /* HAVE_SYSLOG_H */
140 	if(!filename || !filename[0]) {
141 		logfile = stderr;
142 		lock_basic_unlock(&log_lock);
143 		return;
144 	}
145 	/* open the file for logging */
146 	if(chrootdir && chrootdir[0] && strncmp(filename, chrootdir,
147 		strlen(chrootdir)) == 0)
148 		filename += strlen(chrootdir);
149 	f = fopen(filename, "a");
150 	if(!f) {
151 		lock_basic_unlock(&log_lock);
152 		log_err("Could not open logfile %s: %s", filename,
153 			strerror(errno));
154 		return;
155 	}
156 #ifndef UB_ON_WINDOWS
157 	/* line buffering does not work on windows */
158 	setvbuf(f, NULL, (int)_IOLBF, 0);
159 #endif
160 	logfile = f;
161 	lock_basic_unlock(&log_lock);
162 }
163 
164 void log_file(FILE *f)
165 {
166 	lock_basic_lock(&log_lock);
167 	logfile = f;
168 	lock_basic_unlock(&log_lock);
169 }
170 
171 void log_thread_set(int* num)
172 {
173 	ub_thread_key_set(logkey, num);
174 }
175 
176 int log_thread_get(void)
177 {
178 	unsigned int* tid;
179 	if(!key_created) return 0;
180 	tid = (unsigned int*)ub_thread_key_get(logkey);
181 	return (int)(tid?*tid:0);
182 }
183 
184 void log_ident_set(const char* id)
185 {
186 	ident = id;
187 }
188 
189 void log_ident_set_default(const char* id)
190 {
191 	default_ident = id;
192 }
193 
194 void log_ident_revert_to_default()
195 {
196 	ident = default_ident;
197 }
198 
199 void log_ident_set_or_default(const char* identity)
200 {
201 	if(identity == NULL || identity[0] == 0)
202 		log_ident_set(default_ident);
203 	else
204 		log_ident_set(identity);
205 }
206 
207 void log_set_time_asc(int use_asc)
208 {
209 	log_time_asc = use_asc;
210 }
211 
212 void* log_get_lock(void)
213 {
214 	if(!key_created)
215 		return NULL;
216 #ifndef THREADS_DISABLED
217 	return (void*)&log_lock;
218 #else
219 	return NULL;
220 #endif
221 }
222 
223 void
224 log_vmsg(int pri, const char* type,
225 	const char *format, va_list args)
226 {
227 	char message[MAXSYSLOGMSGLEN];
228 	unsigned int* tid = (unsigned int*)ub_thread_key_get(logkey);
229 	time_t now;
230 #if defined(HAVE_STRFTIME) && defined(HAVE_LOCALTIME_R)
231 	char tmbuf[32];
232 	struct tm tm;
233 #elif defined(UB_ON_WINDOWS)
234 	char tmbuf[128], dtbuf[128];
235 #endif
236 	(void)pri;
237 	vsnprintf(message, sizeof(message), format, args);
238 #ifdef HAVE_SYSLOG_H
239 	if(logging_to_syslog) {
240 		syslog(pri, "[%d:%x] %s: %s",
241 			(int)getpid(), tid?*tid:0, type, message);
242 		return;
243 	}
244 #elif defined(UB_ON_WINDOWS)
245 	if(logging_to_syslog) {
246 		char m[32768];
247 		HANDLE* s;
248 		LPCTSTR str = m;
249 		DWORD tp = MSG_GENERIC_ERR;
250 		WORD wt = EVENTLOG_ERROR_TYPE;
251 		if(strcmp(type, "info") == 0) {
252 			tp=MSG_GENERIC_INFO;
253 			wt=EVENTLOG_INFORMATION_TYPE;
254 		} else if(strcmp(type, "warning") == 0) {
255 			tp=MSG_GENERIC_WARN;
256 			wt=EVENTLOG_WARNING_TYPE;
257 		} else if(strcmp(type, "notice") == 0
258 			|| strcmp(type, "debug") == 0) {
259 			tp=MSG_GENERIC_SUCCESS;
260 			wt=EVENTLOG_SUCCESS;
261 		}
262 		snprintf(m, sizeof(m), "[%s:%x] %s: %s",
263 			ident, tid?*tid:0, type, message);
264 		s = RegisterEventSource(NULL, SERVICE_NAME);
265 		if(!s) return;
266 		ReportEvent(s, wt, 0, tp, NULL, 1, 0, &str, NULL);
267 		DeregisterEventSource(s);
268 		return;
269 	}
270 #endif /* HAVE_SYSLOG_H */
271 	lock_basic_lock(&log_lock);
272 	if(!logfile) {
273 		lock_basic_unlock(&log_lock);
274 		return;
275 	}
276 	now = (time_t)time(NULL);
277 #if defined(HAVE_STRFTIME) && defined(HAVE_LOCALTIME_R)
278 	if(log_time_asc && strftime(tmbuf, sizeof(tmbuf), "%b %d %H:%M:%S",
279 		localtime_r(&now, &tm))%(sizeof(tmbuf)) != 0) {
280 		/* %sizeof buf!=0 because old strftime returned max on error */
281 		fprintf(logfile, "%s %s[%d:%x] %s: %s\n", tmbuf,
282 			ident, (int)getpid(), tid?*tid:0, type, message);
283 	} else
284 #elif defined(UB_ON_WINDOWS)
285 	if(log_time_asc && GetTimeFormat(LOCALE_USER_DEFAULT, 0, NULL, NULL,
286 		tmbuf, sizeof(tmbuf)) && GetDateFormat(LOCALE_USER_DEFAULT, 0,
287 		NULL, NULL, dtbuf, sizeof(dtbuf))) {
288 		fprintf(logfile, "%s %s %s[%d:%x] %s: %s\n", dtbuf, tmbuf,
289 			ident, (int)getpid(), tid?*tid:0, type, message);
290 	} else
291 #endif
292 	fprintf(logfile, "[" ARG_LL "d] %s[%d:%x] %s: %s\n", (long long)now,
293 		ident, (int)getpid(), tid?*tid:0, type, message);
294 #ifdef UB_ON_WINDOWS
295 	/* line buffering does not work on windows */
296 	fflush(logfile);
297 #endif
298 	lock_basic_unlock(&log_lock);
299 }
300 
301 /**
302  * implementation of log_info
303  * @param format: format string printf-style.
304  */
305 void
306 log_info(const char *format, ...)
307 {
308         va_list args;
309 	va_start(args, format);
310 	log_vmsg(LOG_INFO, "info", format, args);
311 	va_end(args);
312 }
313 
314 /**
315  * implementation of log_err
316  * @param format: format string printf-style.
317  */
318 void
319 log_err(const char *format, ...)
320 {
321         va_list args;
322 	va_start(args, format);
323 	log_vmsg(LOG_ERR, "error", format, args);
324 	va_end(args);
325 }
326 
327 /**
328  * implementation of log_warn
329  * @param format: format string printf-style.
330  */
331 void
332 log_warn(const char *format, ...)
333 {
334         va_list args;
335 	va_start(args, format);
336 	log_vmsg(LOG_WARNING, "warning", format, args);
337 	va_end(args);
338 }
339 
340 /**
341  * implementation of fatal_exit
342  * @param format: format string printf-style.
343  */
344 void
345 fatal_exit(const char *format, ...)
346 {
347         va_list args;
348 	va_start(args, format);
349 	log_vmsg(LOG_CRIT, "fatal error", format, args);
350 	va_end(args);
351 	exit(1);
352 }
353 
354 /**
355  * implementation of verbose
356  * @param level: verbose level for the message.
357  * @param format: format string printf-style.
358  */
359 void
360 verbose(enum verbosity_value level, const char* format, ...)
361 {
362         va_list args;
363 	va_start(args, format);
364 	if(verbosity >= level) {
365 		if(level == VERB_OPS)
366 			log_vmsg(LOG_NOTICE, "notice", format, args);
367 		else if(level == VERB_DETAIL)
368 			log_vmsg(LOG_INFO, "info", format, args);
369 		else	log_vmsg(LOG_DEBUG, "debug", format, args);
370 	}
371 	va_end(args);
372 }
373 
374 /** log hex data */
375 static void
376 log_hex_f(enum verbosity_value v, const char* msg, void* data, size_t length)
377 {
378 	size_t i, j;
379 	uint8_t* data8 = (uint8_t*)data;
380 	const char* hexchar = "0123456789ABCDEF";
381 	char buf[1024+1]; /* alloc blocksize hex chars + \0 */
382 	const size_t blocksize = 512;
383 	size_t len;
384 
385 	if(length == 0) {
386 		verbose(v, "%s[%u]", msg, (unsigned)length);
387 		return;
388 	}
389 
390 	for(i=0; i<length; i+=blocksize/2) {
391 		len = blocksize/2;
392 		if(length - i < blocksize/2)
393 			len = length - i;
394 		for(j=0; j<len; j++) {
395 			buf[j*2] = hexchar[ data8[i+j] >> 4 ];
396 			buf[j*2 + 1] = hexchar[ data8[i+j] & 0xF ];
397 		}
398 		buf[len*2] = 0;
399 		verbose(v, "%s[%u:%u] %.*s", msg, (unsigned)length,
400 			(unsigned)i, (int)len*2, buf);
401 	}
402 }
403 
404 void
405 log_hex(const char* msg, void* data, size_t length)
406 {
407 	log_hex_f(verbosity, msg, data, length);
408 }
409 
410 void
411 log_query(const char *format, ...)
412 {
413 	va_list args;
414 	va_start(args, format);
415 	log_vmsg(LOG_INFO, "query", format, args);
416 	va_end(args);
417 }
418 
419 void
420 log_reply(const char *format, ...)
421 {
422 	va_list args;
423 	va_start(args, format);
424 	log_vmsg(LOG_INFO, "reply", format, args);
425 	va_end(args);
426 }
427 
428 void log_buf(enum verbosity_value level, const char* msg, sldns_buffer* buf)
429 {
430 	if(verbosity < level)
431 		return;
432 	log_hex_f(level, msg, sldns_buffer_begin(buf), sldns_buffer_limit(buf));
433 }
434 
435 #ifdef USE_WINSOCK
436 char* wsa_strerror(DWORD err)
437 {
438 	static char unknown[32];
439 
440 	switch(err) {
441 	case WSA_INVALID_HANDLE: return "Specified event object handle is invalid.";
442 	case WSA_NOT_ENOUGH_MEMORY: return "Insufficient memory available.";
443 	case WSA_INVALID_PARAMETER: return "One or more parameters are invalid.";
444 	case WSA_OPERATION_ABORTED: return "Overlapped operation aborted.";
445 	case WSA_IO_INCOMPLETE: return "Overlapped I/O event object not in signaled state.";
446 	case WSA_IO_PENDING: return "Overlapped operations will complete later.";
447 	case WSAEINTR: return "Interrupted function call.";
448 	case WSAEBADF: return "File handle is not valid.";
449  	case WSAEACCES: return "Permission denied.";
450 	case WSAEFAULT: return "Bad address.";
451 	case WSAEINVAL: return "Invalid argument.";
452 	case WSAEMFILE: return "Too many open files.";
453 	case WSAEWOULDBLOCK: return "Resource temporarily unavailable.";
454 	case WSAEINPROGRESS: return "Operation now in progress.";
455 	case WSAEALREADY: return "Operation already in progress.";
456 	case WSAENOTSOCK: return "Socket operation on nonsocket.";
457 	case WSAEDESTADDRREQ: return "Destination address required.";
458 	case WSAEMSGSIZE: return "Message too long.";
459 	case WSAEPROTOTYPE: return "Protocol wrong type for socket.";
460 	case WSAENOPROTOOPT: return "Bad protocol option.";
461 	case WSAEPROTONOSUPPORT: return "Protocol not supported.";
462 	case WSAESOCKTNOSUPPORT: return "Socket type not supported.";
463 	case WSAEOPNOTSUPP: return "Operation not supported.";
464 	case WSAEPFNOSUPPORT: return "Protocol family not supported.";
465 	case WSAEAFNOSUPPORT: return "Address family not supported by protocol family.";
466 	case WSAEADDRINUSE: return "Address already in use.";
467 	case WSAEADDRNOTAVAIL: return "Cannot assign requested address.";
468 	case WSAENETDOWN: return "Network is down.";
469 	case WSAENETUNREACH: return "Network is unreachable.";
470 	case WSAENETRESET: return "Network dropped connection on reset.";
471 	case WSAECONNABORTED: return "Software caused connection abort.";
472 	case WSAECONNRESET: return "Connection reset by peer.";
473 	case WSAENOBUFS: return "No buffer space available.";
474 	case WSAEISCONN: return "Socket is already connected.";
475 	case WSAENOTCONN: return "Socket is not connected.";
476 	case WSAESHUTDOWN: return "Cannot send after socket shutdown.";
477 	case WSAETOOMANYREFS: return "Too many references.";
478 	case WSAETIMEDOUT: return "Connection timed out.";
479 	case WSAECONNREFUSED: return "Connection refused.";
480 	case WSAELOOP: return "Cannot translate name.";
481 	case WSAENAMETOOLONG: return "Name too long.";
482 	case WSAEHOSTDOWN: return "Host is down.";
483 	case WSAEHOSTUNREACH: return "No route to host.";
484 	case WSAENOTEMPTY: return "Directory not empty.";
485 	case WSAEPROCLIM: return "Too many processes.";
486 	case WSAEUSERS: return "User quota exceeded.";
487 	case WSAEDQUOT: return "Disk quota exceeded.";
488 	case WSAESTALE: return "Stale file handle reference.";
489 	case WSAEREMOTE: return "Item is remote.";
490 	case WSASYSNOTREADY: return "Network subsystem is unavailable.";
491 	case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range.";
492 	case WSANOTINITIALISED: return "Successful WSAStartup not yet performed.";
493 	case WSAEDISCON: return "Graceful shutdown in progress.";
494 	case WSAENOMORE: return "No more results.";
495 	case WSAECANCELLED: return "Call has been canceled.";
496 	case WSAEINVALIDPROCTABLE: return "Procedure call table is invalid.";
497 	case WSAEINVALIDPROVIDER: return "Service provider is invalid.";
498 	case WSAEPROVIDERFAILEDINIT: return "Service provider failed to initialize.";
499 	case WSASYSCALLFAILURE: return "System call failure.";
500 	case WSASERVICE_NOT_FOUND: return "Service not found.";
501 	case WSATYPE_NOT_FOUND: return "Class type not found.";
502 	case WSA_E_NO_MORE: return "No more results.";
503 	case WSA_E_CANCELLED: return "Call was canceled.";
504 	case WSAEREFUSED: return "Database query was refused.";
505 	case WSAHOST_NOT_FOUND: return "Host not found.";
506 	case WSATRY_AGAIN: return "Nonauthoritative host not found.";
507 	case WSANO_RECOVERY: return "This is a nonrecoverable error.";
508 	case WSANO_DATA: return "Valid name, no data record of requested type.";
509 	case WSA_QOS_RECEIVERS: return "QOS receivers.";
510 	case WSA_QOS_SENDERS: return "QOS senders.";
511 	case WSA_QOS_NO_SENDERS: return "No QOS senders.";
512 	case WSA_QOS_NO_RECEIVERS: return "QOS no receivers.";
513 	case WSA_QOS_REQUEST_CONFIRMED: return "QOS request confirmed.";
514 	case WSA_QOS_ADMISSION_FAILURE: return "QOS admission error.";
515 	case WSA_QOS_POLICY_FAILURE: return "QOS policy failure.";
516 	case WSA_QOS_BAD_STYLE: return "QOS bad style.";
517 	case WSA_QOS_BAD_OBJECT: return "QOS bad object.";
518 	case WSA_QOS_TRAFFIC_CTRL_ERROR: return "QOS traffic control error.";
519 	case WSA_QOS_GENERIC_ERROR: return "QOS generic error.";
520 	case WSA_QOS_ESERVICETYPE: return "QOS service type error.";
521 	case WSA_QOS_EFLOWSPEC: return "QOS flowspec error.";
522 	case WSA_QOS_EPROVSPECBUF: return "Invalid QOS provider buffer.";
523 	case WSA_QOS_EFILTERSTYLE: return "Invalid QOS filter style.";
524 	case WSA_QOS_EFILTERTYPE: return "Invalid QOS filter type.";
525 	case WSA_QOS_EFILTERCOUNT: return "Incorrect QOS filter count.";
526 	case WSA_QOS_EOBJLENGTH: return "Invalid QOS object length.";
527 	case WSA_QOS_EFLOWCOUNT: return "Incorrect QOS flow count.";
528 	/*case WSA_QOS_EUNKOWNPSOBJ: return "Unrecognized QOS object.";*/
529 	case WSA_QOS_EPOLICYOBJ: return "Invalid QOS policy object.";
530 	case WSA_QOS_EFLOWDESC: return "Invalid QOS flow descriptor.";
531 	case WSA_QOS_EPSFLOWSPEC: return "Invalid QOS provider-specific flowspec.";
532 	case WSA_QOS_EPSFILTERSPEC: return "Invalid QOS provider-specific filterspec.";
533 	case WSA_QOS_ESDMODEOBJ: return "Invalid QOS shape discard mode object.";
534 	case WSA_QOS_ESHAPERATEOBJ: return "Invalid QOS shaping rate object.";
535 	case WSA_QOS_RESERVED_PETYPE: return "Reserved policy QOS element type.";
536 	default:
537 		snprintf(unknown, sizeof(unknown),
538 			"unknown WSA error code %d", (int)err);
539 		return unknown;
540 	}
541 }
542 #endif /* USE_WINSOCK */
543