Fix ndrdump to use a common setup_logging() API
[ira/wip.git] / source3 / lib / debug.c
index fc7b1d67f6230c666b494796d14f787599754806..e7dcfb4fdf3f6b2e887224a7055f00612f5016b1 100644 (file)
@@ -29,7 +29,8 @@
  *                    for a terminating null byte.
  */
 
-#define FORMAT_BUFR_MAX ( sizeof( format_bufr ) - 1 )
+#define FORMAT_BUFR_SIZE 1024
+#define FORMAT_BUFR_MAX (FORMAT_BUFR_SIZE - 1)
 
 /* -------------------------------------------------------------------------- **
  * This module implements Samba's debugging utility.
  */
 
 XFILE   *dbf        = NULL;
-pstring debugf     = "";
-BOOL    debug_warn_unknown_class = True;
-BOOL    debug_auto_add_unknown_class = True;
-BOOL    AllowDebugChange = True;
-
-/* 
-   used to check if the user specified a 
-   logfile on the command line 
+static char *debugf = NULL;
+bool    debug_warn_unknown_class = True;
+bool    debug_auto_add_unknown_class = True;
+bool    AllowDebugChange = True;
+
+/*
+   used to check if the user specified a
+   logfile on the command line
 */
-BOOL    override_logfile;              
+bool    override_logfile;
 
+static TALLOC_CTX *tmp_debug_ctx;
 
 /*
  * This is to allow assignment to DEBUGLEVEL before the debug
- * system has been initialised.
+ * system has been initialized.
  */
 static int debug_all_class_hack = 1;
-static BOOL debug_all_class_isset_hack = True;
+static bool debug_all_class_isset_hack = True;
 
 static int debug_num_classes = 0;
 int     *DEBUGLEVEL_CLASS = &debug_all_class_hack;
-BOOL    *DEBUGLEVEL_CLASS_ISSET = &debug_all_class_isset_hack;
+bool    *DEBUGLEVEL_CLASS_ISSET = &debug_all_class_isset_hack;
 
 /* DEBUGLEVEL is #defined to *debug_level */
 int     DEBUGLEVEL = &debug_all_class_hack;
@@ -132,14 +134,14 @@ int     DEBUGLEVEL = &debug_all_class_hack;
  *                    are unable to open a new log file for some reason.
  */
 
-static BOOL    stdout_logging = False;
+static bool    stdout_logging = False;
 static int     debug_count    = 0;
 #ifdef WITH_SYSLOG
 static int     syslog_level   = 0;
 #endif
-static pstring format_bufr    = { '\0' };
+static char *format_bufr = NULL;
 static size_t     format_pos     = 0;
-static BOOL    log_overflow   = False;
+static bool    log_overflow   = False;
 
 /*
  * Define all the debug class selection names here. Names *MUST NOT* contain 
@@ -181,6 +183,8 @@ static char **classname_table = NULL;
  Free memory pointed to by global pointers.
 ****************************************************************************/
 
+static bool initialized;
+
 void gfree_debugsyms(void)
 {
        int i;
@@ -192,11 +196,23 @@ void gfree_debugsyms(void)
                SAFE_FREE( classname_table );
        }
 
-       if ( DEBUGLEVEL_CLASS != &debug_all_class_hack )
+       if ( DEBUGLEVEL_CLASS != &debug_all_class_hack ) {
                SAFE_FREE( DEBUGLEVEL_CLASS );
+               DEBUGLEVEL_CLASS = &debug_all_class_hack;
+       }
 
