log.c revision 269257
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 "ldns/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 */
64enum verbosity_value verbosity = 0;
65/** the file logged to. */
66static FILE* logfile = 0;
67/** if key has been created */
68static int key_created = 0;
69/** pthread key for thread ids in logfile */
70static ub_thread_key_t logkey;
71/** the identity of this executable/process */
72static const char* ident="unbound";
73#if defined(HAVE_SYSLOG_H) || defined(UB_ON_WINDOWS)
74/** are we using syslog(3) to log to */
75static int logging_to_syslog = 0;
76#endif /* HAVE_SYSLOG_H */
77/** time to print in log, if NULL, use time(2) */
78static time_t* log_now = NULL;
79/** print time in UTC or in secondsfrom1970 */
80static int log_time_asc = 0;
81
82void
83log_init(const char* filename, int use_syslog, const char* chrootdir)
84{
85	FILE *f;
86	if(!key_created) {
87		key_created = 1;
88		ub_thread_key_create(&logkey, NULL);
89	}
90	if(logfile
91#if defined(HAVE_SYSLOG_H) || defined(UB_ON_WINDOWS)
92	|| logging_to_syslog
93#endif
94	)
95	verbose(VERB_QUERY, "switching log to %s",
96		use_syslog?"syslog":(filename&&filename[0]?filename:"stderr"));
97	if(logfile && logfile != stderr)
98		fclose(logfile);
99#ifdef HAVE_SYSLOG_H
100	if(logging_to_syslog) {
101		closelog();
102		logging_to_syslog = 0;
103	}
104	if(use_syslog) {
105		/* do not delay opening until first write, because we may
106		 * chroot and no longer be able to access dev/log and so on */
107		openlog(ident, LOG_NDELAY, LOG_DAEMON);
108		logging_to_syslog = 1;
109		return;
110	}
111#elif defined(UB_ON_WINDOWS)
112	if(logging_to_syslog) {
113		logging_to_syslog = 0;
114	}
115	if(use_syslog) {
116		logging_to_syslog = 1;
117		return;
118	}
119#endif /* HAVE_SYSLOG_H */
120	if(!filename || !filename[0]) {
121		logfile = stderr;
122		return;
123	}
124	/* open the file for logging */
125	if(chrootdir && chrootdir[0] && strncmp(filename, chrootdir,
126		strlen(chrootdir)) == 0)
127		filename += strlen(chrootdir);
128	f = fopen(filename, "a");
129	if(!f) {
130		log_err("Could not open logfile %s: %s", filename,
131			strerror(errno));
132		return;
133	}
134#ifndef UB_ON_WINDOWS
135	/* line buffering does not work on windows */
136	setvbuf(f, NULL, (int)_IOLBF, 0);
137#endif
138	logfile = f;
139}
140
141void log_file(FILE *f)
142{
143	logfile = f;
144}
145
146void log_thread_set(int* num)
147{
148	ub_thread_key_set(logkey, num);
149}
150
151void log_ident_set(const char* id)
152{
153	ident = id;
154}
155
156void log_set_time(time_t* t)
157{
158	log_now = t;
159}
160
161void log_set_time_asc(int use_asc)
162{
163	log_time_asc = use_asc;
164}
165
166void
167log_vmsg(int pri, const char* type,
168	const char *format, va_list args)
169{
170	char message[MAXSYSLOGMSGLEN];
171	unsigned int* tid = (unsigned int*)ub_thread_key_get(logkey);
172	time_t now;
173#if defined(HAVE_STRFTIME) && defined(HAVE_LOCALTIME_R)
174	char tmbuf[32];
175	struct tm tm;
176#elif defined(UB_ON_WINDOWS)
177	char tmbuf[128], dtbuf[128];
178#endif
179	(void)pri;
180	vsnprintf(message, sizeof(message), format, args);
181#ifdef HAVE_SYSLOG_H
182	if(logging_to_syslog) {
183		syslog(pri, "[%d:%x] %s: %s",
184			(int)getpid(), tid?*tid:0, type, message);
185		return;
186	}
187#elif defined(UB_ON_WINDOWS)
188	if(logging_to_syslog) {
189		char m[32768];
190		HANDLE* s;
191		LPCTSTR str = m;
192		DWORD tp = MSG_GENERIC_ERR;
193		WORD wt = EVENTLOG_ERROR_TYPE;
194		if(strcmp(type, "info") == 0) {
195			tp=MSG_GENERIC_INFO;
196			wt=EVENTLOG_INFORMATION_TYPE;
197		} else if(strcmp(type, "warning") == 0) {
198			tp=MSG_GENERIC_WARN;
199			wt=EVENTLOG_WARNING_TYPE;
200		} else if(strcmp(type, "notice") == 0
201			|| strcmp(type, "debug") == 0) {
202			tp=MSG_GENERIC_SUCCESS;
203			wt=EVENTLOG_SUCCESS;
204		}
205		snprintf(m, sizeof(m), "[%s:%x] %s: %s",
206			ident, tid?*tid:0, type, message);
207		s = RegisterEventSource(NULL, SERVICE_NAME);
208		if(!s) return;
209		ReportEvent(s, wt, 0, tp, NULL, 1, 0, &str, NULL);
210		DeregisterEventSource(s);
211		return;
212	}
213#endif /* HAVE_SYSLOG_H */
214	if(!logfile) return;
215	if(log_now)
216		now = (time_t)*log_now;
217	else	now = (time_t)time(NULL);
218#if defined(HAVE_STRFTIME) && defined(HAVE_LOCALTIME_R)
219	if(log_time_asc && strftime(tmbuf, sizeof(tmbuf), "%b %d %H:%M:%S",
220		localtime_r(&now, &tm))%(sizeof(tmbuf)) != 0) {
221		/* %sizeof buf!=0 because old strftime returned max on error */
222		fprintf(logfile, "%s %s[%d:%x] %s: %s\n", tmbuf,
223			ident, (int)getpid(), tid?*tid:0, type, message);
224	} else
225#elif defined(UB_ON_WINDOWS)
226	if(log_time_asc && GetTimeFormat(LOCALE_USER_DEFAULT, 0, NULL, NULL,
227		tmbuf, sizeof(tmbuf)) && GetDateFormat(LOCALE_USER_DEFAULT, 0,
228		NULL, NULL, dtbuf, sizeof(dtbuf))) {
229		fprintf(logfile, "%s %s %s[%d:%x] %s: %s\n", dtbuf, tmbuf,
230			ident, (int)getpid(), tid?*tid:0, type, message);
231	} else
232#endif
233	fprintf(logfile, "[" ARG_LL "d] %s[%d:%x] %s: %s\n", (long long)now,
234		ident, (int)getpid(), tid?*tid:0, type, message);
235#ifdef UB_ON_WINDOWS
236	/* line buffering does not work on windows */
237	fflush(logfile);
238#endif
239}
240
241/**
242 * implementation of log_info
243 * @param format: format string printf-style.
244 */
245void
246log_info(const char *format, ...)
247{
248        va_list args;
249	va_start(args, format);
250	log_vmsg(LOG_INFO, "info", format, args);
251	va_end(args);
252}
253
254/**
255 * implementation of log_err
256 * @param format: format string printf-style.
257 */
258void
259log_err(const char *format, ...)
260{
261        va_list args;
262	va_start(args, format);
263	log_vmsg(LOG_ERR, "error", format, args);
264	va_end(args);
265}
266
267/**
268 * implementation of log_warn
269 * @param format: format string printf-style.
270 */
271void
272log_warn(const char *format, ...)
273{
274        va_list args;
275	va_start(args, format);
276	log_vmsg(LOG_WARNING, "warning", format, args);
277	va_end(args);
278}
279
280/**
281 * implementation of fatal_exit
282 * @param format: format string printf-style.
283 */
284void
285fatal_exit(const char *format, ...)
286{
287        va_list args;
288	va_start(args, format);
289	log_vmsg(LOG_CRIT, "fatal error", format, args);
290	va_end(args);
291	exit(1);
292}
293
294/**
295 * implementation of verbose
296 * @param level: verbose level for the message.
297 * @param format: format string printf-style.
298 */
299void
300verbose(enum verbosity_value level, const char* format, ...)
301{
302        va_list args;
303	va_start(args, format);
304	if(verbosity >= level) {
305		if(level == VERB_OPS)
306			log_vmsg(LOG_NOTICE, "notice", format, args);
307		else if(level == VERB_DETAIL)
308			log_vmsg(LOG_INFO, "info", format, args);
309		else	log_vmsg(LOG_DEBUG, "debug", format, args);
310	}
311	va_end(args);
312}
313
314/** log hex data */
315static void
316log_hex_f(enum verbosity_value v, const char* msg, void* data, size_t length)
317{
318	size_t i, j;
319	uint8_t* data8 = (uint8_t*)data;
320	const char* hexchar = "0123456789ABCDEF";
321	char buf[1024+1]; /* alloc blocksize hex chars + \0 */
322	const size_t blocksize = 512;
323	size_t len;
324
325	if(length == 0) {
326		verbose(v, "%s[%u]", msg, (unsigned)length);
327		return;
328	}
329
330	for(i=0; i<length; i+=blocksize/2) {
331		len = blocksize/2;
332		if(length - i < blocksize/2)
333			len = length - i;
334		for(j=0; j<len; j++) {
335			buf[j*2] = hexchar[ data8[i+j] >> 4 ];
336			buf[j*2 + 1] = hexchar[ data8[i+j] & 0xF ];
337		}
338		buf[len*2] = 0;
339		verbose(v, "%s[%u:%u] %.*s", msg, (unsigned)length,
340			(unsigned)i, (int)len*2, buf);
341	}
342}
343
344void
345log_hex(const char* msg, void* data, size_t length)
346{
347	log_hex_f(verbosity, msg, data, length);
348}
349
350void log_buf(enum verbosity_value level, const char* msg, sldns_buffer* buf)
351{
352	if(verbosity < level)
353		return;
354	log_hex_f(level, msg, sldns_buffer_begin(buf), sldns_buffer_limit(buf));
355}
356
357#ifdef USE_WINSOCK
358char* wsa_strerror(DWORD err)
359{
360	static char unknown[32];
361
362	switch(err) {
363	case WSA_INVALID_HANDLE: return "Specified event object handle is invalid.";
364	case WSA_NOT_ENOUGH_MEMORY: return "Insufficient memory available.";
365	case WSA_INVALID_PARAMETER: return "One or more parameters are invalid.";
366	case WSA_OPERATION_ABORTED: return "Overlapped operation aborted.";
367	case WSA_IO_INCOMPLETE: return "Overlapped I/O event object not in signaled state.";
368	case WSA_IO_PENDING: return "Overlapped operations will complete later.";
369	case WSAEINTR: return "Interrupted function call.";
370	case WSAEBADF: return "File handle is not valid.";
371 	case WSAEACCES: return "Permission denied.";
372	case WSAEFAULT: return "Bad address.";
373	case WSAEINVAL: return "Invalid argument.";
374	case WSAEMFILE: return "Too many open files.";
375	case WSAEWOULDBLOCK: return "Resource temporarily unavailable.";
376	case WSAEINPROGRESS: return "Operation now in progress.";
377	case WSAEALREADY: return "Operation already in progress.";
378	case WSAENOTSOCK: return "Socket operation on nonsocket.";
379	case WSAEDESTADDRREQ: return "Destination address required.";
380	case WSAEMSGSIZE: return "Message too long.";
381	case WSAEPROTOTYPE: return "Protocol wrong type for socket.";
382	case WSAENOPROTOOPT: return "Bad protocol option.";
383	case WSAEPROTONOSUPPORT: return "Protocol not supported.";
384	case WSAESOCKTNOSUPPORT: return "Socket type not supported.";
385	case WSAEOPNOTSUPP: return "Operation not supported.";
386	case WSAEPFNOSUPPORT: return "Protocol family not supported.";
387	case WSAEAFNOSUPPORT: return "Address family not supported by protocol family.";
388	case WSAEADDRINUSE: return "Address already in use.";
389	case WSAEADDRNOTAVAIL: return "Cannot assign requested address.";
390	case WSAENETDOWN: return "Network is down.";
391	case WSAENETUNREACH: return "Network is unreachable.";
392	case WSAENETRESET: return "Network dropped connection on reset.";
393	case WSAECONNABORTED: return "Software caused connection abort.";
394	case WSAECONNRESET: return "Connection reset by peer.";
395	case WSAENOBUFS: return "No buffer space available.";
396	case WSAEISCONN: return "Socket is already connected.";
397	case WSAENOTCONN: return "Socket is not connected.";
398	case WSAESHUTDOWN: return "Cannot send after socket shutdown.";
399	case WSAETOOMANYREFS: return "Too many references.";
400	case WSAETIMEDOUT: return "Connection timed out.";
401	case WSAECONNREFUSED: return "Connection refused.";
402	case WSAELOOP: return "Cannot translate name.";
403	case WSAENAMETOOLONG: return "Name too long.";
404	case WSAEHOSTDOWN: return "Host is down.";
405	case WSAEHOSTUNREACH: return "No route to host.";
406	case WSAENOTEMPTY: return "Directory not empty.";
407	case WSAEPROCLIM: return "Too many processes.";
408	case WSAEUSERS: return "User quota exceeded.";
409	case WSAEDQUOT: return "Disk quota exceeded.";
410	case WSAESTALE: return "Stale file handle reference.";
411	case WSAEREMOTE: return "Item is remote.";
412	case WSASYSNOTREADY: return "Network subsystem is unavailable.";
413	case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range.";
414	case WSANOTINITIALISED: return "Successful WSAStartup not yet performed.";
415	case WSAEDISCON: return "Graceful shutdown in progress.";
416	case WSAENOMORE: return "No more results.";
417	case WSAECANCELLED: return "Call has been canceled.";
418	case WSAEINVALIDPROCTABLE: return "Procedure call table is invalid.";
419	case WSAEINVALIDPROVIDER: return "Service provider is invalid.";
420	case WSAEPROVIDERFAILEDINIT: return "Service provider failed to initialize.";
421	case WSASYSCALLFAILURE: return "System call failure.";
422	case WSASERVICE_NOT_FOUND: return "Service not found.";
423	case WSATYPE_NOT_FOUND: return "Class type not found.";
424	case WSA_E_NO_MORE: return "No more results.";
425	case WSA_E_CANCELLED: return "Call was canceled.";
426	case WSAEREFUSED: return "Database query was refused.";
427	case WSAHOST_NOT_FOUND: return "Host not found.";
428	case WSATRY_AGAIN: return "Nonauthoritative host not found.";
429	case WSANO_RECOVERY: return "This is a nonrecoverable error.";
430	case WSANO_DATA: return "Valid name, no data record of requested type.";
431	case WSA_QOS_RECEIVERS: return "QOS receivers.";
432	case WSA_QOS_SENDERS: return "QOS senders.";
433	case WSA_QOS_NO_SENDERS: return "No QOS senders.";
434	case WSA_QOS_NO_RECEIVERS: return "QOS no receivers.";
435	case WSA_QOS_REQUEST_CONFIRMED: return "QOS request confirmed.";
436	case WSA_QOS_ADMISSION_FAILURE: return "QOS admission error.";
437	case WSA_QOS_POLICY_FAILURE: return "QOS policy failure.";
438	case WSA_QOS_BAD_STYLE: return "QOS bad style.";
439	case WSA_QOS_BAD_OBJECT: return "QOS bad object.";
440	case WSA_QOS_TRAFFIC_CTRL_ERROR: return "QOS traffic control error.";
441	case WSA_QOS_GENERIC_ERROR: return "QOS generic error.";
442	case WSA_QOS_ESERVICETYPE: return "QOS service type error.";
443	case WSA_QOS_EFLOWSPEC: return "QOS flowspec error.";
444	case WSA_QOS_EPROVSPECBUF: return "Invalid QOS provider buffer.";
445	case WSA_QOS_EFILTERSTYLE: return "Invalid QOS filter style.";
446	case WSA_QOS_EFILTERTYPE: return "Invalid QOS filter type.";
447	case WSA_QOS_EFILTERCOUNT: return "Incorrect QOS filter count.";
448	case WSA_QOS_EOBJLENGTH: return "Invalid QOS object length.";
449	case WSA_QOS_EFLOWCOUNT: return "Incorrect QOS flow count.";
450	/*case WSA_QOS_EUNKOWNPSOBJ: return "Unrecognized QOS object.";*/
451	case WSA_QOS_EPOLICYOBJ: return "Invalid QOS policy object.";
452	case WSA_QOS_EFLOWDESC: return "Invalid QOS flow descriptor.";
453	case WSA_QOS_EPSFLOWSPEC: return "Invalid QOS provider-specific flowspec.";
454	case WSA_QOS_EPSFILTERSPEC: return "Invalid QOS provider-specific filterspec.";
455	case WSA_QOS_ESDMODEOBJ: return "Invalid QOS shape discard mode object.";
456	case WSA_QOS_ESHAPERATEOBJ: return "Invalid QOS shaping rate object.";
457	case WSA_QOS_RESERVED_PETYPE: return "Reserved policy QOS element type.";
458	default:
459		snprintf(unknown, sizeof(unknown),
460			"unknown WSA error code %d", (int)err);
461		return unknown;
462	}
463}
464#endif /* USE_WINSOCK */
465