Removed version number from file header.
[kai/samba.git] / source3 / lib / debug.c
index 3a90da2f3d2a9c41d027947277cf7100e671f8ac..87a8d429994b149e58d9ea3625692053f30f8254 100644 (file)
@@ -1,6 +1,5 @@
 /*
-   Unix SMB/Netbios implementation.
-   Version 1.9.
+   Unix SMB/CIFS implementation.
    Samba utility functions
    Copyright (C) Andrew Tridgell 1992-1998
 
@@ -26,7 +25,7 @@
  *
  *  FORMAT_BUFR_MAX - Index of the last byte of the format buffer;
  *                    format_bufr[FORMAT_BUFR_MAX] should always be reserved
- *                    for a terminating nul byte.
+ *                    for a terminating null byte.
  */
 
 #define FORMAT_BUFR_MAX ( sizeof( format_bufr ) - 1 )
  *  debugf        - Debug file name.
  *  append_log    - If True, then the output file will be opened in append
  *                  mode.
- *  timestamp_log - 
  *  DEBUGLEVEL    - System-wide debug message limit.  Messages with message-
  *                  levels higher than DEBUGLEVEL will not be processed.
  */
 
-FILE   *dbf        = NULL;
+XFILE   *dbf        = NULL;
 pstring debugf     = "";
 BOOL    append_log = False;
-BOOL    timestamp_log = True;
-int     DEBUGLEVEL = 1;
+
+int     DEBUGLEVEL_CLASS[DBGC_LAST];
+BOOL    DEBUGLEVEL_CLASS_ISSET[DBGC_LAST];
+int     DEBUGLEVEL = DEBUGLEVEL_CLASS;
+BOOL   AllowDebugChange = True;
 
 
 /* -------------------------------------------------------------------------- **
@@ -106,6 +107,12 @@ int     DEBUGLEVEL = 1;
  *                    to build the formatted output.
  *
  *  format_pos      - Marks the first free byte of the format_bufr.
+ * 
+ *
+ *  log_overflow    - When this variable is True, never attempt to check the
+ *                    size of the log. This is a hack, so that we can write
+ *                    a message using DEBUG, from open_logs() when we
+ *                    are unable to open a new log file for some reason.
  */
 
 static BOOL    stdout_logging = False;
@@ -114,209 +121,380 @@ static int     debug_count    = 0;
 static int     syslog_level   = 0;
 #endif
 static pstring format_bufr    = { '\0' };
-static int     format_pos     = 0;
+static size_t     format_pos     = 0;
+static BOOL    log_overflow   = False;
+
+/*
+ * Define all the debug class selection names here. Names *MUST NOT* contain 
+ * white space. There must be one name for each DBGC_<class name>, and they 
+ * must be in the table in the order of DBGC_<class name>.. 
+ */
+char *classname_table[] = {
+       "all",               /* DBGC_ALL; index refs traditional DEBUGLEVEL */
+       "tdb",               /* DBGC_TDB          */
+       "printdrivers",      /* DBGC_PRINTDRIVERS */
+       "lanman",            /* DBGC_LANMAN       */
+       "smb",               /* DBGC_SMB          */
+       "rpc",               /* DBGC_RPC          */
+       "rpc_hdr",           /* DBGC_RPC_HDR      */
+       "bdc",               /* DBGC_BDC          */
+};
 
 
 /* -------------------------------------------------------------------------- **
  * Functions...
  */
 
-/* ************************************************************************** **
- * tells us if interactive logging was requested
- * ************************************************************************** **
- */
-
-BOOL dbg_interactive(void)
+/****************************************************************************
+utility access to debug class names's
+****************************************************************************/
+char* debug_classname_from_index(int ndx)
 {
-       return stdout_logging;
+       return classname_table[ndx];
 }
 
