if we are adding a new sambaAccount, make sure that we add a
[Samba.git] / source / lib / debug.c
blob347c644c2a09e64567e1a94f8358dcf1d97524c0
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;
88 BOOL AllowDebugChange = True;
89 int parsed_debuglevel_class[DBGC_LAST];
91 /* -------------------------------------------------------------------------- **
92 * Internal variables.
94 * stdout_logging - Default False, if set to True then dbf will be set to
95 * stdout and debug output will go to dbf only, and not
96 * to syslog. Set in setup_logging() and read in Debug1().
98 * debug_count - Number of debug messages that have been output.
99 * Used to check log size.
101 * syslog_level - Internal copy of the message debug level. Written by
102 * dbghdr() and read by Debug1().
104 * format_bufr - Used to format debug messages. The dbgtext() function
105 * prints debug messages to a string, and then passes the
106 * string to format_debug_text(), which uses format_bufr
107 * to build the formatted output.
109 * format_pos - Marks the first free byte of the format_bufr.
112 * log_overflow - When this variable is True, never attempt to check the
113 * size of the log. This is a hack, so that we can write
114 * a message using DEBUG, from open_logs() when we
115 * are unable to open a new log file for some reason.
118 static BOOL stdout_logging = False;
119 static int debug_count = 0;
120 #ifdef WITH_SYSLOG
121 static int syslog_level = 0;
122 #endif
123 static pstring format_bufr = { '\0' };
124 static size_t format_pos = 0;
125 static BOOL log_overflow = False;
128 * Define all the debug class selection names here. Names *MUST NOT* contain
129 * white space. There must be one name for each DBGC_<class name>, and they
130 * must be in the table in the order of DBGC_<class name>..
132 char *classname_table[] = {
133 "all", /* DBGC_ALL; index references traditional DEBUGLEVEL */
134 "tdb", /* DBGC_TDB */
135 "printdrivers", /* DBGC_PRINTDRIVERS */
136 "lanman", /* DBGC_LANMAN */
140 /* -------------------------------------------------------------------------- **
141 * Functions...
144 /****************************************************************************
145 utility access to debug class names's
146 ****************************************************************************/
147 char* debug_classname_from_index(int ndx)
149 return classname_table[ndx];
152 /****************************************************************************
153 utility to translate names to debug class index's
154 ****************************************************************************/
155 int debug_lookup_classname(char* classname)
157 int i;
159 if (!classname) return -1;
161 for (i=0; i<DBGC_LAST; i++) {
162 if (strcmp(classname, classname_table[i])==0)
163 return i;
165 return -1;
168 /****************************************************************************
169 parse the debug levels from smbcontrol. Example debug level parameter:
170 printdrivers:7
171 ****************************************************************************/
172 BOOL debug_parse_params(char **params, int *debuglevel_class)
174 int i, ndx;
175 char *class_name;
176 char *class_level;
178 /* Set the new debug level array to the current DEBUGLEVEL array */
179 memcpy(debuglevel_class, DEBUGLEVEL_CLASS, sizeof(DEBUGLEVEL_CLASS));
181 /* Allow DBGC_ALL to be specifies w/o requiring its class name e.g."10"
182 * v.s. "all:10", this is the traditional way to set DEBUGLEVEL
184 if (isdigit((int)params[0][0])) {
185 debuglevel_class[DBGC_ALL] = atoi(params[0]);
186 i = 1; /* start processing at the next params */
188 else
189 i = 0; /* DBGC_ALL not specified OR calss name was included */
191 /* Fill in new debug class levels */
192 for (; i < DBGC_LAST && params[i]; i++) {
193 if ((class_name=strtok(params[i],":")) &&
194 (class_level=strtok(NULL, "\0")) &&
195 ((ndx = debug_lookup_classname(class_name)) != -1)) {
196 debuglevel_class[ndx] = atoi(class_level);
197 } else {
198 DEBUG(0,("debug_parse_params: unrecognized debug class name or format [%s]\n", params[i]));
199 return False;
203 return True;
206 /****************************************************************************
207 parse the debug levels from smb.conf. Example debug level string:
208 3 tdb:5 printdrivers:7
209 Note: the 1st param has no "name:" preceeding it.
210 ****************************************************************************/
211 BOOL debug_parse_levels(char *params_str)
213 int i;
214 char *params[DBGC_LAST];
215 int debuglevel_class[DBGC_LAST];
217 ZERO_ARRAY(params);
218 ZERO_ARRAY(debuglevel_class);
220 if ((params[0]=strtok(params_str," ,"))) {
221 for (i=1; i<DBGC_LAST;i++) {
222 if ((params[i]=strtok(NULL," ,"))==NULL)
223 break;
226 else
227 return False;
229 if (AllowDebugChange == False) {
230 int old_debuglevel_class[DBGC_LAST];
232 /* save current debug level */
233 memcpy(old_debuglevel_class, DEBUGLEVEL_CLASS, sizeof(DEBUGLEVEL_CLASS));
234 if (debug_parse_params(params, debuglevel_class))
235 memcpy(parsed_debuglevel_class, debuglevel_class, sizeof(DEBUGLEVEL_CLASS));
236 memcpy(DEBUGLEVEL_CLASS, old_debuglevel_class, sizeof(old_debuglevel_class));
237 return True;
239 if (debug_parse_params(params, debuglevel_class)) {
240 debug_message(MSG_DEBUG, getpid(), (void*)debuglevel_class, sizeof(debuglevel_class));
241 return True;
242 } else
243 return False;
246 /****************************************************************************
247 receive a "set debug level" message
248 ****************************************************************************/
249 void debug_message(int msg_type, pid_t src, void *buf, size_t len)
251 int i;
253 /* Set the new DEBUGLEVEL_CLASS array from the pased array */
254 memcpy(DEBUGLEVEL_CLASS, buf, sizeof(DEBUGLEVEL_CLASS));
256 DEBUG(1,("INFO: Debug class %s level = %d (pid %u from pid %u)\n",
257 classname_table[DBGC_ALL],
258 DEBUGLEVEL_CLASS[DBGC_ALL], (unsigned int)getpid(), (unsigned int)src));
260 for (i=1; i<DBGC_LAST; i++) {
261 if (DEBUGLEVEL_CLASS[i])
262 DEBUGADD(1,("INFO: Debug class %s level = %d\n",
263 classname_table[i], DEBUGLEVEL_CLASS[i]));
268 /****************************************************************************
269 send a "set debug level" message
270 ****************************************************************************/
271 void debug_message_send(pid_t pid, int level)
273 message_send_pid(pid, MSG_DEBUG, &level, sizeof(int), False);
277 /* ************************************************************************** **
278 * get ready for syslog stuff
279 * ************************************************************************** **
281 void setup_logging(char *pname, BOOL interactive)
283 message_register(MSG_DEBUG, debug_message);
285 /* reset to allow multiple setup calls, going from interactive to
286 non-interactive */
287 stdout_logging = False;
288 dbf = NULL;
290 if (interactive) {
291 stdout_logging = True;
292 dbf = stdout;
294 #ifdef WITH_SYSLOG
295 else {
296 char *p = strrchr( pname,'/' );
297 if (p)
298 pname = p + 1;
299 #ifdef LOG_DAEMON
300 openlog( pname, LOG_PID, SYSLOG_FACILITY );
301 #else /* for old systems that have no facility codes. */
302 openlog( pname, LOG_PID );
303 #endif
305 #endif
306 } /* setup_logging */
308 /* ************************************************************************** **
309 * reopen the log files
310 * note that we now do this unconditionally
311 * We attempt to open the new debug fp before closing the old. This means
312 * if we run out of fd's we just keep using the old fd rather than aborting.
313 * Fix from dgibson@linuxcare.com.
314 * ************************************************************************** **
317 BOOL reopen_logs( void )
319 pstring fname;
320 mode_t oldumask;
321 FILE *new_dbf = NULL;
322 BOOL ret = True;
324 if (stdout_logging)
325 return True;
327 oldumask = umask( 022 );
329 pstrcpy(fname, debugf );
331 if (lp_loaded()) {
332 char *logfname;
334 logfname = lp_logfile();
335 if (*logfname)
336 pstrcpy(fname, logfname);
339 pstrcpy(debugf, fname);
341 if (append_log)
342 new_dbf = sys_fopen( debugf, "a" );
343 else
344 new_dbf = sys_fopen( debugf, "w" );
346 if (!new_dbf) {
347 log_overflow = True;
348 DEBUG(0, ("Unable to open new log file %s: %s\n", debugf, strerror(errno)));
349 log_overflow = False;
350 if (dbf)
351 fflush(dbf);
352 ret = False;
353 } else {
354 setbuf(new_dbf, NULL);
355 if (dbf)
356 (void) fclose(dbf);
357 dbf = new_dbf;
360 /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
361 * to fix problem where smbd's that generate less
362 * than 100 messages keep growing the log.
364 force_check_log_size();
365 (void)umask(oldumask);
367 return ret;
370 /* ************************************************************************** **
371 * Force a check of the log size.
372 * ************************************************************************** **
374 void force_check_log_size( void )
376 debug_count = 100;
379 /***************************************************************************
380 Check to see if there is any need to check if the logfile has grown too big.
381 **************************************************************************/
383 BOOL need_to_check_log_size( void )
385 int maxlog;
387 if( debug_count++ < 100 )
388 return( False );
390 maxlog = lp_max_log_size() * 1024;
391 if( !dbf || maxlog <= 0 ) {
392 debug_count = 0;
393 return(False);
395 return( True );
398 /* ************************************************************************** **
399 * Check to see if the log has grown to be too big.
400 * ************************************************************************** **
403 void check_log_size( void )
405 int maxlog;
406 SMB_STRUCT_STAT st;
409 * We need to be root to check/change log-file, skip this and let the main
410 * loop check do a new check as root.
413 if( geteuid() != 0 )
414 return;
416 if(log_overflow || !need_to_check_log_size() )
417 return;
419 maxlog = lp_max_log_size() * 1024;
421 if( sys_fstat( fileno( dbf ), &st ) == 0 && st.st_size > maxlog ) {
422 (void)reopen_logs();
423 if( dbf && get_file_size( debugf ) > maxlog ) {
424 pstring name;
426 slprintf( name, sizeof(name)-1, "%s.old", debugf );
427 (void)rename( debugf, name );
429 if (!reopen_logs()) {
430 /* We failed to reopen a log - continue using the old name. */
431 (void)rename(name, debugf);
437 * Here's where we need to panic if dbf == NULL..
440 if(dbf == NULL) {
441 /* This code should only be reached in very strange
442 circumstances. If we merely fail to open the new log we
443 should stick with the old one. ergo this should only be
444 reached when opening the logs for the first time: at
445 startup or when the log level is increased from zero.
446 -dwg 6 June 2000
448 dbf = sys_fopen( "/dev/console", "w" );
449 if(dbf) {
450 DEBUG(0,("check_log_size: open of debug file %s failed - using console.\n",
451 debugf ));
452 } else {
454 * We cannot continue without a debug file handle.
456 abort();
459 debug_count = 0;
460 } /* check_log_size */
462 /* ************************************************************************** **
463 * Write an debug message on the debugfile.
464 * This is called by dbghdr() and format_debug_text().
465 * ************************************************************************** **
467 int Debug1( char *format_str, ... )
469 va_list ap;
470 int old_errno = errno;
472 if( stdout_logging )
474 va_start( ap, format_str );
475 if(dbf)
476 (void)vfprintf( dbf, format_str, ap );
477 va_end( ap );
478 errno = old_errno;
479 return( 0 );
482 #ifdef WITH_SYSLOG
483 if( !lp_syslog_only() )
484 #endif
486 if( !dbf )
488 mode_t oldumask = umask( 022 );
490 if( append_log )
491 dbf = sys_fopen( debugf, "a" );
492 else
493 dbf = sys_fopen( debugf, "w" );
494 (void)umask( oldumask );
495 if( dbf )
497 setbuf( dbf, NULL );
499 else
501 errno = old_errno;
502 return(0);
507 #ifdef WITH_SYSLOG
508 if( syslog_level < lp_syslog() )
510 /* map debug levels to syslog() priorities
511 * note that not all DEBUG(0, ...) calls are
512 * necessarily errors
514 static int priority_map[] = {
515 LOG_ERR, /* 0 */
516 LOG_WARNING, /* 1 */
517 LOG_NOTICE, /* 2 */
518 LOG_INFO, /* 3 */
520 int priority;
521 pstring msgbuf;
523 if( syslog_level >= ( sizeof(priority_map) / sizeof(priority_map[0]) )
524 || syslog_level < 0)
525 priority = LOG_DEBUG;
526 else
527 priority = priority_map[syslog_level];
529 va_start( ap, format_str );
530 vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
531 va_end( ap );
533 msgbuf[255] = '\0';
534 syslog( priority, "%s", msgbuf );
536 #endif
538 check_log_size();
540 #ifdef WITH_SYSLOG
541 if( !lp_syslog_only() )
542 #endif
544 va_start( ap, format_str );
545 if(dbf)
546 (void)vfprintf( dbf, format_str, ap );
547 va_end( ap );
548 if(dbf)
549 (void)fflush( dbf );
552 errno = old_errno;
554 return( 0 );
555 } /* Debug1 */
558 /* ************************************************************************** **
559 * Print the buffer content via Debug1(), then reset the buffer.
561 * Input: none
562 * Output: none
564 * ************************************************************************** **
566 static void bufr_print( void )
568 format_bufr[format_pos] = '\0';
569 (void)Debug1( "%s", format_bufr );
570 format_pos = 0;
571 } /* bufr_print */
573 /* ************************************************************************** **
574 * Format the debug message text.
576 * Input: msg - Text to be added to the "current" debug message text.
578 * Output: none.
580 * Notes: The purpose of this is two-fold. First, each call to syslog()
581 * (used by Debug1(), see above) generates a new line of syslog
582 * output. This is fixed by storing the partial lines until the
583 * newline character is encountered. Second, printing the debug
584 * message lines when a newline is encountered allows us to add
585 * spaces, thus indenting the body of the message and making it
586 * more readable.
588 * ************************************************************************** **
590 static void format_debug_text( char *msg )
592 size_t i;
593 BOOL timestamp = (!stdout_logging && (lp_timestamp_logs() ||
594 !(lp_loaded())));
596 for( i = 0; msg[i]; i++ )
598 /* Indent two spaces at each new line. */
599 if(timestamp && 0 == format_pos)
601 format_bufr[0] = format_bufr[1] = ' ';
602 format_pos = 2;
605 /* If there's room, copy the character to the format buffer. */
606 if( format_pos < FORMAT_BUFR_MAX )
607 format_bufr[format_pos++] = msg[i];
609 /* If a newline is encountered, print & restart. */
610 if( '\n' == msg[i] )
611 bufr_print();
613 /* If the buffer is full dump it out, reset it, and put out a line
614 * continuation indicator.
616 if( format_pos >= FORMAT_BUFR_MAX )
618 bufr_print();
619 (void)Debug1( " +>\n" );
623 /* Just to be safe... */
624 format_bufr[format_pos] = '\0';
625 } /* format_debug_text */
627 /* ************************************************************************** **
628 * Flush debug output, including the format buffer content.
630 * Input: none
631 * Output: none
633 * ************************************************************************** **
635 void dbgflush( void )
637 bufr_print();
638 if(dbf)
639 (void)fflush( dbf );
640 } /* dbgflush */
642 /* ************************************************************************** **
643 * Print a Debug Header.
645 * Input: level - Debug level of the message (not the system-wide debug
646 * level.
647 * file - Pointer to a string containing the name of the file
648 * from which this function was called, or an empty string
649 * if the __FILE__ macro is not implemented.
650 * func - Pointer to a string containing the name of the function
651 * from which this function was called, or an empty string
652 * if the __FUNCTION__ macro is not implemented.
653 * line - line number of the call to dbghdr, assuming __LINE__
654 * works.
656 * Output: Always True. This makes it easy to fudge a call to dbghdr()
657 * in a macro, since the function can be called as part of a test.
658 * Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
660 * Notes: This function takes care of setting syslog_level.
662 * ************************************************************************** **
665 BOOL dbghdr( int level, char *file, char *func, int line )
667 /* Ensure we don't lose any real errno value. */
668 int old_errno = errno;
670 if( format_pos ) {
671 /* This is a fudge. If there is stuff sitting in the format_bufr, then
672 * the *right* thing to do is to call
673 * format_debug_text( "\n" );
674 * to write the remainder, and then proceed with the new header.
675 * Unfortunately, there are several places in the code at which
676 * the DEBUG() macro is used to build partial lines. That in mind,
677 * we'll work under the assumption that an incomplete line indicates
678 * that a new header is *not* desired.
680 return( True );
683 #ifdef WITH_SYSLOG
684 /* Set syslog_level. */
685 syslog_level = level;
686 #endif
688 /* Don't print a header if we're logging to stdout. */
689 if( stdout_logging )
690 return( True );
692 /* Print the header if timestamps are turned on. If parameters are
693 * not yet loaded, then default to timestamps on.
695 if( lp_timestamp_logs() || !(lp_loaded()) ) {
696 char header_str[200];
698 header_str[0] = '\0';
700 if( lp_debug_pid())
701 slprintf(header_str,sizeof(header_str)-1,", pid=%u",(unsigned int)sys_getpid());
703 if( lp_debug_uid()) {
704 size_t hs_len = strlen(header_str);
705 slprintf(header_str + hs_len,
706 sizeof(header_str) - 1 - hs_len,
707 ", effective(%u, %u), real(%u, %u)",
708 (unsigned int)geteuid(), (unsigned int)getegid(),
709 (unsigned int)getuid(), (unsigned int)getgid());
712 /* Print it all out at once to prevent split syslog output. */
713 (void)Debug1( "[%s, %d%s] %s:%s(%d)\n",
714 timestring(lp_debug_hires_timestamp()), level,
715 header_str, file, func, line );
718 errno = old_errno;
719 return( True );
722 /* ************************************************************************** **
723 * Add text to the body of the "current" debug message via the format buffer.
725 * Input: format_str - Format string, as used in printf(), et. al.
726 * ... - Variable argument list.
728 * ..or.. va_alist - Old style variable parameter list starting point.
730 * Output: Always True. See dbghdr() for more info, though this is not
731 * likely to be used in the same way.
733 * ************************************************************************** **
735 BOOL dbgtext( char *format_str, ... )
737 va_list ap;
738 pstring msgbuf;
740 va_start( ap, format_str );
741 vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
742 va_end( ap );
744 format_debug_text( msgbuf );
746 return( True );
747 } /* dbgtext */
750 /* ************************************************************************** */