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