-#if defined(SIGUSR2) && !defined(MEM_MAN)
-/* ************************************************************************** **
- * catch a sigusr2 - decrease the debug log level.
- * ************************************************************************** **
- */
-void sig_usr2( int sig )
-  {
-  BlockSignals( True, SIGUSR2 );
-
-  DEBUGLEVEL--;
-  if( DEBUGLEVEL < 0 )
-    DEBUGLEVEL = 0;
-
-  DEBUG( 0, ( "Got SIGUSR2; set debug level to %d.\n", DEBUGLEVEL ) );
-
-  BlockSignals( False, SIGUSR2 );
-  CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
+/****************************************************************************
+utility to translate names to debug class index's
+****************************************************************************/
+int debug_lookup_classname(char* classname)
+{
+       int i;
 
-  } /* sig_usr2 */
-#endif /* SIGUSR2 */
+       if (!classname) return -1;
 
-#if defined(SIGUSR1) && !defined(MEM_MAN)
-/* ************************************************************************** **
- * catch a sigusr1 - increase the debug log level. 
- * ************************************************************************** **
- */
-void sig_usr1( int sig )
-  {
-  BlockSignals( True, SIGUSR1 );
+       for (i=0; i<DBGC_LAST; i++) {
+               if (strcmp(classname, classname_table[i])==0)
+                       return i;
+       }
+       return -1;
+}
 
-  DEBUGLEVEL++;
+/****************************************************************************
+parse the debug levels from smbcontrol. Example debug level parameter:
+  printdrivers:7
+****************************************************************************/
+BOOL debug_parse_params(char **params, int *debuglevel_class,
+                       BOOL *debuglevel_class_isset)
+{
+       int   i, ndx;
+       char *class_name;
+       char *class_level;
+       
+       /* Set the new debug level array to the current DEBUGLEVEL array */
+       memcpy(debuglevel_class, DEBUGLEVEL_CLASS, sizeof(DEBUGLEVEL_CLASS));
+
+       /* Allow DBGC_ALL to be specified w/o requiring its class name e.g."10"  
+        * v.s. "all:10", this is the traditional way to set DEBUGLEVEL 
+        */
+       if (isdigit((int)params[0][0])) {
+               debuglevel_class[DBGC_ALL] = atoi(params[0]);
+               debuglevel_class_isset[DBGC_ALL] = True;
+               i = 1; /* start processing at the next params */
+       }
+       else
+               i = 0; /* DBGC_ALL not specified OR class name was included */
+
+       /* Fill in new debug class levels */
+       for (; i < DBGC_LAST && params[i]; i++) {
+               if ((class_name=strtok(params[i],":")) &&
+                       (class_level=strtok(NULL, "\0")) &&
+            ((ndx = debug_lookup_classname(class_name)) != -1)) {
+                               debuglevel_class[ndx] = atoi(class_level);
+                               debuglevel_class_isset[ndx] = True;
+               } else {
+                       DEBUG(0,("debug_parse_params: unrecognized debug class name or format [%s]\n", params[i]));
+                       return False;
+               }
+       }
+
+       return True;
+}
 
-  if( DEBUGLEVEL > 10 )
-    DEBUGLEVEL = 10;
+/****************************************************************************
+parse the debug levels from smb.conf. Example debug level string:
+  3 tdb:5 printdrivers:7
+Note: the 1st param has no "name:" preceeding it.
+****************************************************************************/
+BOOL debug_parse_levels(char *params_str)
+{
+       int  i;
+       char *params[DBGC_LAST];
+       int  debuglevel_class[DBGC_LAST];       
+       BOOL debuglevel_class_isset[DBGC_LAST];
+
+       if (AllowDebugChange == False)
+               return True;
+       ZERO_ARRAY(params);
+       ZERO_ARRAY(debuglevel_class);
+       ZERO_ARRAY(debuglevel_class_isset);
+
+       if ((params[0]=strtok(params_str," ,"))) {
+               for (i=1; i<DBGC_LAST;i++) {
+                       if ((params[i]=strtok(NULL," ,"))==NULL)
+                               break;
+               }
+       }
+       else
+               return False;
+
+       if (debug_parse_params(params, debuglevel_class, 
+                              debuglevel_class_isset)) {
+               debug_message(0, getpid(), (void*)debuglevel_class, sizeof(debuglevel_class));
+
+               memcpy(DEBUGLEVEL_CLASS, debuglevel_class, 
+                      sizeof(debuglevel_class));
+
+               memcpy(DEBUGLEVEL_CLASS_ISSET, debuglevel_class_isset,
+                      sizeof(debuglevel_class_isset));
+
+               {
+                       int q;
+
+                       for (q = 0; q < DBGC_LAST; q++)
+                               DEBUG(5, ("%s: %d/%d\n",
+                                         classname_table[q],
+                                         DEBUGLEVEL_CLASS[q],
+                                         DEBUGLEVEL_CLASS_ISSET[q]));
+               }
+
+               return True;
+       } else
+               return False;
+}
 
-  DEBUG( 0, ( "Got SIGUSR1; set debug level to %d.\n", DEBUGLEVEL ) );
+/****************************************************************************
+receive a "set debug level" message
+****************************************************************************/
+void debug_message(int msg_type, pid_t src, void *buf, size_t len)
+{
+       struct debuglevel_message *dm = (struct debuglevel_message *)buf;
+       int i;
+
+       /* Set the new DEBUGLEVEL_CLASS array from the passed message */
+       memcpy(DEBUGLEVEL_CLASS, dm->debuglevel_class, sizeof(dm->debuglevel_class));
+       memcpy(DEBUGLEVEL_CLASS_ISSET, dm->debuglevel_class_isset, sizeof(dm->debuglevel_class_isset));
+
+       DEBUG(3,("INFO: Debug class %s level = %d   (pid %u from pid %u)\n",
+                       classname_table[DBGC_ALL],
+                       DEBUGLEVEL_CLASS[DBGC_ALL], (unsigned int)getpid(), (unsigned int)src));
+
+       for (i=1; i<DBGC_LAST; i++) {
+               if (DEBUGLEVEL_CLASS[i])
+                        DEBUGADD(3,("INFO: Debug class %s level = %d\n", 
+                                               classname_table[i], DEBUGLEVEL_CLASS[i]));
+       }
+}
 
-  BlockSignals( False, SIGUSR1 );
-  CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
 
-  } /* sig_usr1 */
-#endif /* SIGUSR1 */
+/****************************************************************************
+send a "set debug level" message
+****************************************************************************/
+void debug_message_send(pid_t pid, int level)
+{
+       message_send_pid(pid, MSG_DEBUG, &level, sizeof(int), False);
+}
 
 
 /* ************************************************************************** **
  * get ready for syslog stuff
  * ************************************************************************** **
  */
