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