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