-void setup_logging( char *pname, BOOL interactive )
-  {
-  if( interactive )
-    {
-    stdout_logging = True;
-    dbf = stdout;
-    }
-#ifdef WITH_SYSLOG
-  else
-    {
-    char *p = strrchr( pname,'/' );
+void setup_logging(char *pname, BOOL interactive)
+{
+       message_register(MSG_DEBUG, debug_message);
 
-    if( p )
-      pname = p + 1;
+       /* reset to allow multiple setup calls, going from interactive to
+          non-interactive */
+       stdout_logging = False;
+       dbf = NULL;
+
+       if (interactive) {
+               stdout_logging = True;
+               dbf = x_stdout;
+       }
+#ifdef WITH_SYSLOG
+       else {
+               char *p = strrchr_m( pname,'/' );
+               if (p)
+                       pname = p + 1;
 #ifdef LOG_DAEMON
-    openlog( pname, LOG_PID, SYSLOG_FACILITY );
-#else /* for old systems that have no facility codes. */
-    openlog( pname, LOG_PID );
+               openlog( pname, LOG_PID, SYSLOG_FACILITY );
+#else
+               /* for old systems that have no facility codes. */
+               openlog( pname, LOG_PID );
 #endif
-    }
+       }
 #endif
-  } /* setup_logging */
+} /* setup_logging */
 
 /* ************************************************************************** **
  * reopen the log files
+ * note that we now do this unconditionally
+ * We attempt to open the new debug fp before closing the old. This means
+ * if we run out of fd's we just keep using the old fd rather than aborting.
+ * Fix from dgibson@linuxcare.com.
  * ************************************************************************** **
  */
