first pass at updating head branch to be to be the same as the SAMBA_2_0 branch
[tprouty/samba.git] / source3 / lib / debug.c
1 /*
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Samba utility functions
5    Copyright (C) Andrew Tridgell 1992-1998
6
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.
11
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.
16
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.
20 */
21
22 #include "includes.h"
23
24 /* -------------------------------------------------------------------------- **
25  * Defines...
26  *
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.
30  */
31
32 #define FORMAT_BUFR_MAX ( sizeof( format_bufr ) - 1 )
33
34 /* -------------------------------------------------------------------------- **
35  * This module implements Samba's debugging utility.
36  *
37  * The syntax of a debugging log file is represented as:
38  *
39  *  <debugfile> :== { <debugmsg> }
40  *
41  *  <debugmsg>  :== <debughdr> '\n' <debugtext>
42  *
43  *  <debughdr>  :== '[' TIME ',' LEVEL ']' [ [FILENAME ':'] [FUNCTION '()'] ]
44  *
45  *  <debugtext> :== { <debugline> }
46  *
47  *  <debugline> :== TEXT '\n'
48  *
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.
54  *
55  * Basically, what that all means is:
56  *
57  * - A debugging log file is made up of debug messages.
58  *
59  * - Each debug message is made up of a header and text.  The header is
60  *   separated from the text by a newline.
61  *
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.
66  *
67  * - The message text is made up of zero or more lines, each terminated by
68  *   a newline.
69  */
70
71 /* -------------------------------------------------------------------------- **
72  * External variables.
73  *
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.
80  */
81
82 FILE   *dbf        = NULL;
83 pstring debugf     = "";
84 BOOL    append_log = False;
85 int     DEBUGLEVEL = 1;
86
87
88 /* -------------------------------------------------------------------------- **
89  * Internal variables.
90  *
91  *  stdout_logging  - Default False, if set to True then dbf will be set to
92  *                    stdout and debug output will go to dbf only, and not
93  *                    to syslog.  Set in setup_logging() and read in Debug1().
94  *
95  *  debug_count     - Number of debug messages that have been output.
96  *                    Used to check log size.
97  *
98  *  syslog_level    - Internal copy of the message debug level.  Written by
99  *                    dbghdr() and read by Debug1().
100  *
101  *  format_bufr     - Used to format debug messages.  The dbgtext() function
102  *                    prints debug messages to a string, and then passes the
103  *                    string to format_debug_text(), which uses format_bufr
104  *                    to build the formatted output.
105  *
106  *  format_pos      - Marks the first free byte of the format_bufr.
107  */
108
109 static BOOL    stdout_logging = False;
110 static int     debug_count    = 0;
111 #ifdef WITH_SYSLOG
112 static int     syslog_level   = 0;
113 #endif
114 static pstring format_bufr    = { '\0' };
115 static size_t     format_pos     = 0;
116
117
118 /* -------------------------------------------------------------------------- **
119  * Functions...
120  */
121
122 #if defined(SIGUSR2)
123 /* ************************************************************************** **
124  * catch a sigusr2 - decrease the debug log level.
125  * ************************************************************************** **
126  */
127 void sig_usr2( int sig )
128   {
129   DEBUGLEVEL--;
130   if( DEBUGLEVEL < 0 )
131     DEBUGLEVEL = 0;
132
133   DEBUG( 0, ( "Got SIGUSR2; set debug level to %d.\n", DEBUGLEVEL ) );
134
135 #if !defined(HAVE_SIGACTION)
136   CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
137 #endif
138
139   } /* sig_usr2 */
140 #endif /* SIGUSR2 */
141
142 #if defined(SIGUSR1)
143 /* ************************************************************************** **
144  * catch a sigusr1 - increase the debug log level. 
145  * ************************************************************************** **
146  */
147 void sig_usr1( int sig )
148   {
149
150   DEBUGLEVEL++;
151
152   if( DEBUGLEVEL > 10 )
153     DEBUGLEVEL = 10;
154
155   DEBUG( 0, ( "Got SIGUSR1; set debug level to %d.\n", DEBUGLEVEL ) );
156
157 #if !defined(HAVE_SIGACTION)
158   CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
159 #endif
160
161   } /* sig_usr1 */
162 #endif /* SIGUSR1 */
163
164
165 /* ************************************************************************** **
166  * get ready for syslog stuff
167  * ************************************************************************** **
168  */
169 void setup_logging( char *pname, BOOL interactive )
170   {
171   if( interactive )
172     {
173     stdout_logging = True;
174     dbf = stdout;
175     }
176 #ifdef WITH_SYSLOG
177   else
178     {
179     char *p = strrchr( pname,'/' );
180
181     if( p )
182       pname = p + 1;
183 #ifdef LOG_DAEMON
184     openlog( pname, LOG_PID, SYSLOG_FACILITY );
185 #else /* for old systems that have no facility codes. */
186     openlog( pname, LOG_PID );
187 #endif
188     }
189 #endif
190   } /* setup_logging */
191
192 /* ************************************************************************** **
193  * reopen the log files
194  * ************************************************************************** **
195  */
196 void reopen_logs( void )
197   {
198   pstring fname;
199   
200   if( DEBUGLEVEL > 0 )
201     {
202     pstrcpy( fname, debugf );
203     if( lp_loaded() && (*lp_logfile()) )
204       pstrcpy( fname, lp_logfile() );
205
206     if( !strcsequal( fname, debugf ) || !dbf || !file_exist( debugf, NULL ) )
207       {
208       mode_t oldumask = umask( 022 );
209
210       pstrcpy( debugf, fname );
211       if( dbf )
212         (void)fclose( dbf );
213       if( append_log )
214         dbf = sys_fopen( debugf, "a" );
215       else
216         dbf = sys_fopen( debugf, "w" );
217       /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
218        * to fix problem where smbd's that generate less
219        * than 100 messages keep growing the log.
220        */
221       force_check_log_size();
222       if( dbf )
223         setbuf( dbf, NULL );
224       (void)umask( oldumask );
225       }
226     }
227   else
228     {
229     if( dbf )
230       {
231       (void)fclose( dbf );
232       dbf = NULL;
233       }
234     }
235   } /* reopen_logs */
236
237 /* ************************************************************************** **
238  * Force a check of the log size.
239  * ************************************************************************** **
240  */
241 void force_check_log_size( void )
242   {
243   debug_count = 100;
244   } /* force_check_log_size */
245
246 /* ************************************************************************** **
247  * Check to see if the log has grown to be too big.
248  * ************************************************************************** **
249  */
250 static void check_log_size( void )
251 {
252   int         maxlog;
253   SMB_STRUCT_STAT st;
254
255   if( debug_count++ < 100 || geteuid() != 0 )
256     return;
257
258   maxlog = lp_max_log_size() * 1024;
259   if( !dbf || maxlog <= 0 )
260     return;
261
262   if( sys_fstat( fileno( dbf ), &st ) == 0 && st.st_size > maxlog )
263     {
264     (void)fclose( dbf );
265     dbf = NULL;
266     reopen_logs();
267     if( dbf && get_file_size( debugf ) > maxlog )
268       {
269       pstring name;
270
271       (void)fclose( dbf );
272       dbf = NULL;
273       slprintf( name, sizeof(name)-1, "%s.old", debugf );
274       (void)rename( debugf, name );
275       reopen_logs();
276       }
277     }
278   /*
279    * Here's where we need to panic if dbf == NULL..
280    */
281   if(dbf == NULL) {
282     dbf = sys_fopen( "/dev/console", "w" );
283     if(dbf) {
284       DEBUG(0,("check_log_size: open of debug file %s failed - using console.\n",
285             debugf ));
286     } else {
287       /*
288        * We cannot continue without a debug file handle.
289        */
290       abort();
291     }
292   }
293   debug_count = 0;
294 } /* check_log_size */
295
296 /* ************************************************************************** **
297  * Write an debug message on the debugfile.
298  * This is called by dbghdr() and format_debug_text().
299  * ************************************************************************** **
300  */
301 #ifdef HAVE_STDARG_H
302  int Debug1( char *format_str, ... )
303 {
304 #else
305  int Debug1(va_alist)
306 va_dcl
307 {  
308   char *format_str;
309 #endif
310   va_list ap;  
311   int old_errno = errno;
312
313   if( stdout_logging )
314     {
315 #ifdef HAVE_STDARG_H
316     va_start( ap, format_str );
317 #else
318     va_start( ap );
319     format_str = va_arg( ap, char * );
320 #endif
321     (void)vfprintf( dbf, format_str, ap );
322     va_end( ap );
323     errno = old_errno;
324     return( 0 );
325     }
326   
327 #ifdef WITH_SYSLOG
328   if( !lp_syslog_only() )
329 #endif
330     {
331     if( !dbf )
332       {
333       mode_t oldumask = umask( 022 );
334
335       if( append_log )
336         dbf = sys_fopen( debugf, "a" );
337       else
338         dbf = sys_fopen( debugf, "w" );
339       (void)umask( oldumask );
340       if( dbf )
341         {
342         setbuf( dbf, NULL );
343         }
344       else
345         {
346         errno = old_errno;
347         return(0);
348         }
349       }
350     }
351
352 #ifdef WITH_SYSLOG
353   if( syslog_level < lp_syslog() )
354     {
355     /* map debug levels to syslog() priorities
356      * note that not all DEBUG(0, ...) calls are
357      * necessarily errors
358      */
359     static int priority_map[] = { 
360       LOG_ERR,     /* 0 */
361       LOG_WARNING, /* 1 */
362       LOG_NOTICE,  /* 2 */
363       LOG_INFO,    /* 3 */
364       };
365     int     priority;
366     pstring msgbuf;
367
368     if( syslog_level >= ( sizeof(priority_map) / sizeof(priority_map[0]) )
369      || syslog_level < 0)
370       priority = LOG_DEBUG;
371     else
372       priority = priority_map[syslog_level];
373       
374 #ifdef HAVE_STDARG_H
375     va_start( ap, format_str );
376 #else
377     va_start( ap );
378     format_str = va_arg( ap, char * );
379 #endif
380     vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
381     va_end( ap );
382       
383     msgbuf[255] = '\0';
384     syslog( priority, "%s", msgbuf );
385     }
386 #endif
387   
388   check_log_size();
389
390 #ifdef WITH_SYSLOG
391   if( !lp_syslog_only() )
392 #endif
393     {
394 #ifdef HAVE_STDARG_H
395     va_start( ap, format_str );
396 #else
397     va_start( ap );
398     format_str = va_arg( ap, char * );
399 #endif
400     (void)vfprintf( dbf, format_str, ap );
401     va_end( ap );
402     (void)fflush( dbf );
403     }
404
405   errno = old_errno;
406
407   return( 0 );
408   } /* Debug1 */
409
410
411 /* ************************************************************************** **
412  * Print the buffer content via Debug1(), then reset the buffer.
413  *
414  *  Input:  none
415  *  Output: none
416  *
417  * ************************************************************************** **
418  */
419 static void bufr_print( void )
420   {
421   format_bufr[format_pos] = '\0';
422   (void)Debug1( "%s", format_bufr );
423   format_pos = 0;
424   } /* bufr_print */
425
426 /* ************************************************************************** **
427  * Format the debug message text.
428  *
429  *  Input:  msg - Text to be added to the "current" debug message text.
430  *
431  *  Output: none.
432  *
433  *  Notes:  The purpose of this is two-fold.  First, each call to syslog()
434  *          (used by Debug1(), see above) generates a new line of syslog
435  *          output.  This is fixed by storing the partial lines until the
436  *          newline character is encountered.  Second, printing the debug
437  *          message lines when a newline is encountered allows us to add
438  *          spaces, thus indenting the body of the message and making it
439  *          more readable.
440  *
441  * ************************************************************************** **
442  */
443 static void format_debug_text( char *msg )
444   {
445   size_t i;
446   BOOL timestamp = (!stdout_logging && (lp_timestamp_logs() || 
447                                         !(lp_loaded())));
448
449   for( i = 0; msg[i]; i++ )
450     {
451     /* Indent two spaces at each new line. */
452     if(timestamp && 0 == format_pos)
453       {
454       format_bufr[0] = format_bufr[1] = ' ';
455       format_pos = 2;
456       }
457
458     /* If there's room, copy the character to the format buffer. */
459     if( format_pos < FORMAT_BUFR_MAX )
460       format_bufr[format_pos++] = msg[i];
461
462     /* If a newline is encountered, print & restart. */
463     if( '\n' == msg[i] )
464       bufr_print();
465
466     /* If the buffer is full dump it out, reset it, and put out a line
467      * continuation indicator.
468      */
469     if( format_pos >= FORMAT_BUFR_MAX )
470       {
471       bufr_print();
472       (void)Debug1( " +>\n" );
473       }
474     }
475
476   /* Just to be safe... */
477   format_bufr[format_pos] = '\0';
478   } /* format_debug_text */
479
480 /* ************************************************************************** **
481  * Flush debug output, including the format buffer content.
482  *
483  *  Input:  none
484  *  Output: none
485  *
486  * ************************************************************************** **
487  */
488 void dbgflush( void )
489   {
490   bufr_print();
491   (void)fflush( dbf );
492   } /* dbgflush */
493
494 /* ************************************************************************** **
495  * Print a Debug Header.
496  *
497  *  Input:  level - Debug level of the message (not the system-wide debug
498  *                  level.
499  *          file  - Pointer to a string containing the name of the file
500  *                  from which this function was called, or an empty string
501  *                  if the __FILE__ macro is not implemented.
502  *          func  - Pointer to a string containing the name of the function
503  *                  from which this function was called, or an empty string
504  *                  if the __FUNCTION__ macro is not implemented.
505  *          line  - line number of the call to dbghdr, assuming __LINE__
506  *                  works.
507  *
508  *  Output: Always True.  This makes it easy to fudge a call to dbghdr()
509  *          in a macro, since the function can be called as part of a test.
510  *          Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
511  *
512  *  Notes:  This function takes care of setting syslog_level.
513  *
514  * ************************************************************************** **
515  */
516
517 BOOL dbghdr( int level, char *file, char *func, int line )
518 {
519   /* Ensure we don't lose any real errno value. */
520   int old_errno = errno;
521
522   if( format_pos ) {
523     /* This is a fudge.  If there is stuff sitting in the format_bufr, then
524      * the *right* thing to do is to call
525      *   format_debug_text( "\n" );
526      * to write the remainder, and then proceed with the new header.
527      * Unfortunately, there are several places in the code at which
528      * the DEBUG() macro is used to build partial lines.  That in mind,
529      * we'll work under the assumption that an incomplete line indicates
530      * that a new header is *not* desired.
531      */
532     return( True );
533   }
534
535 #ifdef WITH_SYSLOG
536   /* Set syslog_level. */
537   syslog_level = level;
538 #endif
539
540   /* Don't print a header if we're logging to stdout. */
541   if( stdout_logging )
542     return( True );
543
544   /* Print the header if timestamps are turned on.  If parameters are
545    * not yet loaded, then default to timestamps on.
546    */
547   if( lp_timestamp_logs() || !(lp_loaded()) ) {
548     char header_str[200];
549
550         header_str[0] = '\0';
551
552         if( lp_debug_pid())
553           slprintf(header_str,sizeof(header_str)-1,", pid=%u",(unsigned int)getpid());
554
555         if( lp_debug_uid()) {
556       size_t hs_len = strlen(header_str);
557           slprintf(header_str + hs_len,
558                sizeof(header_str) - 1 - hs_len,
559                            ", effective(%u, %u), real(%u, %u)",
560                (unsigned int)geteuid(), (unsigned int)getegid(),
561                            (unsigned int)getuid(), (unsigned int)getgid()); 
562         }
563   
564     /* Print it all out at once to prevent split syslog output. */
565     (void)Debug1( "[%s, %d%s] %s:%s(%d)\n",
566                   timestring(lp_debug_hires_timestamp()), level,
567                                   header_str, file, func, line );
568   }
569
570   errno = old_errno;
571   return( True );
572 }
573
574 /* ************************************************************************** **
575  * Add text to the body of the "current" debug message via the format buffer.
576  *
577  *  Input:  format_str  - Format string, as used in printf(), et. al.
578  *          ...         - Variable argument list.
579  *
580  *  ..or..  va_alist    - Old style variable parameter list starting point.
581  *
582  *  Output: Always True.  See dbghdr() for more info, though this is not
583  *          likely to be used in the same way.
584  *
585  * ************************************************************************** **
586  */
587 #ifdef HAVE_STDARG_H
588  BOOL dbgtext( char *format_str, ... )
589   {
590   va_list ap;
591   pstring msgbuf;
592
593   va_start( ap, format_str ); 
594   vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
595   va_end( ap );
596
597   format_debug_text( msgbuf );
598
599   return( True );
600   } /* dbgtext */
601
602 #else
603  BOOL dbgtext( va_alist )
604  va_dcl
605   {
606   char *format_str;
607   va_list ap;
608   pstring msgbuf;
609
610   va_start( ap );
611   format_str = va_arg( ap, char * );
612   vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
613   va_end( ap );
614
615   format_debug_text( msgbuf );
616
617   return( True );
618   } /* dbgtext */
619
620 #endif
621
622 /* ************************************************************************** */