-       if ( DEBUGLEVEL_CLASS_ISSET != &debug_all_class_isset_hack )
+       if ( DEBUGLEVEL_CLASS_ISSET != &debug_all_class_isset_hack ) {
                SAFE_FREE( DEBUGLEVEL_CLASS_ISSET );
+               DEBUGLEVEL_CLASS_ISSET = &debug_all_class_isset_hack;
+       }
+
+       SAFE_FREE(format_bufr);
+
+       debug_num_classes = 0;
+
+       debug_level = DEBUGLEVEL_CLASS;
+
+       initialized = false;
 }
 
 /****************************************************************************
@@ -211,7 +227,7 @@ static char *debug_list_class_names_and_levels(void)
        char **list;
        char *buf = NULL;
        char *b;
-       BOOL err = False;
+       bool err = False;
 
        if (DEBUGLEVEL_CLASS == &debug_all_class_hack) {
                return NULL;
@@ -334,10 +350,10 @@ int debug_add_class(const char *classname)
        if (new_ptr == &debug_all_class_isset_hack) {
                new_ptr = NULL;
        }
-       new_ptr = SMB_REALLOC_ARRAY(new_ptr, BOOL, debug_num_classes + 1);
+       new_ptr = SMB_REALLOC_ARRAY(new_ptr, bool, debug_num_classes + 1);
        if (!new_ptr)
                return -1;
-       DEBUGLEVEL_CLASS_ISSET = (int *)new_ptr;
+       DEBUGLEVEL_CLASS_ISSET = (bool *)new_ptr;
        DEBUGLEVEL_CLASS_ISSET[ndx] = False;
 
        new_ptr = SMB_REALLOC_ARRAY(classname_table, char *, debug_num_classes + 1);
@@ -403,7 +419,7 @@ static void debug_dump_status(int level)
  printdrivers:7
 ****************************************************************************/
 