-void reopen_logs( void )
-  {
-  pstring fname;
-  
-  if( DEBUGLEVEL > 0 )
-    {
-    pstrcpy( fname, debugf );
-    if( lp_loaded() && (*lp_logfile()) )
-      pstrcpy( fname, lp_logfile() );
 
-    if( !strcsequal( fname, debugf ) || !dbf || !file_exist( debugf, NULL ) )
-      {
-      mode_t oldumask = umask( 022 );
+BOOL reopen_logs( void )
+{
+       pstring fname;
+       mode_t oldumask;
+       XFILE *new_dbf = NULL;
+       BOOL ret = True;
 
-      pstrcpy( debugf, fname );
-      if( dbf )
-        (void)fclose( dbf );
-      if( append_log )
-        dbf = sys_fopen( debugf, "a" );
-      else
-        dbf = sys_fopen( debugf, "w" );
-      /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
-       * to fix problem where smbd's that generate less
-       * than 100 messages keep growing the log.
-       */
-      force_check_log_size();
-      if( dbf )
-        setbuf( dbf, NULL );
-      (void)umask( oldumask );
-      }
-    }
-  else
-    {
-    if( dbf )
-      {
-      (void)fclose( dbf );
-      dbf = NULL;
-      }
-    }
-  } /* reopen_logs */
+       if (stdout_logging)
+               return True;
+
+       oldumask = umask( 022 );
+  
+       pstrcpy(fname, debugf );
+
+       if (lp_loaded()) {
+               char *logfname;
+
+               logfname = lp_logfile();
+               if (*logfname)
+                       pstrcpy(fname, logfname);
+       }
+
+       pstrcpy( debugf, fname );
+       if (append_log)
+               new_dbf = x_fopen( debugf, O_WRONLY|O_APPEND|O_CREAT, 0644);
+       else
+               new_dbf = x_fopen( debugf, O_WRONLY|O_CREAT|O_TRUNC, 0644 );
+
+       if (!new_dbf) {
+               log_overflow = True;
+               DEBUG(0, ("Unable to open new log file %s: %s\n", debugf, strerror(errno)));
+               log_overflow = False;
+               if (dbf)
+                       x_fflush(dbf);
+               ret = False;
+       } else {
+               x_setbuf(new_dbf, NULL);
+               if (dbf)
+                       (void) x_fclose(dbf);
+               dbf = new_dbf;
+       }
+
+       /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
+        * to fix problem where smbd's that generate less
+        * than 100 messages keep growing the log.
+        */
+       force_check_log_size();
+       (void)umask(oldumask);
+
+       return ret;
+}
 
 /* ************************************************************************** **
  * Force a check of the log size.
  * ************************************************************************** **
  */
 void force_check_log_size( void )
-  {
+{
   debug_count = 100;
-  } /* force_check_log_size */
+}
+
+/***************************************************************************
+ Check to see if there is any need to check if the logfile has grown too big.
+**************************************************************************/
+
+BOOL need_to_check_log_size( void )
+{
+       int maxlog;
+
+       if( debug_count++ < 100 )
+               return( False );
+
+       maxlog = lp_max_log_size() * 1024;
+       if( !dbf || maxlog <= 0 ) {
+               debug_count = 0;
+               return(False);
+       }
+       return( True );
+}
 
 /* ************************************************************************** **
  * Check to see if the log has grown to be too big.
  * ************************************************************************** **
  */
