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