the first cut of the internal messaging system.
[kai/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 /****************************************************************************
123 receive a "set debug level" message
124 ****************************************************************************/
125 void debug_message(pid_t src, void *buf, int len)
126 {
127         int level;
128         memcpy(&level, buf, sizeof(int));
129         DEBUGLEVEL = level;
130         DEBUG(1,("Debug level set to %d from pid %d\n", level, (int)src));
131 }
132
133 /****************************************************************************
134 send a "set debug level" message
135 ****************************************************************************/
136 void debug_message_send(pid_t pid, int level)
137 {
138         message_send_pid(pid, MSG_DEBUG, &level, sizeof(int));
139 }
140
141
142 /* ************************************************************************** **
143  * get ready for syslog stuff
144  * ************************************************************************** **
145  */
146 void setup_logging( char *pname, BOOL interactive )
147   {
148   if( interactive )
149     {
150     stdout_logging = True;
151     dbf = stdout;
152     }
153 #ifdef WITH_SYSLOG
154   else
155     {
156     char *p = strrchr( pname,'/' );
157
158     if( p )
159       pname = p + 1;
160 #ifdef LOG_DAEMON
161     openlog( pname, LOG_PID, SYSLOG_FACILITY );
162 #else /* for old systems that have no facility codes. */
163     openlog( pname, LOG_PID );
164 #endif
165     }
166 #endif
167   } /* setup_logging */
168
169 /* ************************************************************************** **
170  * reopen the log files
171  * note that we now do this unconditionally
172  * ************************************************************************** **
173  */
174 void reopen_logs( void )
175 {
176         pstring fname;
177         mode_t oldumask;
178
179         if (DEBUGLEVEL <= 0) {
180                 if (dbf) {
181                         (void)fclose(dbf);
182                         dbf = NULL;
183                 }
184                 return;
185         }
186
187         oldumask = umask( 022 );
188   
189         pstrcpy(fname, debugf );
190         if (lp_loaded() && (*lp_logfile()))
191                 pstrcpy(fname, lp_logfile());
192
193         pstrcpy( debugf, fname );
194         if (dbf)
195                 (void)fclose(dbf);
196         if (append_log)
197                 dbf = sys_fopen( debugf, "a" );
198         else
199                 dbf = sys_fopen( debugf, "w" );
200         /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
201          * to fix problem where smbd's that generate less
202          * than 100 messages keep growing the log.
203          */
204         force_check_log_size();
205         if (dbf)
206                 setbuf( dbf, NULL );
207         (void)umask(oldumask);
208 }
209
210
211 /* ************************************************************************** **
212  * Force a check of the log size.
213  * ************************************************************************** **
214  */
215 void force_check_log_size( void )
216 {
217   debug_count = 100;
218 }
219
220 /***************************************************************************
221  Check to see if there is any need to check if the logfile has grown too big.
222 **************************************************************************/
223
224 BOOL need_to_check_log_size( void )
225 {
226         int maxlog;
227
228         if( debug_count++ < 100 )
229                 return( False );
230
231         maxlog = lp_max_log_size() * 1024;
232         if( !dbf || maxlog <= 0 ) {
233                 debug_count = 0;
234                 return(False);
235         }
236         return( True );
237 }
238
239 /* ************************************************************************** **
240  * Check to see if the log has grown to be too big.
241  * ************************************************************************** **
242  */
243
244 void check_log_size( void )
245 {
246   int         maxlog;
247   SMB_STRUCT_STAT st;
248
249   /*
250    *  We need to be root to check/change log-file, skip this and let the main
251    *  loop check do a new check as root.
252    */
253
254   if( geteuid() != 0 )
255     return;
256
257   if( !need_to_check_log_size() )
258     return;
259
260   maxlog = lp_max_log_size() * 1024;
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     if(dbf)
322       (void)vfprintf( dbf, format_str, ap );
323     va_end( ap );
324     errno = old_errno;
325     return( 0 );
326     }
327   
328 #ifdef WITH_SYSLOG
329   if( !lp_syslog_only() )
330 #endif
331     {
332     if( !dbf )
333       {
334       mode_t oldumask = umask( 022 );
335
336       if( append_log )
337         dbf = sys_fopen( debugf, "a" );
338       else
339         dbf = sys_fopen( debugf, "w" );
340       (void)umask( oldumask );
341       if( dbf )
342         {
343         setbuf( dbf, NULL );
344         }
345       else
346         {
347         errno = old_errno;
348         return(0);
349         }
350       }
351     }
352
353 #ifdef WITH_SYSLOG
354   if( syslog_level < lp_syslog() )
355     {
356     /* map debug levels to syslog() priorities
357      * note that not all DEBUG(0, ...) calls are
358      * necessarily errors
359      */
360     static int priority_map[] = { 
361       LOG_ERR,     /* 0 */
362       LOG_WARNING, /* 1 */
363       LOG_NOTICE,  /* 2 */
364       LOG_INFO,    /* 3 */
365       };
366     int     priority;
367     pstring msgbuf;
368
369     if( syslog_level >= ( sizeof(priority_map) / sizeof(priority_map[0]) )
370      || syslog_level < 0)
371       priority = LOG_DEBUG;
372     else
373       priority = priority_map[syslog_level];
374       
375 #ifdef HAVE_STDARG_H
376     va_start( ap, format_str );
377 #else
378     va_start( ap );
379     format_str = va_arg( ap, char * );
380 #endif
381     vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
382     va_end( ap );
383       
384     msgbuf[255] = '\0';
385     syslog( priority, "%s", msgbuf );
386     }
387 #endif
388   
389   check_log_size();
390
391 #ifdef WITH_SYSLOG
392   if( !lp_syslog_only() )
393 #endif
394     {
395 #ifdef HAVE_STDARG_H
396     va_start( ap, format_str );
397 #else
398     va_start( ap );
399     format_str = va_arg( ap, char * );
400 #endif
401     if(dbf)
402       (void)vfprintf( dbf, format_str, ap );
403     va_end( ap );
404     if(dbf)
405       (void)fflush( dbf );
406     }
407
408   errno = old_errno;
409
410   return( 0 );
411   } /* Debug1 */
412
413
414 /* ************************************************************************** **
415  * Print the buffer content via Debug1(), then reset the buffer.
416  *
417  *  Input:  none
418  *  Output: none
419  *
420  * ************************************************************************** **
421  */
422 static void bufr_print( void )
423   {
424   format_bufr[format_pos] = '\0';
425   (void)Debug1( "%s", format_bufr );
426   format_pos = 0;
427   } /* bufr_print */
428
429 /* ************************************************************************** **
430  * Format the debug message text.
431  *
432  *  Input:  msg - Text to be added to the "current" debug message text.
433  *
434  *  Output: none.
435  *
436  *  Notes:  The purpose of this is two-fold.  First, each call to syslog()
437  *          (used by Debug1(), see above) generates a new line of syslog
438  *          output.  This is fixed by storing the partial lines until the
439  *          newline character is encountered.  Second, printing the debug
440  *          message lines when a newline is encountered allows us to add
441  *          spaces, thus indenting the body of the message and making it
442  *          more readable.
443  *
444  * ************************************************************************** **
445  */
446 static void format_debug_text( char *msg )
447   {
448   size_t i;
449   BOOL timestamp = (!stdout_logging && (lp_timestamp_logs() || 
450                                         !(lp_loaded())));
451
452   for( i = 0; msg[i]; i++ )
453     {
454     /* Indent two spaces at each new line. */
455     if(timestamp && 0 == format_pos)
456       {
457       format_bufr[0] = format_bufr[1] = ' ';
458       format_pos = 2;
459       }
460
461     /* If there's room, copy the character to the format buffer. */
462     if( format_pos < FORMAT_BUFR_MAX )
463       format_bufr[format_pos++] = msg[i];
464
465     /* If a newline is encountered, print & restart. */
466     if( '\n' == msg[i] )
467       bufr_print();
468
469     /* If the buffer is full dump it out, reset it, and put out a line
470      * continuation indicator.
471      */
472     if( format_pos >= FORMAT_BUFR_MAX )
473       {
474       bufr_print();
475       (void)Debug1( " +>\n" );
476       }
477     }
478
479   /* Just to be safe... */
480   format_bufr[format_pos] = '\0';
481   } /* format_debug_text */
482
483 /* ************************************************************************** **
484  * Flush debug output, including the format buffer content.
485  *
486  *  Input:  none
487  *  Output: none
488  *
489  * ************************************************************************** **
490  */
491 void dbgflush( void )
492   {
493   bufr_print();
494   if(dbf)
495     (void)fflush( dbf );
496   } /* dbgflush */
497
498 /* ************************************************************************** **
499  * Print a Debug Header.
500  *
501  *  Input:  level - Debug level of the message (not the system-wide debug
502  *                  level.
503  *          file  - Pointer to a string containing the name of the file
504  *                  from which this function was called, or an empty string
505  *                  if the __FILE__ macro is not implemented.
506  *          func  - Pointer to a string containing the name of the function
507  *                  from which this function was called, or an empty string
508  *                  if the __FUNCTION__ macro is not implemented.
509  *          line  - line number of the call to dbghdr, assuming __LINE__
510  *                  works.
511  *
512  *  Output: Always True.  This makes it easy to fudge a call to dbghdr()
513  *          in a macro, since the function can be called as part of a test.
514  *          Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
515  *
516  *  Notes:  This function takes care of setting syslog_level.
517  *
518  * ************************************************************************** **
519  */
520
521 BOOL dbghdr( int level, char *file, char *func, int line )
522 {
523   /* Ensure we don't lose any real errno value. */
524   int old_errno = errno;
525
526   if( format_pos ) {
527     /* This is a fudge.  If there is stuff sitting in the format_bufr, then
528      * the *right* thing to do is to call
529      *   format_debug_text( "\n" );
530      * to write the remainder, and then proceed with the new header.
531      * Unfortunately, there are several places in the code at which
532      * the DEBUG() macro is used to build partial lines.  That in mind,
533      * we'll work under the assumption that an incomplete line indicates
534      * that a new header is *not* desired.
535      */
536     return( True );
537   }
538
539 #ifdef WITH_SYSLOG
540   /* Set syslog_level. */
541   syslog_level = level;
542 #endif
543
544   /* Don't print a header if we're logging to stdout. */
545   if( stdout_logging )
546     return( True );
547
548   /* Print the header if timestamps are turned on.  If parameters are
549    * not yet loaded, then default to timestamps on.
550    */
551   if( lp_timestamp_logs() || !(lp_loaded()) ) {
552     char header_str[200];
553
554         header_str[0] = '\0';
555
556         if( lp_debug_pid())
557           slprintf(header_str,sizeof(header_str)-1,", pid=%u",(unsigned int)sys_getpid());
558
559         if( lp_debug_uid()) {
560       size_t hs_len = strlen(header_str);
561           slprintf(header_str + hs_len,
562                sizeof(header_str) - 1 - hs_len,
563                            ", effective(%u, %u), real(%u, %u)",
564                (unsigned int)geteuid(), (unsigned int)getegid(),
565                            (unsigned int)getuid(), (unsigned int)getgid()); 
566         }
567   
568     /* Print it all out at once to prevent split syslog output. */
569     (void)Debug1( "[%s, %d%s] %s:%s(%d)\n",
570                   timestring(lp_debug_hires_timestamp()), level,
571                                   header_str, file, func, line );
572   }
573
574   errno = old_errno;
575   return( True );
576 }
577
578 /* ************************************************************************** **
579  * Add text to the body of the "current" debug message via the format buffer.
580  *
581  *  Input:  format_str  - Format string, as used in printf(), et. al.
582  *          ...         - Variable argument list.
583  *
584  *  ..or..  va_alist    - Old style variable parameter list starting point.
585  *
586  *  Output: Always True.  See dbghdr() for more info, though this is not
587  *          likely to be used in the same way.
588  *
589  * ************************************************************************** **
590  */
591 #ifdef HAVE_STDARG_H
592  BOOL dbgtext( char *format_str, ... )
593   {
594   va_list ap;
595   pstring msgbuf;
596
597   va_start( ap, format_str ); 
598   vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
599   va_end( ap );
600
601   format_debug_text( msgbuf );
602
603   return( True );
604   } /* dbgtext */
605
606 #else
607  BOOL dbgtext( va_alist )
608  va_dcl
609   {
610   char *format_str;
611   va_list ap;
612   pstring msgbuf;
613
614   va_start( ap );
615   format_str = va_arg( ap, char * );
616   vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
617   va_end( ap );
618
619   format_debug_text( msgbuf );
620
621   return( True );
622   } /* dbgtext */
623
624 #endif
625
626 /* ************************************************************************** */