-static void check_log_size( void )
-  {
-  int         maxlog;
-  SMB_STRUCT_STAT st;
 
-  if( debug_count++ < 100 || getuid() != 0 )
-    return;
+void check_log_size( void )
+{
+       int         maxlog;
+       SMB_STRUCT_STAT st;
 
-  maxlog = lp_max_log_size() * 1024;
-  if( !dbf || maxlog <= 0 )
-    return;
+       /*
+        *  We need to be root to check/change log-file, skip this and let the main
+        *  loop check do a new check as root.
+        */
 
-  if( sys_fstat( fileno( dbf ), &st ) == 0 && st.st_size > maxlog )
-    {
-    (void)fclose( dbf );
-    dbf = NULL;
-    reopen_logs();
-    if( dbf && file_size( debugf ) > maxlog )
-      {
-      pstring name;
+       if( geteuid() != 0 )
+               return;
 
-      (void)fclose( dbf );
-      dbf = NULL;
-      slprintf( name, sizeof(name)-1, "%s.old", debugf );
-      (void)rename( debugf, name );
-      reopen_logs();
-      }
-    }
-  debug_count = 0;
-  } /* check_log_size */
+       if(log_overflow || !need_to_check_log_size() )
+               return;
+
+       maxlog = lp_max_log_size() * 1024;
+
+       if( sys_fstat( x_fileno( dbf ), &st ) == 0 && st.st_size > maxlog ) {
+               (void)reopen_logs();
+               if( dbf && get_file_size( debugf ) > maxlog ) {
+                       pstring 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);
+                       }
+               }
+       }
+
+       /*
+        * Here's where we need to panic if dbf == NULL..
+        */
+
+       if(dbf == NULL) {
+               /* This code should only be reached in very strange
+                * circumstances. If we merely fail to open the new log we
+                * should stick with the old one. ergo this should only be
+                * reached when opening the logs for the first time: at
+                * startup or when the log level is increased from zero.
+                * -dwg 6 June 2000
+                */
+               dbf = x_fopen( "/dev/console", O_WRONLY, 0);
+               if(dbf) {
+                       DEBUG(0,("check_log_size: open of debug file %s failed - using console.\n",
+                                       debugf ));
+               } else {
+                       /*
+                        * We cannot continue without a debug file handle.
+                        */
+                       abort();
+               }
+       }
+       debug_count = 0;
+} /* check_log_size */
 
 /* ************************************************************************** **
  * Write an debug message on the debugfile.
  * This is called by dbghdr() and format_debug_text().
  * ************************************************************************** **
  */
