Merge of new 2.2 code into HEAD (Gerald I hate you :-) :-). Allows new SAMR
[nivanova/samba-autobuild/.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_CLASS[DBGC_LAST];
86 int     DEBUGLEVEL = DEBUGLEVEL_CLASS;
87
88
89 /* -------------------------------------------------------------------------- **
90  * Internal variables.
91  *
92  *  stdout_logging  - Default False, if set to True then dbf will be set to
93  *                    stdout and debug output will go to dbf only, and not
94  *                    to syslog.  Set in setup_logging() and read in Debug1().
95  *
96  *  debug_count     - Number of debug messages that have been output.
97  *                    Used to check log size.
98  *
99  *  syslog_level    - Internal copy of the message debug level.  Written by
100  *                    dbghdr() and read by Debug1().
101  *
102  *  format_bufr     - Used to format debug messages.  The dbgtext() function
103  *                    prints debug messages to a string, and then passes the
104  *                    string to format_debug_text(), which uses format_bufr
105  *                    to build the formatted output.
106  *
107  *  format_pos      - Marks the first free byte of the format_bufr.
108  */
109
110 static BOOL    stdout_logging = False;
111 static int     debug_count    = 0;
112 #ifdef WITH_SYSLOG
113 static int     syslog_level   = 0;
114 #endif
115 static pstring format_bufr    = { '\0' };
116 static size_t     format_pos     = 0;
117
118 /*
119 * Define all the debug class selection names here. Names *MUST NOT* contain 
120 * white space. There must be one name for each DBGC_<class name>, and they 
121 * must be in the table in the order of DBGC_<class name>.. 
122 */
123 char *classname_table[] = {
124         "all",               /* DBGC_ALL; index references traditional DEBUGLEVEL */
125         "tdb",               /* DBGC_TDB        */
126         "printdrivers",      /* DBGC_PRINTDRIVERS */
127         "lanman",            /* DBGC_LANMAN */
128 };
129
130
131 /* -------------------------------------------------------------------------- **
132  * Functions...
133  */
134
135 /****************************************************************************
136 utility access to debug class names's
137 ****************************************************************************/
138 char* debug_classname_from_index(int ndx)
139 {
140         return classname_table[ndx];
141 }
142
143 /****************************************************************************
144 utility to translate names to debug class index's
145 ****************************************************************************/
146 int debug_lookup_classname(char* classname)
147 {
148         int i;
149
150         if (!classname) return -1;
151
152         for (i=0; i<DBGC_LAST; i++) {
153                 if (strcmp(classname, classname_table[i])==0)
154                         return i;
155         }
156         return -1;
157 }
158
159 /****************************************************************************
160 parse the debug levels from smbcontrol. Example debug level parameter:
161   printdrivers:7
162 ****************************************************************************/
163 BOOL debug_parse_params(char **params, int *debuglevel_class)
164 {
165         int   i, ndx;
166         char *class_name;
167         char *class_level;
168         
169         /* Set the new debug level array to the current DEBUGLEVEL array */
170         memcpy(debuglevel_class, DEBUGLEVEL_CLASS, sizeof(DEBUGLEVEL_CLASS));
171
172         /* Allow DBGC_ALL to be specifies w/o requiring its class name e.g."10"  
173          * v.s. "all:10", this is the traditional way to set DEBUGLEVEL 
174          */
175         if (isdigit(params[0][0])) {
176                 debuglevel_class[DBGC_ALL] = atoi(params[0]);
177                 i = 1; /* start processing at the next params */
178         }
179         else
180                 i = 0; /* DBGC_ALL not specified  OR calss name was included */
181
182         /* Fill in new debug class levels */
183         for (; i < DBGC_LAST && params[i]; i++) {
184                 if ((class_name=strtok(params[i],":")) &&
185                         (class_level=strtok(NULL, "\0")) &&
186             ((ndx = debug_lookup_classname(class_name)) != -1)) {
187                                 debuglevel_class[ndx] = atoi(class_level);
188                 } else {
189                         DEBUG(0,("debug_parse_params: unrecognized debug class name or format [%s]\n", params[i]));
190                         return False;
191                 }
192         }
193
194         return True;
195 }
196
197 /****************************************************************************
198 parse the debug levels from smb.conf. Example debug level string:
199   3 tdb:5 printdrivers:7
200 Note: the 1st param has no "name:" preceeding it.
201 ****************************************************************************/
202 BOOL debug_parse_levels(char *params_str)
203 {
204         int  i;
205         char *params[DBGC_LAST];
206         int  debuglevel_class[DBGC_LAST];       
207
208         ZERO_ARRAY(params);
209         ZERO_ARRAY(debuglevel_class);
210
211         if ((params[0]=strtok(params_str," ,"))) {
212                 for (i=1; i<DBGC_LAST;i++) {
213                         if ((params[i]=strtok(NULL," ,"))==NULL)
214                                 break;
215                 }
216         }
217         else
218                 return False;
219
220         if (debug_parse_params(params, debuglevel_class)) {
221                 debug_message(0, getpid(), (void*)debuglevel_class, sizeof(debuglevel_class));
222                 return True;
223         } else
224                 return False;
225 }
226
227 /****************************************************************************
228 receive a "set debug level" message
229 ****************************************************************************/
230 void debug_message(int msg_type, pid_t src, void *buf, size_t len)
231 {
232         int i;
233
234         /* Set the new DEBUGLEVEL_CLASS array from the pased array */
235         memcpy(DEBUGLEVEL_CLASS, buf, sizeof(DEBUGLEVEL_CLASS));
236         
237         DEBUG(1,("INFO: Debug class %s level = %d   (pid %d from pid %d)\n",
238                         classname_table[DBGC_ALL],
239                         DEBUGLEVEL_CLASS[DBGC_ALL], getpid(), (int)src));
240
241         for (i=1; i<DBGC_LAST; i++) {
242                 if (DEBUGLEVEL_CLASS[i])
243                          DEBUGADD(1,("INFO: Debug class %s level = %d\n", 
244                                                 classname_table[i], DEBUGLEVEL_CLASS[i]));
245         }
246 }
247
248
249 /****************************************************************************
250 send a "set debug level" message
251 ****************************************************************************/
252 void debug_message_send(pid_t pid, int level)
253 {
254         message_send_pid(pid, MSG_DEBUG, &level, sizeof(int), False);
255 }
256
257
258 /* ************************************************************************** **
259  * get ready for syslog stuff
260  * ************************************************************************** **
261  */
262 void setup_logging(char *pname, BOOL interactive)
263 {
264         message_register(MSG_DEBUG, debug_message);
265
266         /* reset to allow multiple setup calls, going from interactive to
267            non-interactive */
268         stdout_logging = False;
269         dbf = NULL;
270
271         if (interactive) {
272                 stdout_logging = True;
273                 dbf = stdout;
274         }
275 #ifdef WITH_SYSLOG
276         else {
277                 char *p = strrchr( pname,'/' );
278                 if (p)
279                         pname = p + 1;
280 #ifdef LOG_DAEMON
281                 openlog( pname, LOG_PID, SYSLOG_FACILITY );
282 #else /* for old systems that have no facility codes. */
283                 openlog( pname, LOG_PID );
284 #endif
285         }
286 #endif
287 } /* setup_logging */
288
289 /* ************************************************************************** **
290  * reopen the log files
291  * note that we now do this unconditionally
292  * ************************************************************************** **
293  */
294 void reopen_logs( void )
295 {
296         pstring fname;
297         mode_t oldumask;
298
299         if (DEBUGLEVEL_CLASS[ DBGC_ALL ] <= 0) {
300                 if (dbf) {
301                         (void)fclose(dbf);
302                         dbf = NULL;
303                 }
304                 return;
305         }
306
307         oldumask = umask( 022 );
308   
309         pstrcpy(fname, debugf );
310         if (lp_loaded() && (*lp_logfile()))
311                 pstrcpy(fname, lp_logfile());
312
313         pstrcpy( debugf, fname );
314         if (dbf)
315                 (void)fclose(dbf);
316         if (append_log)
317                 dbf = sys_fopen( debugf, "a" );
318         else
319                 dbf = sys_fopen( debugf, "w" );
320         /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
321          * to fix problem where smbd's that generate less
322          * than 100 messages keep growing the log.
323          */
324         force_check_log_size();
325         if (dbf)
326                 setbuf( dbf, NULL );
327         (void)umask(oldumask);
328 }
329
330
331 /* ************************************************************************** **
332  * Force a check of the log size.
333  * ************************************************************************** **
334  */
335 void force_check_log_size( void )
336 {
337   debug_count = 100;
338 }
339
340 /***************************************************************************
341  Check to see if there is any need to check if the logfile has grown too big.
342 **************************************************************************/
343
344 BOOL need_to_check_log_size( void )
345 {
346         int maxlog;
347
348         if( debug_count++ < 100 )
349                 return( False );
350
351         maxlog = lp_max_log_size() * 1024;
352         if( !dbf || maxlog <= 0 ) {
353                 debug_count = 0;
354                 return(False);
355         }
356         return( True );
357 }
358
359 /* ************************************************************************** **
360  * Check to see if the log has grown to be too big.
361  * ************************************************************************** **
362  */
363
364 void check_log_size( void )
365 {
366   int         maxlog;
367   SMB_STRUCT_STAT st;
368
369   /*
370    *  We need to be root to check/change log-file, skip this and let the main
371    *  loop check do a new check as root.
372    */
373
374   if( geteuid() != 0 )
375     return;
376
377   if( !need_to_check_log_size() )
378     return;
379
380   maxlog = lp_max_log_size() * 1024;
381
382   if( sys_fstat( fileno( dbf ), &st ) == 0 && st.st_size > maxlog )
383     {
384     (void)fclose( dbf );
385     dbf = NULL;
386     reopen_logs();
387     if( dbf && get_file_size( debugf ) > maxlog )
388       {
389       pstring name;
390
391       (void)fclose( dbf );
392       dbf = NULL;
393       slprintf( name, sizeof(name)-1, "%s.old", debugf );
394       (void)rename( debugf, name );
395       reopen_logs();
396       }
397     }
398   /*
399    * Here's where we need to panic if dbf == NULL..
400    */
401   if(dbf == NULL) {
402     dbf = sys_fopen( "/dev/console", "w" );
403     if(dbf) {
404       DEBUG(0,("check_log_size: open of debug file %s failed - using console.\n",
405             debugf ));
406     } else {
407       /*
408        * We cannot continue without a debug file handle.
409        */
410       abort();
411     }
412   }
413   debug_count = 0;
414 } /* check_log_size */
415
416 /* ************************************************************************** **
417  * Write an debug message on the debugfile.
418  * This is called by dbghdr() and format_debug_text().
419  * ************************************************************************** **
420  */
421 #ifdef HAVE_STDARG_H
422  int Debug1( char *format_str, ... )
423 {
424 #else
425  int Debug1(va_alist)
426 va_dcl
427 {  
428   char *format_str;
429 #endif
430   va_list ap;  
431   int old_errno = errno;
432
433   if( stdout_logging )
434     {
435 #ifdef HAVE_STDARG_H
436     va_start( ap, format_str );
437 #else
438     va_start( ap );
439     format_str = va_arg( ap, char * );
440 #endif
441     if(dbf)
442       (void)vfprintf( dbf, format_str, ap );
443     va_end( ap );
444     errno = old_errno;
445     return( 0 );
446     }
447   
448 #ifdef WITH_SYSLOG
449   if( !lp_syslog_only() )
450 #endif
451     {
452     if( !dbf )
453       {
454       mode_t oldumask = umask( 022 );
455
456       if( append_log )
457         dbf = sys_fopen( debugf, "a" );
458       else
459         dbf = sys_fopen( debugf, "w" );
460       (void)umask( oldumask );
461       if( dbf )
462         {
463         setbuf( dbf, NULL );
464         }
465       else
466         {
467         errno = old_errno;
468         return(0);
469         }
470       }
471     }
472
473 #ifdef WITH_SYSLOG
474   if( syslog_level < lp_syslog() )
475     {
476     /* map debug levels to syslog() priorities
477      * note that not all DEBUG(0, ...) calls are
478      * necessarily errors
479      */
480     static int priority_map[] = { 
481       LOG_ERR,     /* 0 */
482       LOG_WARNING, /* 1 */
483       LOG_NOTICE,  /* 2 */
484       LOG_INFO,    /* 3 */
485       };
486     int     priority;
487     pstring msgbuf;
488
489     if( syslog_level >= ( sizeof(priority_map) / sizeof(priority_map[0]) )
490      || syslog_level < 0)
491       priority = LOG_DEBUG;
492     else
493       priority = priority_map[syslog_level];
494       
495 #ifdef HAVE_STDARG_H
496     va_start( ap, format_str );
497 #else
498     va_start( ap );
499     format_str = va_arg( ap, char * );
500 #endif
501     vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
502     va_end( ap );
503       
504     msgbuf[255] = '\0';
505     syslog( priority, "%s", msgbuf );
506     }
507 #endif
508   
509   check_log_size();
510
511 #ifdef WITH_SYSLOG
512   if( !lp_syslog_only() )
513 #endif
514     {
515 #ifdef HAVE_STDARG_H
516     va_start( ap, format_str );
517 #else
518     va_start( ap );
519     format_str = va_arg( ap, char * );
520 #endif
521     if(dbf)
522       (void)vfprintf( dbf, format_str, ap );
523     va_end( ap );
524     if(dbf)
525       (void)fflush( dbf );
526     }
527
528   errno = old_errno;
529
530   return( 0 );
531   } /* Debug1 */
532
533
534 /* ************************************************************************** **
535  * Print the buffer content via Debug1(), then reset the buffer.
536  *
537  *  Input:  none
538  *  Output: none
539  *
540  * ************************************************************************** **
541  */
542 static void bufr_print( void )
543   {
544   format_bufr[format_pos] = '\0';
545   (void)Debug1( "%s", format_bufr );
546   format_pos = 0;
547   } /* bufr_print */
548
549 /* ************************************************************************** **
550  * Format the debug message text.
551  *
552  *  Input:  msg - Text to be added to the "current" debug message text.
553  *
554  *  Output: none.
555  *
556  *  Notes:  The purpose of this is two-fold.  First, each call to syslog()
557  *          (used by Debug1(), see above) generates a new line of syslog
558  *          output.  This is fixed by storing the partial lines until the
559  *          newline character is encountered.  Second, printing the debug
560  *          message lines when a newline is encountered allows us to add
561  *          spaces, thus indenting the body of the message and making it
562  *          more readable.
563  *
564  * ************************************************************************** **
565  */
566 static void format_debug_text( char *msg )
567   {
568   size_t i;
569   BOOL timestamp = (!stdout_logging && (lp_timestamp_logs() || 
570                                         !(lp_loaded())));
571
572   for( i = 0; msg[i]; i++ )
573     {
574     /* Indent two spaces at each new line. */
575     if(timestamp && 0 == format_pos)
576       {
577       format_bufr[0] = format_bufr[1] = ' ';
578       format_pos = 2;
579       }
580
581     /* If there's room, copy the character to the format buffer. */
582     if( format_pos < FORMAT_BUFR_MAX )
583       format_bufr[format_pos++] = msg[i];
584
585     /* If a newline is encountered, print & restart. */
586     if( '\n' == msg[i] )
587       bufr_print();
588
589     /* If the buffer is full dump it out, reset it, and put out a line
590      * continuation indicator.
591      */
592     if( format_pos >= FORMAT_BUFR_MAX )
593       {
594       bufr_print();
595       (void)Debug1( " +>\n" );
596       }
597     }
598
599   /* Just to be safe... */
600   format_bufr[format_pos] = '\0';
601   } /* format_debug_text */
602
603 /* ************************************************************************** **
604  * Flush debug output, including the format buffer content.
605  *
606  *  Input:  none
607  *  Output: none
608  *
609  * ************************************************************************** **
610  */
611 void dbgflush( void )
612   {
613   bufr_print();
614   if(dbf)
615     (void)fflush( dbf );
616   } /* dbgflush */
617
618 /* ************************************************************************** **
619  * Print a Debug Header.
620  *
621  *  Input:  level - Debug level of the message (not the system-wide debug
622  *                  level.
623  *          file  - Pointer to a string containing the name of the file
624  *                  from which this function was called, or an empty string
625  *                  if the __FILE__ macro is not implemented.
626  *          func  - Pointer to a string containing the name of the function
627  *                  from which this function was called, or an empty string
628  *                  if the __FUNCTION__ macro is not implemented.
629  *          line  - line number of the call to dbghdr, assuming __LINE__
630  *                  works.
631  *
632  *  Output: Always True.  This makes it easy to fudge a call to dbghdr()
633  *          in a macro, since the function can be called as part of a test.
634  *          Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
635  *
636  *  Notes:  This function takes care of setting syslog_level.
637  *
638  * ************************************************************************** **
639  */
640
641 BOOL dbghdr( int level, char *file, char *func, int line )
642 {
643   /* Ensure we don't lose any real errno value. */
644   int old_errno = errno;
645
646   if( format_pos ) {
647     /* This is a fudge.  If there is stuff sitting in the format_bufr, then
648      * the *right* thing to do is to call
649      *   format_debug_text( "\n" );
650      * to write the remainder, and then proceed with the new header.
651      * Unfortunately, there are several places in the code at which
652      * the DEBUG() macro is used to build partial lines.  That in mind,
653      * we'll work under the assumption that an incomplete line indicates
654      * that a new header is *not* desired.
655      */
656     return( True );
657   }
658
659 #ifdef WITH_SYSLOG
660   /* Set syslog_level. */
661   syslog_level = level;
662 #endif
663
664   /* Don't print a header if we're logging to stdout. */
665   if( stdout_logging )
666     return( True );
667
668   /* Print the header if timestamps are turned on.  If parameters are
669    * not yet loaded, then default to timestamps on.
670    */
671   if( lp_timestamp_logs() || !(lp_loaded()) ) {
672     char header_str[200];
673
674         header_str[0] = '\0';
675
676         if( lp_debug_pid())
677           slprintf(header_str,sizeof(header_str)-1,", pid=%u",(unsigned int)sys_getpid());
678
679         if( lp_debug_uid()) {
680       size_t hs_len = strlen(header_str);
681           slprintf(header_str + hs_len,
682                sizeof(header_str) - 1 - hs_len,
683                            ", effective(%u, %u), real(%u, %u)",
684                (unsigned int)geteuid(), (unsigned int)getegid(),
685                            (unsigned int)getuid(), (unsigned int)getgid()); 
686         }
687   
688     /* Print it all out at once to prevent split syslog output. */
689     (void)Debug1( "[%s, %d%s] %s:%s(%d)\n",
690                   timestring(lp_debug_hires_timestamp()), level,
691                                   header_str, file, func, line );
692   }
693
694   errno = old_errno;
695   return( True );
696 }
697
698 /* ************************************************************************** **
699  * Add text to the body of the "current" debug message via the format buffer.
700  *
701  *  Input:  format_str  - Format string, as used in printf(), et. al.
702  *          ...         - Variable argument list.
703  *
704  *  ..or..  va_alist    - Old style variable parameter list starting point.
705  *
706  *  Output: Always True.  See dbghdr() for more info, though this is not
707  *          likely to be used in the same way.
708  *
709  * ************************************************************************** **
710  */
711 #ifdef HAVE_STDARG_H
712  BOOL dbgtext( char *format_str, ... )
713   {
714   va_list ap;
715   pstring msgbuf;
716
717   va_start( ap, format_str ); 
718   vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
719   va_end( ap );
720
721   format_debug_text( msgbuf );
722
723   return( True );
724   } /* dbgtext */
725
726 #else
727  BOOL dbgtext( va_alist )
728  va_dcl
729   {
730   char *format_str;
731   va_list ap;
732   pstring msgbuf;
733
734   va_start( ap );
735   format_str = va_arg( ap, char * );
736   vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
737   va_end( ap );
738
739   format_debug_text( msgbuf );
740
741   return( True );
742   } /* dbgtext */
743
744 #endif
745
746 /* ************************************************************************** */