preparing for release of alpha.0.8
[Samba.git] / source / lib / debug.c
blobab11d81a212c96c08a265ef1093113be66a09f06
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 * timestamp_log -
79 * DEBUGLEVEL - System-wide debug message limit. Messages with message-
80 * levels higher than DEBUGLEVEL will not be processed.
83 FILE *dbf = NULL;
84 pstring debugf = "";
85 BOOL append_log = False;
86 BOOL timestamp_log = True;
87 int DEBUGLEVEL = 1;
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 static BOOL stdout_logging = False;
112 static int debug_count = 0;
113 #ifdef WITH_SYSLOG
114 static int syslog_level = 0;
115 #endif
116 static pstring format_bufr = { '\0' };
117 static int format_pos = 0;
120 /* -------------------------------------------------------------------------- **
121 * Functions...
124 /* ************************************************************************** **
125 * tells us if interactive logging was requested
126 * ************************************************************************** **
128 BOOL dbg_interactive(void)
130 return stdout_logging;
133 #if defined(SIGUSR2) && !defined(MEM_MAN)
134 /* ************************************************************************** **
135 * catch a sigusr2 - decrease the debug log level.
136 * ************************************************************************** **
138 void sig_usr2( int sig )
140 BlockSignals( True, SIGUSR2 );
142 DEBUGLEVEL--;
143 if( DEBUGLEVEL < 0 )
144 DEBUGLEVEL = 0;
146 DEBUG( 0, ( "Got SIGUSR2; set debug level to %d.\n", DEBUGLEVEL ) );
148 BlockSignals( False, SIGUSR2 );
149 CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
151 } /* sig_usr2 */
152 #endif /* SIGUSR2 */
154 #if defined(SIGUSR1) && !defined(MEM_MAN)
155 /* ************************************************************************** **
156 * catch a sigusr1 - increase the debug log level.
157 * ************************************************************************** **
159 void sig_usr1( int sig )
161 BlockSignals( True, SIGUSR1 );
163 DEBUGLEVEL++;
165 if( DEBUGLEVEL > 10 )
166 DEBUGLEVEL = 10;
168 DEBUG( 0, ( "Got SIGUSR1; set debug level to %d.\n", DEBUGLEVEL ) );
170 BlockSignals( False, SIGUSR1 );
171 CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
173 } /* sig_usr1 */
174 #endif /* SIGUSR1 */
177 /* ************************************************************************** **
178 * get ready for syslog stuff
179 * ************************************************************************** **
181 void setup_logging( char *pname, BOOL interactive )
183 if( interactive )
185 stdout_logging = True;
186 dbf = stdout;
188 #ifdef WITH_SYSLOG
189 else
191 char *p = strrchr( pname,'/' );
193 if( p )
194 pname = p + 1;
195 #ifdef LOG_DAEMON
196 openlog( pname, LOG_PID, SYSLOG_FACILITY );
197 #else /* for old systems that have no facility codes. */
198 openlog( pname, LOG_PID );
199 #endif
201 #endif
202 } /* setup_logging */
204 /* ************************************************************************** **
205 * reopen the log files
206 * ************************************************************************** **
208 void reopen_logs( void )
210 pstring fname;
212 if( DEBUGLEVEL > 0 )
214 pstrcpy( fname, debugf );
215 if( lp_loaded() && (*lp_logfile()) )
216 pstrcpy( fname, lp_logfile() );
218 if( !strcsequal( fname, debugf ) || !dbf || !file_exist( debugf, NULL ) )
220 mode_t oldumask = umask( 022 );
222 pstrcpy( debugf, fname );
223 if( dbf )
224 (void)fclose( dbf );
225 if( append_log )
226 dbf = sys_fopen( debugf, "a" );
227 else
228 dbf = sys_fopen( debugf, "w" );
229 /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
230 * to fix problem where smbd's that generate less
231 * than 100 messages keep growing the log.
233 force_check_log_size();
234 if( dbf )
235 setbuf( dbf, NULL );
236 (void)umask( oldumask );
239 else
241 if( dbf )
243 (void)fclose( dbf );
244 dbf = NULL;
247 } /* reopen_logs */
249 /* ************************************************************************** **
250 * Force a check of the log size.
251 * ************************************************************************** **
253 void force_check_log_size( void )
255 debug_count = 100;
256 } /* force_check_log_size */
258 /* ************************************************************************** **
259 * Check to see if the log has grown to be too big.
260 * ************************************************************************** **
262 static void check_log_size( void )
264 int maxlog;
265 SMB_STRUCT_STAT st;
267 if( debug_count++ < 100 || getuid() != 0 )
268 return;
270 maxlog = lp_max_log_size() * 1024;
271 if( !dbf || maxlog <= 0 )
272 return;
274 if( sys_fstat( fileno( dbf ), &st ) == 0 && st.st_size > maxlog )
276 (void)fclose( dbf );
277 dbf = NULL;
278 reopen_logs();
279 if( dbf && file_size( debugf ) > maxlog )
281 pstring name;
283 (void)fclose( dbf );
284 dbf = NULL;
285 slprintf( name, sizeof(name)-1, "%s.old", debugf );
286 (void)rename( debugf, name );
287 reopen_logs();
290 debug_count = 0;
291 } /* check_log_size */
293 /* ************************************************************************** **
294 * Write an debug message on the debugfile.
295 * This is called by dbghdr() and format_debug_text().
296 * ************************************************************************** **
298 #ifdef HAVE_STDARG_H
299 int Debug1( char *format_str, ... )
301 #else
302 int Debug1(va_alist)
303 va_dcl
305 char *format_str;
306 #endif
307 va_list ap;
308 int old_errno = errno;
310 if( stdout_logging )
312 #ifdef HAVE_STDARG_H
313 va_start( ap, format_str );
314 #else
315 va_start( ap );
316 format_str = va_arg( ap, char * );
317 #endif
318 (void)vfprintf( dbf, format_str, ap );
319 va_end( ap );
320 errno = old_errno;
321 return( 0 );
324 #ifdef WITH_SYSLOG
325 if( !lp_syslog_only() )
326 #endif
328 if( !dbf )
330 mode_t oldumask = umask( 022 );
332 if( append_log )
333 dbf = sys_fopen( debugf, "a" );
334 else
335 dbf = sys_fopen( debugf, "w" );
336 (void)umask( oldumask );
337 if( dbf )
339 setbuf( dbf, NULL );
341 else
343 errno = old_errno;
344 return(0);
349 #ifdef WITH_SYSLOG
350 if( syslog_level < lp_syslog() )
352 /* map debug levels to syslog() priorities
353 * note that not all DEBUG(0, ...) calls are
354 * necessarily errors
356 static int priority_map[] = {
357 LOG_ERR, /* 0 */
358 LOG_WARNING, /* 1 */
359 LOG_NOTICE, /* 2 */
360 LOG_INFO, /* 3 */
362 int priority;
363 pstring msgbuf;
365 if( syslog_level >= ( sizeof(priority_map) / sizeof(priority_map[0]) )
366 || syslog_level < 0)
367 priority = LOG_DEBUG;
368 else
369 priority = priority_map[syslog_level];
371 #ifdef HAVE_STDARG_H
372 va_start( ap, format_str );
373 #else
374 va_start( ap );
375 format_str = va_arg( ap, char * );
376 #endif
377 vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
378 va_end( ap );
380 msgbuf[255] = '\0';
381 syslog( priority, "%s", msgbuf );
383 #endif
385 #ifdef WITH_SYSLOG
386 if( !lp_syslog_only() )
387 #endif
389 #ifdef HAVE_STDARG_H
390 va_start( ap, format_str );
391 #else
392 va_start( ap );
393 format_str = va_arg( ap, char * );
394 #endif
395 (void)vfprintf( dbf, format_str, ap );
396 va_end( ap );
397 (void)fflush( dbf );
400 check_log_size();
402 errno = old_errno;
404 return( 0 );
405 } /* Debug1 */
408 /* ************************************************************************** **
409 * Print the buffer content via Debug1(), then reset the buffer.
411 * Input: none
412 * Output: none
414 * ************************************************************************** **
416 static void bufr_print( void )
418 format_bufr[format_pos] = '\0';
419 (void)Debug1( "%s", format_bufr );
420 format_pos = 0;
421 } /* bufr_print */
423 /* ************************************************************************** **
424 * Format the debug message text.
426 * Input: msg - Text to be added to the "current" debug message text.
428 * Output: none.
430 * Notes: The purpose of this is two-fold. First, each call to syslog()
431 * (used by Debug1(), see above) generates a new line of syslog
432 * output. This is fixed by storing the partial lines until the
433 * newline character is encountered. Second, printing the debug
434 * message lines when a newline is encountered allows us to add
435 * spaces, thus indenting the body of the message and making it
436 * more readable.
438 * ************************************************************************** **
440 static void format_debug_text( char *msg )
442 int i;
443 BOOL timestamp = (timestamp_log && !stdout_logging && (lp_timestamp_logs() ||
444 !(lp_loaded())));
446 for( i = 0; msg[i]; i++ )
448 /* Indent two spaces at each new line. */
449 if(timestamp && 0 == format_pos)
451 format_bufr[0] = format_bufr[1] = ' ';
452 format_pos = 2;
455 /* If there's room, copy the character to the format buffer. */
456 if( format_pos < FORMAT_BUFR_MAX )
457 format_bufr[format_pos++] = msg[i];
459 /* If a newline is encountered, print & restart. */
460 if( '\n' == msg[i] )
461 bufr_print();
463 /* If the buffer is full dump it out, reset it, and put out a line
464 * continuation indicator.
466 if( format_pos >= FORMAT_BUFR_MAX )
468 bufr_print();
469 (void)Debug1( " +>\n" );
473 /* Just to be safe... */
474 format_bufr[format_pos] = '\0';
475 } /* format_debug_text */
477 /* ************************************************************************** **
478 * Flush debug output, including the format buffer content.
480 * Input: none
481 * Output: none
483 * ************************************************************************** **
485 void dbgflush( void )
487 bufr_print();
488 (void)fflush( dbf );
489 } /* dbgflush */
491 /* ************************************************************************** **
492 * Print a Debug Header.
494 * Input: level - Debug level of the message (not the system-wide debug
495 * level.
496 * file - Pointer to a string containing the name of the file
497 * from which this function was called, or an empty string
498 * if the __FILE__ macro is not implemented.
499 * func - Pointer to a string containing the name of the function
500 * from which this function was called, or an empty string
501 * if the __FUNCTION__ macro is not implemented.
502 * line - line number of the call to dbghdr, assuming __LINE__
503 * works.
505 * Output: Always True. This makes it easy to fudge a call to dbghdr()
506 * in a macro, since the function can be called as part of a test.
507 * Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
509 * Notes: This function takes care of setting syslog_level.
511 * ************************************************************************** **
513 BOOL dbghdr( int level, char *file, char *func, int line )
515 if( format_pos )
517 /* This is a fudge. If there is stuff sitting in the format_bufr, then
518 * the *right* thing to do is to call
519 * format_debug_text( "\n" );
520 * to write the remainder, and then proceed with the new header.
521 * Unfortunately, there are several places in the code at which
522 * the DEBUG() macro is used to build partial lines. That in mind,
523 * we'll work under the assumption that an incomplete line indicates
524 * that a new header is *not* desired.
526 return( True );
529 #ifdef WITH_SYSLOG
530 /* Set syslog_level. */
531 syslog_level = level;
532 #endif
534 /* Don't print a header if we're logging to stdout. */
535 if( stdout_logging )
536 return( True );
538 /* Print the header if timestamps are turned on. If parameters are
539 * not yet loaded, then default to timestamps on.
541 if( timestamp_log && (lp_timestamp_logs() || !(lp_loaded()) ))
543 /* Print it all out at once to prevent split syslog output. */
544 (void)Debug1( "[%s, %d] %s:%s(%d)\n",
545 timestring(), level, file, func, line );
548 return( True );
549 } /* dbghdr */
551 /* ************************************************************************** **
552 * Add text to the body of the "current" debug message via the format buffer.
554 * Input: format_str - Format string, as used in printf(), et. al.
555 * ... - Variable argument list.
557 * ..or.. va_alist - Old style variable parameter list starting point.
559 * Output: Always True. See dbghdr() for more info, though this is not
560 * likely to be used in the same way.
562 * ************************************************************************** **
564 #ifdef HAVE_STDARG_H
565 BOOL dbgtext( char *format_str, ... )
567 va_list ap;
568 pstring msgbuf;
570 va_start( ap, format_str );
571 vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
572 va_end( ap );
574 format_debug_text( msgbuf );
576 return( True );
577 } /* dbgtext */
579 #else
580 BOOL dbgtext( va_alist )
581 va_dcl
583 char *format_str;
584 va_list ap;
585 pstring msgbuf;
587 va_start( ap );
588 format_str = va_arg( ap, char * );
589 vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
590 va_end( ap );
592 format_debug_text( msgbuf );
594 return( True );
595 } /* dbgtext */
597 #endif
599 dbg_Token dbg_char2token( dbg_Token *state, int c )
600 /* ************************************************************************ **
601 * Parse input one character at a time.
603 * Input: state - A pointer to a token variable. This is used to
604 * maintain the parser state between calls. For
605 * each input stream, you should set up a separate
606 * state variable and initialize it to dbg_null.
607 * Pass a pointer to it into this function with each
608 * character in the input stream. See dbg_test()
609 * for an example.
610 * c - The "current" character in the input stream.
612 * Output: A token.
613 * The token value will change when delimiters are found,
614 * which indicate a transition between syntactical objects.
615 * Possible return values are:
617 * dbg_null - The input character was an end-of-line.
618 * This resets the parser to its initial state
619 * in preparation for parsing the next line.
620 * dbg_eof - Same as dbg_null, except that the character
621 * was an end-of-file.
622 * dbg_ignore - Returned for whitespace and delimiters.
623 * These lexical tokens are only of interest
624 * to the parser.
625 * dbg_header - Indicates the start of a header line. The
626 * input character was '[' and was the first on
627 * the line.
628 * dbg_timestamp - Indicates that the input character was part
629 * of a header timestamp.
630 * dbg_level - Indicates that the input character was part
631 * of the debug-level value in the header.
632 * dbg_sourcefile - Indicates that the input character was part
633 * of the sourcefile name in the header.
634 * dbg_function - Indicates that the input character was part
635 * of the function name in the header.
636 * dbg_lineno - Indicates that the input character was part
637 * of the DEBUG call line number in the header.
638 * dbg_message - Indicates that the input character was part
639 * of the DEBUG message text.
641 * ************************************************************************ **
644 /* The terminating characters that we see will greatly depend upon
645 * how they are read. For example, if gets() is used instead of
646 * fgets(), then we will not see newline characters. A lot also
647 * depends on the calling function, which may handle terminators
648 * itself.
650 * '\n', '\0', and EOF are all considered line terminators. The
651 * dbg_eof token is sent back if an EOF is encountered.
653 * Warning: only allow the '\0' character to be sent if you are
654 * using gets() to read whole lines (thus replacing '\n'
655 * with '\0'). Sending '\0' at the wrong time will mess
656 * up the parsing.
658 switch( c )
660 case EOF:
661 *state = dbg_null; /* Set state to null (initial state) so */
662 return( dbg_eof ); /* that we can restart with new input. */
663 case '\n':
664 case '\0':
665 *state = dbg_null; /* A newline or eoln resets to the null state. */
666 return( dbg_null );
669 /* When within the body of the message, only a line terminator
670 * can cause a change of state. We've already checked for line
671 * terminators, so if the current state is dbg_msgtxt, simply
672 * return that as our current token.
674 if( dbg_message == *state )
675 return( dbg_message );
677 /* If we are at the start of a new line, and the input character
678 * is an opening bracket, then the line is a header line, otherwise
679 * it's a message body line.
681 if( dbg_null == *state )
683 if( '[' == c )
685 *state = dbg_timestamp;
686 return( dbg_header );
688 *state = dbg_message;
689 return( dbg_message );
692 /* We've taken care of terminators, text blocks and new lines.
693 * The remaining possibilities are all within the header line
694 * itself.
697 /* Within the header line, whitespace can be ignored *except*
698 * within the timestamp.
700 if( isspace( c ) )
702 /* Fudge. The timestamp may contain space characters. */
703 if( (' ' == c) && (dbg_timestamp == *state) )
704 return( dbg_timestamp );
705 /* Otherwise, ignore whitespace. */
706 return( dbg_ignore );
709 /* Okay, at this point we know we're somewhere in the header.
710 * Valid header *states* are: dbg_timestamp, dbg_level,
711 * dbg_sourcefile, dbg_function, and dbg_lineno.
713 switch( c )
715 case ',':
716 if( dbg_timestamp == *state )
718 *state = dbg_level;
719 return( dbg_ignore );
721 break;
722 case ']':
723 if( dbg_level == *state )
725 *state = dbg_sourcefile;
726 return( dbg_ignore );
728 break;
729 case ':':
730 if( dbg_sourcefile == *state )
732 *state = dbg_function;
733 return( dbg_ignore );
735 break;
736 case '(':
737 if( dbg_function == *state )
739 *state = dbg_lineno;
740 return( dbg_ignore );
742 break;
743 case ')':
744 if( dbg_lineno == *state )
746 *state = dbg_null;
747 return( dbg_ignore );
749 break;
752 /* If the previous block did not result in a state change, then
753 * return the current state as the current token.
755 return( *state );
756 } /* dbg_char2token */
758 /* ************************************************************************** */