-#ifdef HAVE_STDARG_H
  int Debug1( char *format_str, ... )
 {
-#else
- int Debug1(va_alist)
-va_dcl
-{  
-  char *format_str;
-#endif
   va_list ap;  
   int old_errno = errno;
 
   if( stdout_logging )
     {
-#ifdef HAVE_STDARG_H
     va_start( ap, format_str );
-#else
-    va_start( ap );
-    format_str = va_arg( ap, char * );
-#endif
-    (void)vfprintf( dbf, format_str, ap );
+    if(dbf)
+      (void)x_vfprintf( dbf, format_str, ap );
     va_end( ap );
     errno = old_errno;
     return( 0 );
@@ -331,13 +509,13 @@ va_dcl
       mode_t oldumask = umask( 022 );
 
       if( append_log )
-        dbf = sys_fopen( debugf, "a" );
+        dbf = x_fopen( debugf, O_WRONLY|O_APPEND|O_CREAT, 0644 );
       else
-        dbf = sys_fopen( debugf, "w" );
+        dbf = x_fopen( debugf, O_WRONLY|O_CREAT|O_TRUNC, 0644 );
       (void)umask( oldumask );
       if( dbf )
         {
-        setbuf( dbf, NULL );
+        x_setbuf( dbf, NULL );
         }
       else
         {
@@ -369,12 +547,7 @@ va_dcl
     else
       priority = priority_map[syslog_level];
       
-#ifdef HAVE_STDARG_H
     va_start( ap, format_str );
-#else
-    va_start( ap );
-    format_str = va_arg( ap, char * );
-#endif
     vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
     va_end( ap );
       
@@ -383,23 +556,20 @@ va_dcl
     }
 #endif
   
+  check_log_size();
+
 #ifdef WITH_SYSLOG
   if( !lp_syslog_only() )
 #endif
     {
-#ifdef HAVE_STDARG_H
     va_start( ap, format_str );
-#else
-    va_start( ap );
-    format_str = va_arg( ap, char * );
-#endif
-    (void)vfprintf( dbf, format_str, ap );
+    if(dbf)
+      (void)x_vfprintf( dbf, format_str, ap );
     va_end( ap );
-    (void)fflush( dbf );
+    if(dbf)
+      (void)x_fflush( dbf );
     }
 
-  check_log_size();
-
   errno = old_errno;
 
   return( 0 );
@@ -440,8 +610,8 @@ static void bufr_print( void )
  */
 static void format_debug_text( char *msg )
   {
-  int i;
-  BOOL timestamp = (timestamp_log && !stdout_logging && (lp_timestamp_logs() || 
+  size_t i;
+  BOOL timestamp = (!stdout_logging && (lp_timestamp_logs() || 
                                        !(lp_loaded())));
 
   for( i = 0; msg[i]; i++ )
@@ -486,14 +656,15 @@ static void format_debug_text( char *msg )
 void dbgflush( void )
   {
   bufr_print();
-  (void)fflush( dbf );
+  if(dbf)
+    (void)x_fflush( dbf );
   } /* dbgflush */
 
 /* ************************************************************************** **
  * Print a Debug Header.
  *
  *  Input:  level - Debug level of the message (not the system-wide debug
- *                  level.
+ *                  level. )
  *          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.
@@ -511,10 +682,13 @@ void dbgflush( void )
  *
  * ************************************************************************** **
  */
+
 BOOL dbghdr( int level, char *file, char *func, int line )
-  {
-  if( format_pos )
-    {
+{
+  /* Ensure we don't lose any real errno value. */
+  int old_errno = errno;
+
+  if( format_pos ) {
     /* This is a fudge.  If there is stuff sitting in the format_bufr, then
      * the *right* thing to do is to call
      *   format_debug_text( "\n" );
@@ -525,7 +699,7 @@ BOOL dbghdr( int level, char *file, char *func, int line )
      * that a new header is *not* desired.
      */
     return( True );
-    }
+  }
 
 #ifdef WITH_SYSLOG
   /* Set syslog_level. */
@@ -539,15 +713,32 @@ BOOL dbghdr( int level, char *file, char *func, int line )
   /* Print the header if timestamps are turned on.  If parameters are
    * not yet loaded, then default to timestamps on.
    */
-  if( timestamp_log && (lp_timestamp_logs() || !(lp_loaded()) ))
-    {
+  if( lp_timestamp_logs() || !(lp_loaded()) ) {
+    char header_str[200];
+
+       header_str[0] = '\0';
+
+       if( lp_debug_pid())
+         slprintf(header_str,sizeof(header_str)-1,", pid=%u",(unsigned int)sys_getpid());
+
+       if( lp_debug_uid()) {
+      size_t hs_len = strlen(header_str);
+         slprintf(header_str + hs_len,
+               sizeof(header_str) - 1 - hs_len,
+                          ", effective(%u, %u), real(%u, %u)",
+               (unsigned int)geteuid(), (unsigned int)getegid(),
+                          (unsigned int)getuid(), (unsigned int)getgid()); 
+       }
+  
     /* Print it all out at once to prevent split syslog output. */
-    (void)Debug1( "[%s, %d] %s:%s(%d)\n",
-                  timestring(), level, file, func, line );
-    }
+    (void)Debug1( "[%s, %d%s] %s:%s(%d)\n",
+                  timestring(lp_debug_hires_timestamp()), level,
+                                 header_str, file, func, line );
+  }
 
+  errno = old_errno;
   return( True );
-  } /* dbghdr */
+}
 
 /* ************************************************************************** **
  * Add text to the body of the "current" debug message via the format buffer.
@@ -562,7 +753,6 @@ BOOL dbghdr( int level, char *file, char *func, int line )
  *
  * ************************************************************************** **
  */
-#ifdef HAVE_STDARG_H
  BOOL dbgtext( char *format_str, ... )
   {
   va_list ap;
@@ -577,24 +767,5 @@ BOOL dbghdr( int level, char *file, char *func, int line )
   return( True );
   } /* dbgtext */
 
-#else
- BOOL dbgtext( va_alist )
- va_dcl
-  {
-  char *format_str;
-  va_list ap;
-  pstring msgbuf;
-
-  va_start( ap );
-  format_str = va_arg( ap, char * );
-  vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
-  va_end( ap );
-
-  format_debug_text( msgbuf );
-
-  return( True );
-  } /* dbgtext */
-
-#endif
 
 /* ************************************************************************** */