-static BOOL debug_parse_params(char **params)
+static bool debug_parse_params(char **params)
 {
        int   i, ndx;
        char *class_name;
@@ -425,8 +441,9 @@ static BOOL debug_parse_params(char **params)
 
        /* Fill in new debug class levels */
        for (; i < debug_num_classes && params[i]; i++) {
-               if ((class_name=strtok(params[i],":")) &&
-                       (class_level=strtok(NULL, "\0")) &&
+               char *saveptr;
+               if ((class_name = strtok_r(params[i],":", &saveptr)) &&
+                       (class_level = strtok_r(NULL, "\0", &saveptr)) &&
             ((ndx = debug_lookup_classname(class_name)) != -1)) {
                                DEBUGLEVEL_CLASS[ndx] = atoi(class_level);
                                DEBUGLEVEL_CLASS_ISSET[ndx] = True;
@@ -445,7 +462,7 @@ static BOOL debug_parse_params(char **params)
  Note: the 1st param has no "name:" preceeding it.
 ****************************************************************************/
 
-BOOL debug_parse_levels(const char *params_str)
+bool debug_parse_levels(const char *params_str)
 {
        char **params;
 
@@ -455,14 +472,14 @@ BOOL debug_parse_levels(const char *params_str)
        if (AllowDebugChange == False)
                return True;
 
-       params = str_list_make(params_str, NULL);
+       params = str_list_make_v3(talloc_tos(), params_str, NULL);
 
        if (debug_parse_params(params)) {
                debug_dump_status(5);
-               str_list_free(&params);
+               TALLOC_FREE(params);
                return True;
        } else {
-               str_list_free(&params);
+               TALLOC_FREE(params);
                return False;
        }
 }
@@ -471,7 +488,7 @@ BOOL debug_parse_levels(const char *params_str)
  Receive a "set debug level" message.
 ****************************************************************************/
 
-static void debug_message(struct messaging_context *msg_ctx,
+void debug_message(struct messaging_context *msg_ctx,
                          void *private_data, 
                          uint32_t msg_type, 
                          struct server_id src,
@@ -525,17 +542,20 @@ Init debugging (one time stuff)
 
 void debug_init(void)
 {
-       static BOOL initialised = False;
        const char **p;
 
-       if (initialised)
+       if (initialized)
                return;
 
-       initialised = True;
+       initialized = true;
 
        for(p = default_classname_table; *p; p++) {
                debug_add_class(*p);
        }
+       format_bufr = (char *)SMB_MALLOC(FORMAT_BUFR_SIZE);
+       if (!format_bufr) {
+               smb_panic("debug_init: unable to create buffer");
+       }
 }
 
 void debug_register_msgs(struct messaging_context *msg_ctx)
@@ -549,7 +569,7 @@ void debug_register_msgs(struct messaging_context *msg_ctx)
  Get ready for syslog stuff
 **************************************************************************/
 
-void setup_logging(const char *pname, BOOL interactive)
+void setup_logging(const char *pname, bool interactive)
 {
        debug_init();
 
@@ -558,7 +578,9 @@ void setup_logging(const char *pname, BOOL interactive)
        stdout_logging = False;
        if (dbf) {
                x_fflush(dbf);
-               (void) x_fclose(dbf);
+                if (dbf != x_stdout) {
+                        (void) x_fclose(dbf);
+                }
        }
 
        dbf = NULL;
@@ -583,6 +605,25 @@ void setup_logging(const char *pname, BOOL interactive)
 #endif
 }
 
+/**
+   Just run logging to stdout for this program 
+*/
+_PUBLIC_ void setup_logging_stdout(void)
+{
+       setup_logging(NULL, True);
+}
+
+
+/***************************************************************************
+ Set the logfile name.
+**************************************************************************/
+
+void debug_set_logfile(const char *name)
+{
+       SAFE_FREE(debugf);
+       debugf = SMB_STRDUP(name);
+}
+
 /**************************************************************************
  reopen the log files
  note that we now do this unconditionally
@@ -591,31 +632,39 @@ void setup_logging(const char *pname, BOOL interactive)
  Fix from dgibson@linuxcare.com.
 **************************************************************************/
 
-BOOL reopen_logs( void )
+bool reopen_logs( void )
 {
-       pstring fname;
+       char *fname = NULL;
        mode_t oldumask;
        XFILE *new_dbf = NULL;
        XFILE *old_dbf = NULL;
-       BOOL ret = True;
+       bool ret = True;
 
        if (stdout_logging)
                return True;
 
        oldumask = umask( 022 );
-  
-       pstrcpy(fname, debugf );
-       debugf[0] = '\0';
+
+       fname = debugf;
+       if (!fname) {
+               return false;
+       }
+       debugf = NULL;
 
        if (lp_loaded()) {
                char *logfname;
 
                logfname = lp_logfile();
-               if (*logfname)
-                       pstrcpy(fname, logfname);
+               if (*logfname) {
+                       SAFE_FREE(fname);
+                       fname = SMB_STRDUP(logfname);
+                       if (!fname) {
+                               return false;
+                       }
+               }
        }
 
-       pstrcpy( debugf, fname );
+       debugf = fname;
        new_dbf = x_fopen( debugf, O_WRONLY|O_APPEND|O_CREAT, 0644);
 
        if (!new_dbf) {
@@ -640,8 +689,8 @@ BOOL reopen_logs( void )
        force_check_log_size();
        (void)umask(oldumask);
 
-       /* Take over stderr to catch ouput into logs */
-       if (dbf && sys_dup2(x_fileno(dbf), 2) == -1) {
+       /* Take over stderr to catch output into logs */
+       if (dbf && dup2(x_fileno(dbf), 2) == -1) {
                close_low_fds(True); /* Close stderr too, if dup2 can't point it
                                        at the logfile */
        }
@@ -662,7 +711,7 @@ void force_check_log_size( void )
  Check to see if there is any need to check if the logfile has grown too big.
 **************************************************************************/
 
-BOOL need_to_check_log_size( void )
+bool need_to_check_log_size( void )
 {
        int maxlog;
 
@@ -699,18 +748,21 @@ void check_log_size( void )
 
        maxlog = lp_max_log_size() * 1024;
 
-       if( sys_fstat( x_fileno( dbf ), &st ) == 0 && st.st_size > maxlog ) {
+       if( sys_fstat( x_fileno( dbf ), &st ) == 0 && st.st_ex_size > maxlog ) {
                (void)reopen_logs();
                if( dbf && get_file_size( debugf ) > maxlog ) {
-                       pstring name;
+                       char *name = NULL;
+
+                       if (asprintf(&name, "%s.old", debugf ) < 0) {
+                               return;
+                       }
+                       (void)rename(debugf, name);
 
-                       slprintf( name, sizeof(name)-1, "%s.old", debugf );
-                       (void)rename( debugf, name );
-      
                        if (!reopen_logs()) {
                                /* We failed to reopen a log - continue using the old name. */
                                (void)rename(name, debugf);
                        }
+                       SAFE_FREE(name);
                }
        }
 
@@ -747,7 +799,7 @@ void check_log_size( void )
 
  int Debug1( const char *format_str, ... )
 {
-       va_list ap;  
+       va_list ap;
        int old_errno = errno;
 
        debug_count++;
@@ -758,13 +810,13 @@ void check_log_size( void )
                        (void)x_vfprintf( dbf, format_str, ap );
                va_end( ap );
                errno = old_errno;
-               return( 0 );
+               goto done;
        }
 
        /* prevent recursion by checking if reopen_logs() has temporaily
-          set the debugf string to "" */
-       if( debugf[0] == '\0')
-               return( 0 );
+          set the debugf string to NULL */
+       if( debugf == NULL)
+               goto done;
 
 #ifdef WITH_SYSLOG
        if( !lp_syslog_only() )
@@ -779,7 +831,7 @@ void check_log_size( void )
                                x_setbuf( dbf, NULL );
                        } else {
                                errno = old_errno;
-                               return(0);
+                               goto done;
                        }
                }
        }
@@ -789,29 +841,32 @@ void check_log_size( void )
                /* map debug levels to syslog() priorities
                 * note that not all DEBUG(0, ...) calls are
                 * necessarily errors */
-               static int priority_map[] = { 
+               static const int priority_map[4] = {
                        LOG_ERR,     /* 0 */
                        LOG_WARNING, /* 1 */
                        LOG_NOTICE,  /* 2 */
                        LOG_INFO,    /* 3 */
                };
                int     priority;
-               pstring msgbuf;
+               char *msgbuf = NULL;
+               int ret;
 
-               if( syslog_level >= ( sizeof(priority_map) / sizeof(priority_map[0]) ) || syslog_level < 0)
+               if( syslog_level >= ARRAY_SIZE(priority_map) || syslog_level < 0)
                        priority = LOG_DEBUG;
                else
                        priority = priority_map[syslog_level];
 
-               va_start( ap, format_str );
-               vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
-               va_end( ap );
+               va_start(ap, format_str);
+               ret = vasprintf(&msgbuf, format_str, ap);
+               va_end(ap);
 
-               msgbuf[255] = '\0';
-               syslog( priority, "%s", msgbuf );
+               if (ret != -1) {
+                       syslog(priority, "%s", msgbuf);
+               }
+               SAFE_FREE(msgbuf);
        }
 #endif
-  
+
        check_log_size();
 
 #ifdef WITH_SYSLOG
@@ -826,6 +881,9 @@ void check_log_size( void )
                        (void)x_fflush( dbf );
        }
 
+ done:
+       TALLOC_FREE(tmp_debug_ctx);
+
        errno = old_errno;
 
        return( 0 );
@@ -864,7 +922,11 @@ static void bufr_print( void )
 static void format_debug_text( const char *msg )
 {
        size_t i;
-       BOOL timestamp = (!stdout_logging && (lp_timestamp_logs() || !(lp_loaded())));
+       bool timestamp = (!stdout_logging && (lp_timestamp_logs() || !(lp_loaded())));
+
+       if (!format_bufr) {
+               debug_init();
+       }
 
        for( i = 0; msg[i]; i++ ) {
                /* Indent two spaces at each new line. */
@@ -913,6 +975,7 @@ void dbgflush( void )
 
  Input:  level - Debug level of the message (not the system-wide debug
                   level. )
+         cls   - Debuglevel class of the calling module.
           file  - Pointer to a string containing the name of the file
                   from which this function was called, or an empty string
                   if the __FILE__ macro is not implemented.
@@ -930,7 +993,7 @@ void dbgflush( void )
 
 ****************************************************************************/
 
-BOOL dbghdr( int level, const char *file, const char *func, int line )
+bool dbghdrclass(int level, int cls, const char *location, const char *func)
 {
        /* Ensure we don't lose any real errno value. */
        int old_errno = errno;
@@ -976,16 +1039,26 @@ BOOL dbghdr( int level, const char *file, const char *func, int line )
                                (unsigned int)geteuid(), (unsigned int)getegid(),
                                (unsigned int)getuid(), (unsigned int)getgid()); 
                }
+
+               if (lp_debug_class() && (cls != DBGC_ALL)) {
+                       size_t hs_len = strlen(header_str);
+                       slprintf(header_str + hs_len,
+                                sizeof(header_str) -1 - hs_len,
+                                ", class=%s",
+                                default_classname_table[cls]);
+               }
   
                /* Print it all out at once to prevent split syslog output. */
                if( lp_debug_prefix_timestamp() ) {
                    (void)Debug1( "[%s, %2d%s] ",
-                       current_timestring(lp_debug_hires_timestamp()), level,
-                       header_str);
+                       current_timestring(debug_ctx(),
+                                          lp_debug_hires_timestamp()),
+                       level, header_str);
                } else {
-                   (void)Debug1( "[%s, %2d%s] %s:%s(%d)\n",
-                       current_timestring(lp_debug_hires_timestamp()), level,
-                       header_str, file, func, line );
+                   (void)Debug1( "[%s, %2d%s] %s(%s)\n",
+                       current_timestring(debug_ctx(),
+                                          lp_debug_hires_timestamp()),
+                       level, header_str, location, func );
                }
        }
 
@@ -993,6 +1066,12 @@ BOOL dbghdr( int level, const char *file, const char *func, int line )
        return( True );
 }
 
+bool dbghdr(int level, const char *location, const char *func)
+{
+       /* For compatibility with Samba 4, which doesn't have debug classes */
+       return dbghdrclass(level, 0, location, func);
+}
+
 /***************************************************************************
  Add text to the body of the "current" debug message via the format buffer.
 
@@ -1006,16 +1085,33 @@ BOOL dbghdr( int level, const char *file, const char *func, int line )
 
 ***************************************************************************/
 
BOOL dbgtext( const char *format_str, ... )
bool dbgtext( const char *format_str, ... )
 {
        va_list ap;
-       pstring msgbuf;
+       char *msgbuf = NULL;
+       bool ret = true;
+       int res;
 
-       va_start( ap, format_str ); 
-       vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
-       va_end( ap );
+       va_start(ap, format_str);
+       res = vasprintf(&msgbuf, format_str, ap);
+       va_end(ap);
 
-       format_debug_text( msgbuf );
+       if (res != -1) {
+               format_debug_text(msgbuf);
+       } else {
+               ret = false;
+       }
+       SAFE_FREE(msgbuf);
+       return ret;
+}
 
-  return( True );
+/*
+ * Get us a temporary talloc context usable just for DEBUG arguments
+ */
+TALLOC_CTX *debug_ctx(void)
+{
+        if (tmp_debug_ctx == NULL) {
+                tmp_debug_ctx = talloc_named_const(NULL, 0, "debug_ctx");
+        }
+        return tmp_debug_ctx;
 }