always compile before commit :-)
[Samba.git] / source / lib / debug.c
blob43f0ac1fec24636e84574b4dabcca30e7988dea9
1 /*
2 Unix SMB/Netbios implementation.
3 Version 1.9.
4 Samba utility functions
5 Copyright (C) Andrew Tridgell 1992-1998
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #include "includes.h"
24 /* -------------------------------------------------------------------------- **
25 * Defines...
27 * FORMAT_BUFR_MAX - Index of the last byte of the format buffer;
28 * format_bufr[FORMAT_BUFR_MAX] should always be reserved
29 * for a terminating nul byte.
32 #define FORMAT_BUFR_MAX ( sizeof( format_bufr ) - 1 )
34 /* -------------------------------------------------------------------------- **
35 * This module implements Samba's debugging utility.
37 * The syntax of a debugging log file is represented as:
39 * <debugfile> :== { <debugmsg> }
41 * <debugmsg> :== <debughdr> '\n' <debugtext>
43 * <debughdr> :== '[' TIME ',' LEVEL ']' [ [FILENAME ':'] [FUNCTION '()'] ]
45 * <debugtext> :== { <debugline> }
47 * <debugline> :== TEXT '\n'
49 * TEXT is a string of characters excluding the newline character.
50 * LEVEL is the DEBUG level of the message (an integer in the range 0..10).
51 * TIME is a timestamp.
52 * FILENAME is the name of the file from which the debug message was generated.
53 * FUNCTION is the function from which the debug message was generated.
55 * Basically, what that all means is:
57 * - A debugging log file is made up of debug messages.
59 * - Each debug message is made up of a header and text. The header is
60 * separated from the text by a newline.
62 * - The header begins with the timestamp and debug level of the message
63 * enclosed in brackets. The filename and function from which the
64 * message was generated may follow. The filename is terminated by a
65 * colon, and the function name is terminated by parenthesis.
67 * - The message text is made up of zero or more lines, each terminated by
68 * a newline.
71 /* -------------------------------------------------------------------------- **
72 * External variables.
74 * dbf - Global debug file handle.
75 * debugf - Debug file name.
76 * append_log - If True, then the output file will be opened in append
77 * mode.
78 * DEBUGLEVEL - System-wide debug message limit. Messages with message-
79 * levels higher than DEBUGLEVEL will not be processed.
82 FILE *dbf = NULL;
83 pstring debugf = "";
84 BOOL append_log = False;
86 int DEBUGLEVEL_CLASS[DBGC_LAST];
87 int DEBUGLEVEL = DEBUGLEVEL_CLASS;
90 /* -------------------------------------------------------------------------- **
91 * Internal variables.
93 * stdout_logging - Default False, if set to True then dbf will be set to
94 * stdout and debug output will go to dbf only, and not
95 * to syslog. Set in setup_logging() and read in Debug1().
97 * debug_count - Number of debug messages that have been output.
98 * Used to check log size.
100 * syslog_level - Internal copy of the message debug level. Written by
101 * dbghdr() and read by Debug1().
103 * format_bufr - Used to format debug messages. The dbgtext() function
104 * prints debug messages to a string, and then passes the
105 * string to format_debug_text(), which uses format_bufr
106 * to build the formatted output.
108 * format_pos - Marks the first free byte of the format_bufr.
111 * log_overflow - When this variable is True, never attempt to check the
112 * size of the log. This is a hack, so that we can write
113 * a message using DEBUG, from open_logs() when we
114 * are unable to open a new log file for some reason.
117 static BOOL stdout_logging = False;
118 static int debug_count = 0;
119 #ifdef WITH_SYSLOG
120 static int syslog_level = 0;
121 #endif
122 static pstring format_bufr = { '\0' };
123 static size_t format_pos = 0;
124 static BOOL log_overflow = False;
127 * Define all the debug class selection names here. Names *MUST NOT* contain
128 * white space. There must be one name for each DBGC_<class name>, and they
129 * must be in the table in the order of DBGC_<class name>..
131 char *classname_table[] = {
132 "all", /* DBGC_ALL; index references traditional DEBUGLEVEL */
133 "tdb", /* DBGC_TDB */
134 "printdrivers", /* DBGC_PRINTDRIVERS */
135 "lanman", /* DBGC_LANMAN */
139 /* -------------------------------------------------------------------------- **
140 * Functions...
143 /****************************************************************************
144 utility access to debug class names's
145 ****************************************************************************/
146 char* debug_classname_from_index(int ndx)
148 return classname_table[ndx];
151 /****************************************************************************
152 utility to translate names to debug class index's
153 ****************************************************************************/
154 int debug_lookup_classname(char* classname)
156 int i;
158 if (!classname) return -1;
160 for (i=0; i<DBGC_LAST; i++) {
161 if (strcmp(classname, classname_table[i])==0)
162 return i;
164 return -1;
167 /****************************************************************************
168 parse the debug levels from smbcontrol. Example debug level parameter:
169 printdrivers:7
170 ****************************************************************************/
171 BOOL debug_parse_params(char **params, int *debuglevel_class)
173 int i, ndx;
174 char *class_name;
175 char *class_level;
177 /* Set the new debug level array to the current DEBUGLEVEL array */
178 memcpy(debuglevel_class, DEBUGLEVEL_CLASS, sizeof(DEBUGLEVEL_CLASS));
180 /* Allow DBGC_ALL to be specifies w/o requiring its class name e.g."10"
181 * v.s. "all:10", this is the traditional way to set DEBUGLEVEL
183 if (isdigit((int)params[0][0])) {
184 debuglevel_class[DBGC_ALL] = atoi(params[0]);
185 i = 1; /* start processing at the next params */
187 else
188 i = 0; /* DBGC_ALL not specified OR calss name was included */
190 /* Fill in new debug class levels */
191 for (; i < DBGC_LAST && params[i]; i++) {
192 if ((class_name=strtok(params[i],":")) &&
193 (class_level=strtok(NULL, "\0")) &&
194 ((ndx = debug_lookup_classname(class_name)) != -1)) {
195 debuglevel_class[ndx] = atoi(class_level);
196 } else {
197 DEBUG(0,("debug_parse_params: unrecognized debug class name or format [%s]\n", params[i]));
198 return False;
202 return True;
205 /****************************************************************************
206 parse the debug levels from smb.conf. Example debug level string:
207 3 tdb:5 printdrivers:7
208 Note: the 1st param has no "name:" preceeding it.
209 ****************************************************************************/
210 BOOL debug_parse_levels(char *params_str)
212 int i;
213 char *params[DBGC_LAST];
214 int debuglevel_class[DBGC_LAST];
216 ZERO_ARRAY(params);
217 ZERO_ARRAY(debuglevel_class);
219 if ((params[0]=strtok(params_str," ,"))) {
220 for (i=1; i<DBGC_LAST;i++) {
221 if ((params[i]=strtok(NULL," ,"))==NULL)
222 break;
225 else
226 return False;
228 if (debug_parse_params(params, debuglevel_class)) {
229 debug_message(0, getpid(), (void*)debuglevel_class, sizeof(debuglevel_class));
230 return True;
231 } else
232 return False;
235 /****************************************************************************
236 receive a "set debug level" message
237 ****************************************************************************/
238 void debug_message(int msg_type, pid_t src, void *buf, size_t len)
240 int i;
242 /* Set the new DEBUGLEVEL_CLASS array from the pased array */
243 memcpy(DEBUGLEVEL_CLASS, buf, sizeof(DEBUGLEVEL_CLASS));
245 DEBUG(1,("INFO: Debug class %s level = %d (pid %u from pid %u)\n",
246 classname_table[DBGC_ALL],
247 DEBUGLEVEL_CLASS[DBGC_ALL], (unsigned int)getpid(), (unsigned int)src));
249 for (i=1; i<DBGC_LAST; i++) {
250 if (DEBUGLEVEL_CLASS[i])
251 DEBUGADD(1,("INFO: Debug class %s level = %d\n",
252 classname_table[i], DEBUGLEVEL_CLASS[i]));
257 /****************************************************************************
258 send a "set debug level" message
259 ****************************************************************************/
260 void debug_message_send(pid_t pid, int level)
262 message_send_pid(pid, MSG_DEBUG, &level, sizeof(int), False);
266 /* ************************************************************************** **
267 * get ready for syslog stuff
268 * ************************************************************************** **
270 void setup_logging(char *pname, BOOL interactive)
272 message_register(MSG_DEBUG, debug_message);
274 /* reset to allow multiple setup calls, going from interactive to
275 non-interactive */
276 stdout_logging = False;
277 dbf = NULL;
279 if (interactive) {
280 stdout_logging = True;
281 dbf = stdout;
283 #ifdef WITH_SYSLOG
284 else {
285 char *p = strrchr( pname,'/' );
286 if (p)
287 pname = p + 1;
288 #ifdef LOG_DAEMON
289 openlog( pname, LOG_PID, SYSLOG_FACILITY );
290 #else /* for old systems that have no facility codes. */
291 openlog( pname, LOG_PID );
292 #endif
294 #endif
295 } /* setup_logging */
297 /* ************************************************************************** **
298 * reopen the log files
299 * note that we now do this unconditionally
300 * We attempt to open the new debug fp before closing the old. This means
301 * if we run out of fd's we just keep using the old fd rather than aborting.
302 * Fix from dgibson@linuxcare.com.
303 * ************************************************************************** **
306 BOOL reopen_logs( void )
308 pstring fname;
309 mode_t oldumask;
310 FILE *new_dbf = NULL;
311 BOOL ret = True;
313 if (stdout_logging)
314 return True;
316 oldumask = umask( 022 );
318 pstrcpy(fname, debugf );
319 if (lp_loaded() && (*lp_logfile()))
320 pstrcpy(fname, lp_logfile());
322 pstrcpy(debugf, fname);
324 if (append_log)
325 new_dbf = sys_fopen( debugf, "a" );
326 else
327 new_dbf = sys_fopen( debugf, "w" );
329 if (!new_dbf) {
330 log_overflow = True;
331 DEBUG(0, ("Unable to open new log file %s: %s\n", debugf, strerror(errno)));
332 log_overflow = False;
333 fflush(dbf);
334 ret = False;
335 } else {
336 setbuf(new_dbf, NULL);
337 if (dbf)
338 (void) fclose(dbf);
339 dbf = new_dbf;
342 /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
343 * to fix problem where smbd's that generate less
344 * than 100 messages keep growing the log.
346 force_check_log_size();
347 (void)umask(oldumask);
349 return ret;
352 /* ************************************************************************** **
353 * Force a check of the log size.
354 * ************************************************************************** **
356 void force_check_log_size( void )
358 debug_count = 100;
361 /***************************************************************************
362 Check to see if there is any need to check if the logfile has grown too big.
363 **************************************************************************/
365 BOOL need_to_check_log_size( void )
367 int maxlog;
369 if( debug_count++ < 100 )
370 return( False );
372 maxlog = lp_max_log_size() * 1024;
373 if( !dbf || maxlog <= 0 ) {
374 debug_count = 0;
375 return(False);
377 return( True );
380 /* ************************************************************************** **
381 * Check to see if the log has grown to be too big.
382 * ************************************************************************** **
385 void check_log_size( void )
387 int maxlog;
388 SMB_STRUCT_STAT st;
391 * We need to be root to check/change log-file, skip this and let the main
392 * loop check do a new check as root.
395 if( geteuid() != 0 )
396 return;
398 if(log_overflow || !need_to_check_log_size() )
399 return;
401 maxlog = lp_max_log_size() * 1024;
403 if( sys_fstat( fileno( dbf ), &st ) == 0 && st.st_size > maxlog ) {
404 (void)reopen_logs();
405 if( dbf && get_file_size( debugf ) > maxlog ) {
406 pstring name;
408 slprintf( name, sizeof(name)-1, "%s.old", debugf );
409 (void)rename( debugf, name );
411 if (!reopen_logs()) {
412 /* We failed to reopen a log - continue using the old name. */
413 (void)rename(name, debugf);
419 * Here's where we need to panic if dbf == NULL..
422 if(dbf == NULL) {
423 /* This code should only be reached in very strange
424 circumstances. If we merely fail to open the new log we
425 should stick with the old one. ergo this should only be
426 reached when opening the logs for the first time: at
427 startup or when the log level is increased from zero.
428 -dwg 6 June 2000
430 dbf = sys_fopen( "/dev/console", "w" );
431 if(dbf) {
432 DEBUG(0,("check_log_size: open of debug file %s failed - using console.\n",
433 debugf ));
434 } else {
436 * We cannot continue without a debug file handle.
438 abort();
441 debug_count = 0;
442 } /* check_log_size */
444 /* ************************************************************************** **
445 * Write an debug message on the debugfile.
446 * This is called by dbghdr() and format_debug_text().
447 * ************************************************************************** **
449 int Debug1( char *format_str, ... )
451 va_list ap;
452 int old_errno = errno;
454 if( stdout_logging )
456 va_start( ap, format_str );
457 if(dbf)
458 (void)vfprintf( dbf, format_str, ap );
459 va_end( ap );
460 errno = old_errno;
461 return( 0 );
464 #ifdef WITH_SYSLOG
465 if( !lp_syslog_only() )
466 #endif
468 if( !dbf )
470 mode_t oldumask = umask( 022 );
472 if( append_log )
473 dbf = sys_fopen( debugf, "a" );
474 else
475 dbf = sys_fopen( debugf, "w" );
476 (void)umask( oldumask );
477 if( dbf )
479 setbuf( dbf, NULL );
481 else
483 errno = old_errno;
484 return(0);
489 #ifdef WITH_SYSLOG
490 if( syslog_level < lp_syslog() )
492 /* map debug levels to syslog() priorities
493 * note that not all DEBUG(0, ...) calls are
494 * necessarily errors
496 static int priority_map[] = {
497 LOG_ERR, /* 0 */
498 LOG_WARNING, /* 1 */
499 LOG_NOTICE, /* 2 */
500 LOG_INFO, /* 3 */
502 int priority;
503 pstring msgbuf;
505 if( syslog_level >= ( sizeof(priority_map) / sizeof(priority_map[0]) )
506 || syslog_level < 0)
507 priority = LOG_DEBUG;
508 else
509 priority = priority_map[syslog_level];
511 va_start( ap, format_str );
512 vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
513 va_end( ap );
515 msgbuf[255] = '\0';
516 syslog( priority, "%s", msgbuf );
518 #endif
520 check_log_size();
522 #ifdef WITH_SYSLOG
523 if( !lp_syslog_only() )
524 #endif
526 va_start( ap, format_str );
527 if(dbf)
528 (void)vfprintf( dbf, format_str, ap );
529 va_end( ap );
530 if(dbf)
531 (void)fflush( dbf );
534 errno = old_errno;
536 return( 0 );
537 } /* Debug1 */
540 /* ************************************************************************** **
541 * Print the buffer content via Debug1(), then reset the buffer.
543 * Input: none
544 * Output: none
546 * ************************************************************************** **
548 static void bufr_print( void )
550 format_bufr[format_pos] = '\0';
551 (void)Debug1( "%s", format_bufr );
552 format_pos = 0;
553 } /* bufr_print */
555 /* ************************************************************************** **
556 * Format the debug message text.
558 * Input: msg - Text to be added to the "current" debug message text.
560 * Output: none.
562 * Notes: The purpose of this is two-fold. First, each call to syslog()
563 * (used by Debug1(), see above) generates a new line of syslog
564 * output. This is fixed by storing the partial lines until the
565 * newline character is encountered. Second, printing the debug
566 * message lines when a newline is encountered allows us to add
567 * spaces, thus indenting the body of the message and making it
568 * more readable.
570 * ************************************************************************** **
572 static void format_debug_text( char *msg )
574 size_t i;
575 BOOL timestamp = (!stdout_logging && (lp_timestamp_logs() ||
576 !(lp_loaded())));
578 for( i = 0; msg[i]; i++ )
580 /* Indent two spaces at each new line. */
581 if(timestamp && 0 == format_pos)
583 format_bufr[0] = format_bufr[1] = ' ';
584 format_pos = 2;
587 /* If there's room, copy the character to the format buffer. */
588 if( format_pos < FORMAT_BUFR_MAX )
589 format_bufr[format_pos++] = msg[i];
591 /* If a newline is encountered, print & restart. */
592 if( '\n' == msg[i] )
593 bufr_print();
595 /* If the buffer is full dump it out, reset it, and put out a line
596 * continuation indicator.
598 if( format_pos >= FORMAT_BUFR_MAX )
600 bufr_print();
601 (void)Debug1( " +>\n" );
605 /* Just to be safe... */
606 format_bufr[format_pos] = '\0';
607 } /* format_debug_text */
609 /* ************************************************************************** **
610 * Flush debug output, including the format buffer content.
612 * Input: none
613 * Output: none
615 * ************************************************************************** **
617 void dbgflush( void )
619 bufr_print();
620 if(dbf)
621 (void)fflush( dbf );
622 } /* dbgflush */
624 /* ************************************************************************** **
625 * Print a Debug Header.
627 * Input: level - Debug level of the message (not the system-wide debug
628 * level.
629 * file - Pointer to a string containing the name of the file
630 * from which this function was called, or an empty string
631 * if the __FILE__ macro is not implemented.
632 * func - Pointer to a string containing the name of the function
633 * from which this function was called, or an empty string
634 * if the __FUNCTION__ macro is not implemented.
635 * line - line number of the call to dbghdr, assuming __LINE__
636 * works.
638 * Output: Always True. This makes it easy to fudge a call to dbghdr()
639 * in a macro, since the function can be called as part of a test.
640 * Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
642 * Notes: This function takes care of setting syslog_level.
644 * ************************************************************************** **
647 BOOL dbghdr( int level, char *file, char *func, int line )
649 /* Ensure we don't lose any real errno value. */
650 int old_errno = errno;
652 if( format_pos ) {
653 /* This is a fudge. If there is stuff sitting in the format_bufr, then
654 * the *right* thing to do is to call
655 * format_debug_text( "\n" );
656 * to write the remainder, and then proceed with the new header.
657 * Unfortunately, there are several places in the code at which
658 * the DEBUG() macro is used to build partial lines. That in mind,
659 * we'll work under the assumption that an incomplete line indicates
660 * that a new header is *not* desired.
662 return( True );
665 #ifdef WITH_SYSLOG
666 /* Set syslog_level. */
667 syslog_level = level;
668 #endif
670 /* Don't print a header if we're logging to stdout. */
671 if( stdout_logging )
672 return( True );
674 /* Print the header if timestamps are turned on. If parameters are
675 * not yet loaded, then default to timestamps on.
677 if( lp_timestamp_logs() || !(lp_loaded()) ) {
678 char header_str[200];
680 header_str[0] = '\0';
682 if( lp_debug_pid())
683 slprintf(header_str,sizeof(header_str)-1,", pid=%u",(unsigned int)sys_getpid());
685 if( lp_debug_uid()) {
686 size_t hs_len = strlen(header_str);
687 slprintf(header_str + hs_len,
688 sizeof(header_str) - 1 - hs_len,
689 ", effective(%u, %u), real(%u, %u)",
690 (unsigned int)geteuid(), (unsigned int)getegid(),
691 (unsigned int)getuid(), (unsigned int)getgid());
694 /* Print it all out at once to prevent split syslog output. */
695 (void)Debug1( "[%s, %d%s] %s:%s(%d)\n",
696 timestring(lp_debug_hires_timestamp()), level,
697 header_str, file, func, line );
700 errno = old_errno;
701 return( True );
704 /* ************************************************************************** **
705 * Add text to the body of the "current" debug message via the format buffer.
707 * Input: format_str - Format string, as used in printf(), et. al.
708 * ... - Variable argument list.
710 * ..or.. va_alist - Old style variable parameter list starting point.
712 * Output: Always True. See dbghdr() for more info, though this is not
713 * likely to be used in the same way.
715 * ************************************************************************** **
717 BOOL dbgtext( char *format_str, ... )
719 va_list ap;
720 pstring msgbuf;
722 va_start( ap, format_str );
723 vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
724 va_end( ap );
726 format_debug_text( msgbuf );
728 return( True );
729 } /* dbgtext */
732 /* ************************************************************************** */