r14397: Fix deadcode in coverity error #1.
[sfrench/samba-autobuild/.git] / source3 / lib / debug.c
1 /*
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Elrond               2002
6    Copyright (C) Simo Sorce           2002
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24
25 /* -------------------------------------------------------------------------- **
26  * Defines...
27  *
28  *  FORMAT_BUFR_MAX - Index of the last byte of the format buffer;
29  *                    format_bufr[FORMAT_BUFR_MAX] should always be reserved
30  *                    for a terminating null byte.
31  */
32
33 #define FORMAT_BUFR_MAX ( sizeof( format_bufr ) - 1 )
34
35 /* -------------------------------------------------------------------------- **
36  * This module implements Samba's debugging utility.
37  *
38  * The syntax of a debugging log file is represented as:
39  *
40  *  <debugfile> :== { <debugmsg> }
41  *
42  *  <debugmsg>  :== <debughdr> '\n' <debugtext>
43  *
44  *  <debughdr>  :== '[' TIME ',' LEVEL ']' [ [FILENAME ':'] [FUNCTION '()'] ]
45  *
46  *  <debugtext> :== { <debugline> }
47  *
48  *  <debugline> :== TEXT '\n'
49  *
50  * TEXT     is a string of characters excluding the newline character.
51  * LEVEL    is the DEBUG level of the message (an integer in the range 0..10).
52  * TIME     is a timestamp.
53  * FILENAME is the name of the file from which the debug message was generated.
54  * FUNCTION is the function from which the debug message was generated.
55  *
56  * Basically, what that all means is:
57  *
58  * - A debugging log file is made up of debug messages.
59  *
60  * - Each debug message is made up of a header and text.  The header is
61  *   separated from the text by a newline.
62  *
63  * - The header begins with the timestamp and debug level of the message
64  *   enclosed in brackets.  The filename and function from which the
65  *   message was generated may follow.  The filename is terminated by a
66  *   colon, and the function name is terminated by parenthesis.
67  *
68  * - The message text is made up of zero or more lines, each terminated by
69  *   a newline.
70  */
71
72 /* -------------------------------------------------------------------------- **
73  * External variables.
74  *
75  *  dbf           - Global debug file handle.
76  *  debugf        - Debug file name.
77  *  DEBUGLEVEL    - System-wide debug message limit.  Messages with message-
78  *                  levels higher than DEBUGLEVEL will not be processed.
79  */
80
81 XFILE   *dbf        = NULL;
82 pstring debugf     = "";
83 BOOL    debug_warn_unknown_class = True;
84 BOOL    debug_auto_add_unknown_class = True;
85 BOOL    AllowDebugChange = True;
86
87 /* 
88    used to check if the user specified a 
89    logfile on the command line 
90 */
91 BOOL    override_logfile;               
92
93
94 /*
95  * This is to allow assignment to DEBUGLEVEL before the debug
96  * system has been initialised.
97  */
98 static int debug_all_class_hack = 1;
99 static BOOL debug_all_class_isset_hack = True;
100
101 static int debug_num_classes = 0;
102 int     *DEBUGLEVEL_CLASS = &debug_all_class_hack;
103 BOOL    *DEBUGLEVEL_CLASS_ISSET = &debug_all_class_isset_hack;
104
105 /* DEBUGLEVEL is #defined to *debug_level */
106 int     DEBUGLEVEL = &debug_all_class_hack;
107
108
109 /* -------------------------------------------------------------------------- **
110  * Internal variables.
111  *
112  *  stdout_logging  - Default False, if set to True then dbf will be set to
113  *                    stdout and debug output will go to dbf only, and not
114  *                    to syslog.  Set in setup_logging() and read in Debug1().
115  *
116  *  debug_count     - Number of debug messages that have been output.
117  *                    Used to check log size.
118  *
119  *  syslog_level    - Internal copy of the message debug level.  Written by
120  *                    dbghdr() and read by Debug1().
121  *
122  *  format_bufr     - Used to format debug messages.  The dbgtext() function
123  *                    prints debug messages to a string, and then passes the
124  *                    string to format_debug_text(), which uses format_bufr
125  *                    to build the formatted output.
126  *
127  *  format_pos      - Marks the first free byte of the format_bufr.
128  * 
129  *
130  *  log_overflow    - When this variable is True, never attempt to check the
131  *                    size of the log. This is a hack, so that we can write
132  *                    a message using DEBUG, from open_logs() when we
133  *                    are unable to open a new log file for some reason.
134  */
135
136 static BOOL    stdout_logging = False;
137 static int     debug_count    = 0;
138 #ifdef WITH_SYSLOG
139 static int     syslog_level   = 0;
140 #endif
141 static pstring format_bufr    = { '\0' };
142 static size_t     format_pos     = 0;
143 static BOOL    log_overflow   = False;
144
145 /*
146  * Define all the debug class selection names here. Names *MUST NOT* contain 
147  * white space. There must be one name for each DBGC_<class name>, and they 
148  * must be in the table in the order of DBGC_<class name>.. 
149  */
150 static const char *default_classname_table[] = {
151         "all",               /* DBGC_ALL; index refs traditional DEBUGLEVEL */
152         "tdb",               /* DBGC_TDB          */
153         "printdrivers",      /* DBGC_PRINTDRIVERS */
154         "lanman",            /* DBGC_LANMAN       */
155         "smb",               /* DBGC_SMB          */
156         "rpc_parse",         /* DBGC_RPC_PARSE    */
157         "rpc_srv",           /* DBGC_RPC_SRV      */
158         "rpc_cli",           /* DBGC_RPC_CLI      */
159         "passdb",            /* DBGC_PASSDB       */
160         "sam",               /* DBGC_SAM          */
161         "auth",              /* DBGC_AUTH         */
162         "winbind",           /* DBGC_WINBIND      */
163         "vfs",               /* DBGC_VFS          */
164         "idmap",             /* DBGC_IDMAP        */
165         "quota",             /* DBGC_QUOTA        */
166         "acls",              /* DBGC_ACLS         */
167         "locking",           /* DBGC_LOCKING      */
168         "msdfs",             /* DBGC_MSDFS        */
169         NULL
170 };
171
172 static char **classname_table = NULL;
173
174
175 /* -------------------------------------------------------------------------- **
176  * Functions...
177  */
178
179
180 /****************************************************************************
181 utility lists registered debug class names's
182 ****************************************************************************/
183
184 #define MAX_CLASS_NAME_SIZE 1024
185
186 static char *debug_list_class_names_and_levels(void)
187 {
188         int i, dim;
189         char **list;
190         char *buf = NULL;
191         char *b;
192         BOOL err = False;
193
194         if (DEBUGLEVEL_CLASS == &debug_all_class_hack) {
195                 return NULL;
196         }
197
198         list = SMB_CALLOC_ARRAY(char *, debug_num_classes + 1);
199         if (!list) {
200                 return NULL;
201         }
202
203         /* prepare strings */
204         for (i = 0, dim = 0; i < debug_num_classes; i++) {
205                 int l = asprintf(&list[i],
206                                 "%s:%d ",
207                                 classname_table[i],
208                                 DEBUGLEVEL_CLASS_ISSET[i]?DEBUGLEVEL_CLASS[i]:DEBUGLEVEL);
209                 if (l < 0 || l > MAX_CLASS_NAME_SIZE) {
210                         err = True;
211                         goto done;
212                 }
213                 dim += l;
214         }
215
216         /* create single string list - add space for newline */
217         b = buf = SMB_MALLOC(dim+1);
218         if (!buf) {
219                 err = True;
220                 goto done;
221         }
222         for (i = 0; i < debug_num_classes; i++) {
223                 int l = strlen(list[i]);
224                 strncpy(b, list[i], l);
225                 b = b + l;
226         }
227         b[-1] = '\n'; /* replace last space with newline */
228         b[0] = '\0';  /* null terminate string */
229
230 done:
231         /* free strings list */
232         for (i = 0; i < debug_num_classes; i++) {
233                 SAFE_FREE(list[i]);
234         }
235         SAFE_FREE(list);
236
237         if (err) {
238                 return NULL;
239         } else {
240                 return buf;
241         }
242 }
243
244 /****************************************************************************
245  Utility access to debug class names's.
246 ****************************************************************************/
247
248 const char *debug_classname_from_index(int ndx)
249 {
250         if (ndx < 0 || ndx >= debug_num_classes)
251                 return NULL;
252         else
253                 return classname_table[ndx];
254 }
255
256 /****************************************************************************
257  Utility to translate names to debug class index's (internal version).
258 ****************************************************************************/
259
260 static int debug_lookup_classname_int(const char* classname)
261 {
262         int i;
263
264         if (!classname) return -1;
265
266         for (i=0; i < debug_num_classes; i++) {
267                 if (strcmp(classname, classname_table[i])==0)
268                         return i;
269         }
270         return -1;
271 }
272
273 /****************************************************************************
274  Add a new debug class to the system.
275 ****************************************************************************/
276
277 int debug_add_class(const char *classname)
278 {
279         int ndx;
280         void *new_ptr;
281
282         if (!classname)
283                 return -1;
284
285         /* check the init has yet been called */
286         debug_init();
287
288         ndx = debug_lookup_classname_int(classname);
289         if (ndx >= 0)
290                 return ndx;
291         ndx = debug_num_classes;
292
293         new_ptr = DEBUGLEVEL_CLASS;
294         if (DEBUGLEVEL_CLASS == &debug_all_class_hack) {
295                 /* Initial loading... */
296                 new_ptr = NULL;
297         }
298         new_ptr = SMB_REALLOC_ARRAY(new_ptr, int, debug_num_classes + 1);
299         if (!new_ptr)
300                 return -1;
301         DEBUGLEVEL_CLASS = new_ptr;
302         DEBUGLEVEL_CLASS[ndx] = 0;
303
304         /* debug_level is the pointer used for the DEBUGLEVEL-thingy */
305         if (ndx==0) {
306                 /* Transfer the initial level from debug_all_class_hack */
307                 DEBUGLEVEL_CLASS[ndx] = DEBUGLEVEL;
308         }
309         debug_level = DEBUGLEVEL_CLASS;
310
311         new_ptr = DEBUGLEVEL_CLASS_ISSET;
312         if (new_ptr == &debug_all_class_isset_hack) {
313                 new_ptr = NULL;
314         }
315         new_ptr = SMB_REALLOC_ARRAY(new_ptr, BOOL, debug_num_classes + 1);
316         if (!new_ptr)
317                 return -1;
318         DEBUGLEVEL_CLASS_ISSET = new_ptr;
319         DEBUGLEVEL_CLASS_ISSET[ndx] = False;
320
321         new_ptr = SMB_REALLOC_ARRAY(classname_table, char *, debug_num_classes + 1);
322         if (!new_ptr)
323                 return -1;
324         classname_table = new_ptr;
325
326         classname_table[ndx] = SMB_STRDUP(classname);
327         if (! classname_table[ndx])
328                 return -1;
329         
330         debug_num_classes++;
331
332         return ndx;
333 }
334
335 /****************************************************************************
336  Utility to translate names to debug class index's (public version).
337 ****************************************************************************/
338
339 int debug_lookup_classname(const char *classname)
340 {
341         int ndx;
342        
343         if (!classname || !*classname)
344                 return -1;
345
346         ndx = debug_lookup_classname_int(classname);
347
348         if (ndx != -1)
349                 return ndx;
350
351         if (debug_warn_unknown_class) {
352                 DEBUG(0, ("debug_lookup_classname(%s): Unknown class\n",
353                           classname));
354         }
355         if (debug_auto_add_unknown_class) {
356                 return debug_add_class(classname);
357         }
358         return -1;
359 }
360
361 /****************************************************************************
362  Dump the current registered debug levels.
363 ****************************************************************************/
364
365 static void debug_dump_status(int level)
366 {
367         int q;
368
369         DEBUG(level, ("INFO: Current debug levels:\n"));
370         for (q = 0; q < debug_num_classes; q++) {
371                 DEBUGADD(level, ("  %s: %s/%d\n",
372                                  classname_table[q],
373                                  (DEBUGLEVEL_CLASS_ISSET[q]
374                                   ? "True" : "False"),
375                                  DEBUGLEVEL_CLASS[q]));
376         }
377 }
378
379 /****************************************************************************
380  parse the debug levels from smbcontrol. Example debug level parameter:
381  printdrivers:7
382 ****************************************************************************/
383
384 static BOOL debug_parse_params(char **params)
385 {
386         int   i, ndx;
387         char *class_name;
388         char *class_level;
389
390         if (!params)
391                 return False;
392
393         /* Allow DBGC_ALL to be specified w/o requiring its class name e.g."10"  
394          * v.s. "all:10", this is the traditional way to set DEBUGLEVEL 
395          */
396         if (isdigit((int)params[0][0])) {
397                 DEBUGLEVEL_CLASS[DBGC_ALL] = atoi(params[0]);
398                 DEBUGLEVEL_CLASS_ISSET[DBGC_ALL] = True;
399                 i = 1; /* start processing at the next params */
400         } else {
401                 i = 0; /* DBGC_ALL not specified OR class name was included */
402         }
403
404         /* Fill in new debug class levels */
405         for (; i < debug_num_classes && params[i]; i++) {
406                 if ((class_name=strtok(params[i],":")) &&
407                         (class_level=strtok(NULL, "\0")) &&
408             ((ndx = debug_lookup_classname(class_name)) != -1)) {
409                                 DEBUGLEVEL_CLASS[ndx] = atoi(class_level);
410                                 DEBUGLEVEL_CLASS_ISSET[ndx] = True;
411                 } else {
412                         DEBUG(0,("debug_parse_params: unrecognized debug class name or format [%s]\n", params[i]));
413                         return False;
414                 }
415         }
416
417         return True;
418 }
419
420 /****************************************************************************
421  Parse the debug levels from smb.conf. Example debug level string:
422   3 tdb:5 printdrivers:7
423  Note: the 1st param has no "name:" preceeding it.
424 ****************************************************************************/
425
426 BOOL debug_parse_levels(const char *params_str)
427 {
428         char **params;
429
430         /* Just in case */
431         debug_init();
432
433         if (AllowDebugChange == False)
434                 return True;
435
436         params = str_list_make(params_str, NULL);
437
438         if (debug_parse_params(params)) {
439                 debug_dump_status(5);
440                 str_list_free(&params);
441                 return True;
442         } else {
443                 str_list_free(&params);
444                 return False;
445         }
446 }
447
448 /****************************************************************************
449  Receive a "set debug level" message.
450 ****************************************************************************/
451
452 static void debug_message(int msg_type, struct process_id src,
453                           void *buf, size_t len)
454 {
455         const char *params_str = buf;
456
457         /* Check, it's a proper string! */
458         if (params_str[len-1] != '\0') {
459                 DEBUG(1, ("Invalid debug message from pid %u to pid %u\n",
460                           (unsigned int)procid_to_pid(&src),
461                           (unsigned int)getpid()));
462                 return;
463         }
464
465         DEBUG(3, ("INFO: Remote set of debug to `%s'  (pid %u from pid %u)\n",
466                   params_str, (unsigned int)getpid(),
467                   (unsigned int)procid_to_pid(&src)));
468
469         debug_parse_levels(params_str);
470 }
471
472 /****************************************************************************
473  Send a "set debug level" message.
474 ****************************************************************************/
475
476 void debug_message_send(pid_t pid, const char *params_str)
477 {
478         if (!params_str)
479                 return;
480         message_send_pid(pid_to_procid(pid), MSG_DEBUG,
481                          params_str, strlen(params_str) + 1,
482                          False);
483 }
484
485 /****************************************************************************
486  Return current debug level.
487 ****************************************************************************/
488
489 static void debuglevel_message(int msg_type, struct process_id src,
490                                void *buf, size_t len)
491 {
492         char *message = debug_list_class_names_and_levels();
493
494         DEBUG(1,("INFO: Received REQ_DEBUGLEVEL message from PID %u\n",
495                  (unsigned int)procid_to_pid(&src)));
496         message_send_pid(src, MSG_DEBUGLEVEL, message, strlen(message) + 1, True);
497
498         SAFE_FREE(message);
499 }
500
501 /****************************************************************************
502 Init debugging (one time stuff)
503 ****************************************************************************/
504
505 void debug_init(void)
506 {
507         static BOOL initialised = False;
508         const char **p;
509
510         if (initialised)
511                 return;
512         
513         initialised = True;
514
515         message_register(MSG_DEBUG, debug_message);
516         message_register(MSG_REQ_DEBUGLEVEL, debuglevel_message);
517
518         for(p = default_classname_table; *p; p++) {
519                 debug_add_class(*p);
520         }
521 }
522
523 /***************************************************************************
524  Get ready for syslog stuff
525 **************************************************************************/
526
527 void setup_logging(const char *pname, BOOL interactive)
528 {
529         debug_init();
530
531         /* reset to allow multiple setup calls, going from interactive to
532            non-interactive */
533         stdout_logging = False;
534         if (dbf) {
535                 x_fflush(dbf);
536                 (void) x_fclose(dbf);
537         }
538
539         dbf = NULL;
540
541         if (interactive) {
542                 stdout_logging = True;
543                 dbf = x_stdout;
544                 x_setbuf( x_stdout, NULL );
545         }
546 #ifdef WITH_SYSLOG
547         else {
548                 const char *p = strrchr_m( pname,'/' );
549                 if (p)
550                         pname = p + 1;
551 #ifdef LOG_DAEMON
552                 openlog( pname, LOG_PID, SYSLOG_FACILITY );
553 #else
554                 /* for old systems that have no facility codes. */
555                 openlog( pname, LOG_PID );
556 #endif
557         }
558 #endif
559 }
560
561 /**************************************************************************
562  reopen the log files
563  note that we now do this unconditionally
564  We attempt to open the new debug fp before closing the old. This means
565  if we run out of fd's we just keep using the old fd rather than aborting.
566  Fix from dgibson@linuxcare.com.
567 **************************************************************************/
568
569 BOOL reopen_logs( void )
570 {
571         pstring fname;
572         mode_t oldumask;
573         XFILE *new_dbf = NULL;
574         XFILE *old_dbf = NULL;
575         BOOL ret = True;
576
577         if (stdout_logging)
578                 return True;
579
580         oldumask = umask( 022 );
581   
582         pstrcpy(fname, debugf );
583         debugf[0] = '\0';
584
585         if (lp_loaded()) {
586                 char *logfname;
587
588                 logfname = lp_logfile();
589                 if (*logfname)
590                         pstrcpy(fname, logfname);
591         }
592
593         pstrcpy( debugf, fname );
594         new_dbf = x_fopen( debugf, O_WRONLY|O_APPEND|O_CREAT, 0644);
595
596         if (!new_dbf) {
597                 log_overflow = True;
598                 DEBUG(0, ("Unable to open new log file %s: %s\n", debugf, strerror(errno)));
599                 log_overflow = False;
600                 if (dbf)
601                         x_fflush(dbf);
602                 ret = False;
603         } else {
604                 x_setbuf(new_dbf, NULL);
605                 old_dbf = dbf;
606                 dbf = new_dbf;
607                 if (old_dbf)
608                         (void) x_fclose(old_dbf);
609         }
610
611         /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
612          * to fix problem where smbd's that generate less
613          * than 100 messages keep growing the log.
614          */
615         force_check_log_size();
616         (void)umask(oldumask);
617
618         /* Take over stderr to catch ouput into logs */
619         if (dbf && sys_dup2(x_fileno(dbf), 2) == -1) {
620                 close_low_fds(True); /* Close stderr too, if dup2 can't point it
621                                         at the logfile */
622         }
623
624         return ret;
625 }
626
627 /**************************************************************************
628  Force a check of the log size.
629  ***************************************************************************/
630
631 void force_check_log_size( void )
632 {
633         debug_count = 100;
634 }
635
636 /***************************************************************************
637  Check to see if there is any need to check if the logfile has grown too big.
638 **************************************************************************/
639
640 BOOL need_to_check_log_size( void )
641 {
642         int maxlog;
643
644         if( debug_count < 100 )
645                 return( False );
646
647         maxlog = lp_max_log_size() * 1024;
648         if( !dbf || maxlog <= 0 ) {
649                 debug_count = 0;
650                 return(False);
651         }
652         return( True );
653 }
654
655 /**************************************************************************
656  Check to see if the log has grown to be too big.
657  **************************************************************************/
658
659 void check_log_size( void )
660 {
661         int         maxlog;
662         SMB_STRUCT_STAT st;
663
664         /*
665          *  We need to be root to check/change log-file, skip this and let the main
666          *  loop check do a new check as root.
667          */
668
669         if( geteuid() != 0 )
670                 return;
671
672         if(log_overflow || !need_to_check_log_size() )
673                 return;
674
675         maxlog = lp_max_log_size() * 1024;
676
677         if( sys_fstat( x_fileno( dbf ), &st ) == 0 && st.st_size > maxlog ) {
678                 (void)reopen_logs();
679                 if( dbf && get_file_size( debugf ) > maxlog ) {
680                         pstring name;
681
682                         slprintf( name, sizeof(name)-1, "%s.old", debugf );
683                         (void)rename( debugf, name );
684       
685                         if (!reopen_logs()) {
686                                 /* We failed to reopen a log - continue using the old name. */
687                                 (void)rename(name, debugf);
688                         }
689                 }
690         }
691
692         /*
693          * Here's where we need to panic if dbf == NULL..
694          */
695
696         if(dbf == NULL) {
697                 /* This code should only be reached in very strange
698                  * circumstances. If we merely fail to open the new log we
699                  * should stick with the old one. ergo this should only be
700                  * reached when opening the logs for the first time: at
701                  * startup or when the log level is increased from zero.
702                  * -dwg 6 June 2000
703                  */
704                 dbf = x_fopen( "/dev/console", O_WRONLY, 0);
705                 if(dbf) {
706                         DEBUG(0,("check_log_size: open of debug file %s failed - using console.\n",
707                                         debugf ));
708                 } else {
709                         /*
710                          * We cannot continue without a debug file handle.
711                          */
712                         abort();
713                 }
714         }
715         debug_count = 0;
716 }
717
718 /*************************************************************************
719  Write an debug message on the debugfile.
720  This is called by dbghdr() and format_debug_text().
721 ************************************************************************/
722
723  int Debug1( const char *format_str, ... )
724 {
725         va_list ap;  
726         int old_errno = errno;
727
728         debug_count++;
729
730         if( stdout_logging ) {
731                 va_start( ap, format_str );
732                 if(dbf)
733                         (void)x_vfprintf( dbf, format_str, ap );
734                 va_end( ap );
735                 errno = old_errno;
736                 return( 0 );
737         }
738
739         /* prevent recursion by checking if reopen_logs() has temporaily
740            set the debugf string to "" */
741         if( debugf[0] == '\0')
742                 return( 0 );
743
744 #ifdef WITH_SYSLOG
745         if( !lp_syslog_only() )
746 #endif
747         {
748                 if( !dbf ) {
749                         mode_t oldumask = umask( 022 );
750
751                         dbf = x_fopen( debugf, O_WRONLY|O_APPEND|O_CREAT, 0644 );
752                         (void)umask( oldumask );
753                         if( dbf ) {
754                                 x_setbuf( dbf, NULL );
755                         } else {
756                                 errno = old_errno;
757                                 return(0);
758                         }
759                 }
760         }
761
762 #ifdef WITH_SYSLOG
763         if( syslog_level < lp_syslog() ) {
764                 /* map debug levels to syslog() priorities
765                  * note that not all DEBUG(0, ...) calls are
766                  * necessarily errors */
767                 static int priority_map[] = { 
768                         LOG_ERR,     /* 0 */
769                         LOG_WARNING, /* 1 */
770                         LOG_NOTICE,  /* 2 */
771                         LOG_INFO,    /* 3 */
772                 };
773                 int     priority;
774                 pstring msgbuf;
775
776                 if( syslog_level >= ( sizeof(priority_map) / sizeof(priority_map[0]) ) || syslog_level < 0)
777                         priority = LOG_DEBUG;
778                 else
779                         priority = priority_map[syslog_level];
780
781                 va_start( ap, format_str );
782                 vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
783                 va_end( ap );
784
785                 msgbuf[255] = '\0';
786                 syslog( priority, "%s", msgbuf );
787         }
788 #endif
789   
790         check_log_size();
791
792 #ifdef WITH_SYSLOG
793         if( !lp_syslog_only() )
794 #endif
795         {
796                 va_start( ap, format_str );
797                 if(dbf)
798                         (void)x_vfprintf( dbf, format_str, ap );
799                 va_end( ap );
800                 if(dbf)
801                         (void)x_fflush( dbf );
802         }
803
804         errno = old_errno;
805
806         return( 0 );
807 }
808
809
810 /**************************************************************************
811  Print the buffer content via Debug1(), then reset the buffer.
812  Input:  none
813  Output: none
814 ****************************************************************************/
815
816 static void bufr_print( void )
817 {
818         format_bufr[format_pos] = '\0';
819         (void)Debug1( "%s", format_bufr );
820         format_pos = 0;
821 }
822
823 /***************************************************************************
824  Format the debug message text.
825
826  Input:  msg - Text to be added to the "current" debug message text.
827
828  Output: none.
829
830  Notes:  The purpose of this is two-fold.  First, each call to syslog()
831          (used by Debug1(), see above) generates a new line of syslog
832          output.  This is fixed by storing the partial lines until the
833          newline character is encountered.  Second, printing the debug
834          message lines when a newline is encountered allows us to add
835          spaces, thus indenting the body of the message and making it
836          more readable.
837 **************************************************************************/
838
839 static void format_debug_text( const char *msg )
840 {
841         size_t i;
842         BOOL timestamp = (!stdout_logging && (lp_timestamp_logs() || !(lp_loaded())));
843
844         for( i = 0; msg[i]; i++ ) {
845                 /* Indent two spaces at each new line. */
846                 if(timestamp && 0 == format_pos) {
847                         format_bufr[0] = format_bufr[1] = ' ';
848                         format_pos = 2;
849                 }
850
851                 /* If there's room, copy the character to the format buffer. */
852                 if( format_pos < FORMAT_BUFR_MAX )
853                         format_bufr[format_pos++] = msg[i];
854
855                 /* If a newline is encountered, print & restart. */
856                 if( '\n' == msg[i] )
857                         bufr_print();
858
859                 /* If the buffer is full dump it out, reset it, and put out a line
860                  * continuation indicator.
861                  */
862                 if( format_pos >= FORMAT_BUFR_MAX ) {
863                         bufr_print();
864                         (void)Debug1( " +>\n" );
865                 }
866         }
867
868         /* Just to be safe... */
869         format_bufr[format_pos] = '\0';
870 }
871
872 /***************************************************************************
873  Flush debug output, including the format buffer content.
874
875  Input:  none
876  Output: none
877 ***************************************************************************/
878
879 void dbgflush( void )
880 {
881         bufr_print();
882         if(dbf)
883                 (void)x_fflush( dbf );
884 }
885
886 /***************************************************************************
887  Print a Debug Header.
888
889  Input:  level - Debug level of the message (not the system-wide debug
890                   level. )
891           file  - Pointer to a string containing the name of the file
892                   from which this function was called, or an empty string
893                   if the __FILE__ macro is not implemented.
894           func  - Pointer to a string containing the name of the function
895                   from which this function was called, or an empty string
896                   if the __FUNCTION__ macro is not implemented.
897          line  - line number of the call to dbghdr, assuming __LINE__
898                  works.
899
900   Output: Always True.  This makes it easy to fudge a call to dbghdr()
901           in a macro, since the function can be called as part of a test.
902           Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
903
904   Notes:  This function takes care of setting syslog_level.
905
906 ****************************************************************************/
907
908 BOOL dbghdr( int level, const char *file, const char *func, int line )
909 {
910         /* Ensure we don't lose any real errno value. */
911         int old_errno = errno;
912
913         if( format_pos ) {
914                 /* This is a fudge.  If there is stuff sitting in the format_bufr, then
915                  * the *right* thing to do is to call
916                  *   format_debug_text( "\n" );
917                  * to write the remainder, and then proceed with the new header.
918                  * Unfortunately, there are several places in the code at which
919                  * the DEBUG() macro is used to build partial lines.  That in mind,
920                  * we'll work under the assumption that an incomplete line indicates
921                  * that a new header is *not* desired.
922                  */
923                 return( True );
924         }
925
926 #ifdef WITH_SYSLOG
927         /* Set syslog_level. */
928         syslog_level = level;
929 #endif
930
931         /* Don't print a header if we're logging to stdout. */
932         if( stdout_logging )
933                 return( True );
934
935         /* Print the header if timestamps are turned on.  If parameters are
936          * not yet loaded, then default to timestamps on.
937          */
938         if( lp_timestamp_logs() || !(lp_loaded()) ) {
939                 char header_str[200];
940
941                 header_str[0] = '\0';
942
943                 if( lp_debug_pid())
944                         slprintf(header_str,sizeof(header_str)-1,", pid=%u",(unsigned int)sys_getpid());
945
946                 if( lp_debug_uid()) {
947                         size_t hs_len = strlen(header_str);
948                         slprintf(header_str + hs_len,
949                         sizeof(header_str) - 1 - hs_len,
950                                 ", effective(%u, %u), real(%u, %u)",
951                                 (unsigned int)geteuid(), (unsigned int)getegid(),
952                                 (unsigned int)getuid(), (unsigned int)getgid()); 
953                 }
954   
955                 /* Print it all out at once to prevent split syslog output. */
956                 (void)Debug1( "[%s, %d%s] %s:%s(%d)\n",
957                         timestring(lp_debug_hires_timestamp()), level,
958                         header_str, file, func, line );
959         }
960
961         errno = old_errno;
962         return( True );
963 }
964
965 /***************************************************************************
966  Add text to the body of the "current" debug message via the format buffer.
967
968   Input:  format_str  - Format string, as used in printf(), et. al.
969           ...         - Variable argument list.
970
971   ..or..  va_alist    - Old style variable parameter list starting point.
972
973   Output: Always True.  See dbghdr() for more info, though this is not
974           likely to be used in the same way.
975
976 ***************************************************************************/
977
978  BOOL dbgtext( const char *format_str, ... )
979 {
980         va_list ap;
981         pstring msgbuf;
982
983         va_start( ap, format_str ); 
984         vslprintf( msgbuf, sizeof(msgbuf)-1, format_str, ap );
985         va_end( ap );
986
987         format_debug_text( msgbuf );
988
989   return( True );
990 }