d96fcc5322f13a1df108ee015a0e090614097d35
[samba.git] / lib / util / 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 3 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, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "system/syslog.h"
25 #include "lib/util/time_basic.h"
26
27 /* define what facility to use for syslog */
28 #ifndef SYSLOG_FACILITY
29 #define SYSLOG_FACILITY LOG_DAEMON
30 #endif
31
32 /* -------------------------------------------------------------------------- **
33  * Defines...
34  *
35  *  FORMAT_BUFR_MAX - Index of the last byte of the format buffer;
36  *                    format_bufr[FORMAT_BUFR_MAX] should always be reserved
37  *                    for a terminating null byte.
38  */
39
40 #define FORMAT_BUFR_SIZE 1024
41 #define FORMAT_BUFR_MAX (FORMAT_BUFR_SIZE - 1)
42
43 /* -------------------------------------------------------------------------- **
44  * This module implements Samba's debugging utility.
45  *
46  * The syntax of a debugging log file is represented as:
47  *
48  *  <debugfile> :== { <debugmsg> }
49  *
50  *  <debugmsg>  :== <debughdr> '\n' <debugtext>
51  *
52  *  <debughdr>  :== '[' TIME ',' LEVEL ']' [ [FILENAME ':'] [FUNCTION '()'] ]
53  *
54  *  <debugtext> :== { <debugline> }
55  *
56  *  <debugline> :== TEXT '\n'
57  *
58  * TEXT     is a string of characters excluding the newline character.
59  * LEVEL    is the DEBUG level of the message (an integer in the range 0..10).
60  * TIME     is a timestamp.
61  * FILENAME is the name of the file from which the debug message was generated.
62  * FUNCTION is the function from which the debug message was generated.
63  *
64  * Basically, what that all means is:
65  *
66  * - A debugging log file is made up of debug messages.
67  *
68  * - Each debug message is made up of a header and text.  The header is
69  *   separated from the text by a newline.
70  *
71  * - The header begins with the timestamp and debug level of the message
72  *   enclosed in brackets.  The filename and function from which the
73  *   message was generated may follow.  The filename is terminated by a
74  *   colon, and the function name is terminated by parenthesis.
75  *
76  * - The message text is made up of zero or more lines, each terminated by
77  *   a newline.
78  */
79
80 /* state variables for the debug system */
81 static struct {
82         bool initialized;
83         int fd;   /* The log file handle */
84         enum debug_logtype logtype; /* The type of logging we are doing: eg stdout, file, stderr */
85         const char *prog_name;
86         bool reopening_logs;
87         bool schedule_reopen_logs;
88
89         struct debug_settings settings;
90         char *debugf;
91         debug_callback_fn callback;
92         void *callback_private;
93 } state = {
94         .settings = {
95                 .timestamp_logs = true
96         },
97         .fd = 2 /* stderr by default */
98 };
99
100 /* -------------------------------------------------------------------------- **
101  * External variables.
102  */
103
104 /*
105    used to check if the user specified a
106    logfile on the command line
107 */
108 bool    override_logfile;
109
110 /*
111  * This is to allow reading of DEBUGLEVEL_CLASS before the debug
112  * system has been initialized.
113  */
114 static const int debug_class_list_initial[DBGC_MAX_FIXED + 1];
115
116 static int debug_num_classes = 0;
117 int     *DEBUGLEVEL_CLASS = discard_const_p(int, debug_class_list_initial);
118
119
120 /* -------------------------------------------------------------------------- **
121  * Internal variables.
122  *
123  *  debug_count     - Number of debug messages that have been output.
124  *                    Used to check log size.
125  *
126  *  current_msg_level    - Internal copy of the message debug level.  Written by
127  *                    dbghdr() and read by Debug1().
128  *
129  *  format_bufr     - Used to format debug messages.  The dbgtext() function
130  *                    prints debug messages to a string, and then passes the
131  *                    string to format_debug_text(), which uses format_bufr
132  *                    to build the formatted output.
133  *
134  *  format_pos      - Marks the first free byte of the format_bufr.
135  *
136  *
137  *  log_overflow    - When this variable is true, never attempt to check the
138  *                    size of the log. This is a hack, so that we can write
139  *                    a message using DEBUG, from open_logs() when we
140  *                    are unable to open a new log file for some reason.
141  */
142
143 static int     debug_count    = 0;
144 static int     current_msg_level   = 0;
145 static char format_bufr[FORMAT_BUFR_SIZE];
146 static size_t     format_pos     = 0;
147 static bool    log_overflow   = false;
148
149 /*
150  * Define all the debug class selection names here. Names *MUST NOT* contain
151  * white space. There must be one name for each DBGC_<class name>, and they
152  * must be in the table in the order of DBGC_<class name>..
153  */
154 static const char *default_classname_table[] = {
155         "all",               /* DBGC_ALL; index refs traditional DEBUGLEVEL */
156         "tdb",               /* DBGC_TDB          */
157         "printdrivers",      /* DBGC_PRINTDRIVERS */
158         "lanman",            /* DBGC_LANMAN       */
159         "smb",               /* DBGC_SMB          */
160         "rpc_parse",         /* DBGC_RPC_PARSE    */
161         "rpc_srv",           /* DBGC_RPC_SRV      */
162         "rpc_cli",           /* DBGC_RPC_CLI      */
163         "passdb",            /* DBGC_PASSDB       */
164         "sam",               /* DBGC_SAM          */
165         "auth",              /* DBGC_AUTH         */
166         "winbind",           /* DBGC_WINBIND      */
167         "vfs",               /* DBGC_VFS          */
168         "idmap",             /* DBGC_IDMAP        */
169         "quota",             /* DBGC_QUOTA        */
170         "acls",              /* DBGC_ACLS         */
171         "locking",           /* DBGC_LOCKING      */
172         "msdfs",             /* DBGC_MSDFS        */
173         "dmapi",             /* DBGC_DMAPI        */
174         "registry",          /* DBGC_REGISTRY     */
175         "scavenger",         /* DBGC_SCAVENGER    */
176         "dns",               /* DBGC_DNS          */
177         "ldb",               /* DBGC_LDB          */
178         NULL
179 };
180
181 static char **classname_table = NULL;
182
183
184 /* -------------------------------------------------------------------------- **
185  * Functions...
186  */
187
188 static void debug_init(void);
189
190 /***************************************************************************
191  Free memory pointed to by global pointers.
192 ****************************************************************************/
193
194 void gfree_debugsyms(void)
195 {
196         TALLOC_FREE(classname_table);
197
198         if ( DEBUGLEVEL_CLASS != debug_class_list_initial ) {
199                 TALLOC_FREE( DEBUGLEVEL_CLASS );
200                 DEBUGLEVEL_CLASS = discard_const_p(int, debug_class_list_initial);
201         }
202
203         debug_num_classes = 0;
204
205         state.initialized = false;
206 }
207
208 /****************************************************************************
209 utility lists registered debug class names's
210 ****************************************************************************/
211
212 char *debug_list_class_names_and_levels(void)
213 {
214         char *buf = NULL;
215         unsigned int i;
216         /* prepare strings */
217         for (i = 0; i < debug_num_classes; i++) {
218                 buf = talloc_asprintf_append(buf, 
219                                              "%s:%d%s",
220                                              classname_table[i],
221                                              DEBUGLEVEL_CLASS[i],
222                                              i == (debug_num_classes - 1) ? "\n" : " ");
223                 if (buf == NULL) {
224                         return NULL;
225                 }
226         }
227         return buf;
228 }
229
230 /****************************************************************************
231  Utility to translate names to debug class index's (internal version).
232 ****************************************************************************/
233
234 static int debug_lookup_classname_int(const char* classname)
235 {
236         int i;
237
238         if (!classname) return -1;
239
240         for (i=0; i < debug_num_classes; i++) {
241                 if (strcmp(classname, classname_table[i])==0)
242                         return i;
243         }
244         return -1;
245 }
246
247 /****************************************************************************
248  Add a new debug class to the system.
249 ****************************************************************************/
250
251 int debug_add_class(const char *classname)
252 {
253         int ndx;
254         int *new_class_list;
255         char **new_name_list;
256         int default_level;
257
258         if (!classname)
259                 return -1;
260
261         /* check the init has yet been called */
262         debug_init();
263
264         ndx = debug_lookup_classname_int(classname);
265         if (ndx >= 0)
266                 return ndx;
267         ndx = debug_num_classes;
268
269         if (DEBUGLEVEL_CLASS == debug_class_list_initial) {
270                 /* Initial loading... */
271                 new_class_list = NULL;
272         } else {
273                 new_class_list = DEBUGLEVEL_CLASS;
274         }
275
276         default_level = DEBUGLEVEL_CLASS[DBGC_ALL];
277
278         new_class_list = talloc_realloc(NULL, new_class_list, int, ndx + 1);
279         if (!new_class_list)
280                 return -1;
281         DEBUGLEVEL_CLASS = new_class_list;
282
283         DEBUGLEVEL_CLASS[ndx] = default_level;
284
285         new_name_list = talloc_realloc(NULL, classname_table, char *, ndx + 1);
286         if (!new_name_list)
287                 return -1;
288         classname_table = new_name_list;
289
290         classname_table[ndx] = talloc_strdup(classname_table, classname);
291         if (! classname_table[ndx])
292                 return -1;
293
294         debug_num_classes = ndx + 1;
295
296         return ndx;
297 }
298
299 /****************************************************************************
300  Utility to translate names to debug class index's (public version).
301 ****************************************************************************/
302
303 int debug_lookup_classname(const char *classname)
304 {
305         int ndx;
306
307         if (!classname || !*classname)
308                 return -1;
309
310         ndx = debug_lookup_classname_int(classname);
311
312         if (ndx != -1)
313                 return ndx;
314
315         DEBUG(0, ("debug_lookup_classname(%s): Unknown class\n",
316                   classname));
317         return debug_add_class(classname);
318 }
319
320 /****************************************************************************
321  Dump the current registered debug levels.
322 ****************************************************************************/
323
324 static void debug_dump_status(int level)
325 {
326         int q;
327
328         DEBUG(level, ("INFO: Current debug levels:\n"));
329         for (q = 0; q < debug_num_classes; q++) {
330                 const char *classname = classname_table[q];
331                 DEBUGADD(level, ("  %s: %d\n",
332                                  classname,
333                                  DEBUGLEVEL_CLASS[q]));
334         }
335 }
336
337 static bool debug_parse_param(char *param)
338 {
339         char *class_name;
340         char *class_level;
341         char *saveptr;
342         int ndx;
343
344         class_name = strtok_r(param, ":", &saveptr);
345         if (class_name == NULL) {
346                 return false;
347         }
348
349         class_level = strtok_r(NULL, "\0", &saveptr);
350         if (class_level == NULL) {
351                 return false;
352         }
353
354         ndx = debug_lookup_classname(class_name);
355         if (ndx == -1) {
356                 return false;
357         }
358
359         DEBUGLEVEL_CLASS[ndx] = atoi(class_level);
360
361         return true;
362 }
363
364 /****************************************************************************
365  parse the debug levels from smbcontrol. Example debug level parameter:
366  printdrivers:7
367 ****************************************************************************/
368
369 static bool debug_parse_params(char **params)
370 {
371         int   i, ndx;
372
373         if (!params)
374                 return false;
375
376         /* Allow DBGC_ALL to be specified w/o requiring its class name e.g."10"
377          * v.s. "all:10", this is the traditional way to set DEBUGLEVEL
378          */
379         if (isdigit((int)params[0][0])) {
380                 DEBUGLEVEL_CLASS[DBGC_ALL] = atoi(params[0]);
381                 i = 1; /* start processing at the next params */
382         } else {
383                 DEBUGLEVEL_CLASS[DBGC_ALL] = 0;
384                 i = 0; /* DBGC_ALL not specified OR class name was included */
385         }
386
387         /* Array is debug_num_classes long */
388         for (ndx = DBGC_ALL; ndx < debug_num_classes; ndx++) {
389                 DEBUGLEVEL_CLASS[ndx] = DEBUGLEVEL_CLASS[DBGC_ALL];
390         }
391
392         /* Fill in new debug class levels */
393         for (; params[i]; i++) {
394                 bool ok;
395
396                 ok = debug_parse_param(params[i]);
397                 if (!ok) {
398                         DEBUG(0,("debug_parse_params: unrecognized debug "
399                                  "class name or format [%s]\n", params[i]));
400                         return false;
401                 }
402         }
403
404         return true;
405 }
406
407 /****************************************************************************
408  Parse the debug levels from smb.conf. Example debug level string:
409   3 tdb:5 printdrivers:7
410  Note: the 1st param has no "name:" preceeding it.
411 ****************************************************************************/
412
413 bool debug_parse_levels(const char *params_str)
414 {
415         char **params;
416
417         /* Just in case */
418         debug_init();
419
420         params = str_list_make(NULL, params_str, NULL);
421
422         if (debug_parse_params(params)) {
423                 debug_dump_status(5);
424                 TALLOC_FREE(params);
425                 return true;
426         } else {
427                 TALLOC_FREE(params);
428                 return false;
429         }
430 }
431
432 /* setup for logging of talloc warnings */
433 static void talloc_log_fn(const char *msg)
434 {
435         DEBUG(0,("%s", msg));
436 }
437
438 void debug_setup_talloc_log(void)
439 {
440         talloc_set_log_fn(talloc_log_fn);
441 }
442
443
444 /****************************************************************************
445 Init debugging (one time stuff)
446 ****************************************************************************/
447
448 static void debug_init(void)
449 {
450         const char **p;
451
452         if (state.initialized)
453                 return;
454
455         state.initialized = true;
456
457         debug_setup_talloc_log();
458
459         for(p = default_classname_table; *p; p++) {
460                 debug_add_class(*p);
461         }
462 }
463
464 /* This forces in some smb.conf derived values into the debug system.
465  * There are no pointers in this structure, so we can just
466  * structure-assign it in */
467 void debug_set_settings(struct debug_settings *settings)
468 {
469         state.settings = *settings;
470 }
471
472 /**
473   control the name of the logfile and whether logging will be to stdout, stderr
474   or a file, and set up syslog
475
476   new_log indicates the destination for the debug log (an enum in
477   order of precedence - once set to DEBUG_FILE, it is not possible to
478   reset to DEBUG_STDOUT for example.  This makes it easy to override
479   for debug to stderr on the command line, as the smb.conf cannot
480   reset it back to file-based logging
481 */
482 void setup_logging(const char *prog_name, enum debug_logtype new_logtype)
483 {
484         debug_init();
485         if (state.logtype < new_logtype) {
486                 state.logtype = new_logtype;
487         }
488         if (prog_name) {
489                 state.prog_name = prog_name;
490         }
491         reopen_logs_internal();
492
493         if (state.logtype == DEBUG_FILE) {
494 #ifdef WITH_SYSLOG
495                 const char *p = strrchr(prog_name, '/');
496                 if (p)
497                         prog_name = p + 1;
498 #ifdef LOG_DAEMON
499                 openlog( prog_name, LOG_PID, SYSLOG_FACILITY );
500 #else
501                 /* for old systems that have no facility codes. */
502                 openlog( prog_name, LOG_PID );
503 #endif
504 #endif
505         }
506 }
507
508 /***************************************************************************
509  Set the logfile name.
510 **************************************************************************/
511
512 void debug_set_logfile(const char *name)
513 {
514         if (name == NULL || *name == 0) {
515                 /* this copes with calls when smb.conf is not loaded yet */
516                 return;
517         }
518         TALLOC_FREE(state.debugf);
519         state.debugf = talloc_strdup(NULL, name);
520 }
521
522 static void debug_close_fd(int fd)
523 {
524         if (fd > 2) {
525                 close(fd);
526         }
527 }
528
529 bool debug_get_output_is_stderr(void)
530 {
531         return (state.logtype == DEBUG_DEFAULT_STDERR) || (state.logtype == DEBUG_STDERR);
532 }
533
534 bool debug_get_output_is_stdout(void)
535 {
536         return (state.logtype == DEBUG_DEFAULT_STDOUT) || (state.logtype == DEBUG_STDOUT);
537 }
538
539 void debug_set_callback(void *private_ptr, debug_callback_fn fn)
540 {
541         debug_init();
542         if (fn) {
543                 state.logtype = DEBUG_CALLBACK;
544                 state.callback_private = private_ptr;
545                 state.callback = fn;
546         } else {
547                 state.logtype = DEBUG_DEFAULT_STDERR;
548                 state.callback_private = NULL;
549                 state.callback = NULL;
550         }
551 }
552
553 /**************************************************************************
554  reopen the log files
555  note that we now do this unconditionally
556  We attempt to open the new debug fp before closing the old. This means
557  if we run out of fd's we just keep using the old fd rather than aborting.
558  Fix from dgibson@linuxcare.com.
559 **************************************************************************/
560
561 /**
562   reopen the log file (usually called because the log file name might have changed)
563 */
564 bool reopen_logs_internal(void)
565 {
566         mode_t oldumask;
567         int new_fd = 0;
568         int old_fd = 0;
569         bool ret = true;
570
571         if (state.reopening_logs) {
572                 return true;
573         }
574
575         /* Now clear the SIGHUP induced flag */
576         state.schedule_reopen_logs = false;
577
578         switch (state.logtype) {
579         case DEBUG_CALLBACK:
580                 return true;
581         case DEBUG_STDOUT:
582         case DEBUG_DEFAULT_STDOUT:
583                 debug_close_fd(state.fd);
584                 state.fd = 1;
585                 return true;
586
587         case DEBUG_DEFAULT_STDERR:
588         case DEBUG_STDERR:
589                 debug_close_fd(state.fd);
590                 state.fd = 2;
591                 return true;
592
593         case DEBUG_FILE:
594                 break;
595         }
596
597         oldumask = umask( 022 );
598
599         if (!state.debugf) {
600                 return false;
601         }
602
603         state.reopening_logs = true;
604
605         new_fd = open( state.debugf, O_WRONLY|O_APPEND|O_CREAT, 0644);
606
607         if (new_fd == -1) {
608                 log_overflow = true;
609                 DEBUG(0, ("Unable to open new log file '%s': %s\n", state.debugf, strerror(errno)));
610                 log_overflow = false;
611                 ret = false;
612         } else {
613                 old_fd = state.fd;
614                 state.fd = new_fd;
615                 debug_close_fd(old_fd);
616         }
617
618         /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
619          * to fix problem where smbd's that generate less
620          * than 100 messages keep growing the log.
621          */
622         force_check_log_size();
623         (void)umask(oldumask);
624
625         /* Take over stderr to catch output into logs */
626         if (state.fd > 0) {
627                 if (dup2(state.fd, 2) == -1) {
628                         /* Close stderr too, if dup2 can't point it -
629                            at the logfile.  There really isn't much
630                            that can be done on such a fundemental
631                            failure... */
632                         close_low_fds(false, false, true);
633                 }
634         }
635
636         state.reopening_logs = false;
637
638         return ret;
639 }
640
641 /**************************************************************************
642  Force a check of the log size.
643  ***************************************************************************/
644
645 void force_check_log_size( void )
646 {
647         debug_count = 100;
648 }
649
650 _PUBLIC_ void debug_schedule_reopen_logs(void)
651 {
652         state.schedule_reopen_logs = true;
653 }
654
655
656 /***************************************************************************
657  Check to see if there is any need to check if the logfile has grown too big.
658 **************************************************************************/
659
660 bool need_to_check_log_size( void )
661 {
662         int maxlog;
663
664         if( debug_count < 100)
665                 return( false );
666
667         maxlog = state.settings.max_log_size * 1024;
668         if ( state.fd <=2 || maxlog <= 0 ) {
669                 debug_count = 0;
670                 return(false);
671         }
672         return( true );
673 }
674
675 /**************************************************************************
676  Check to see if the log has grown to be too big.
677  **************************************************************************/
678
679 void check_log_size( void )
680 {
681         int         maxlog;
682         struct stat st;
683
684         /*
685          *  We need to be root to check/change log-file, skip this and let the main
686          *  loop check do a new check as root.
687          */
688
689 #if _SAMBA_BUILD_ == 3
690         if (geteuid() != sec_initial_uid())
691 #else
692         if( geteuid() != 0)
693 #endif
694         {
695                 /* We don't check sec_initial_uid() here as it isn't
696                  * available in common code and we don't generally
697                  * want to rotate and the possibly lose logs in
698                  * make test or the build farm */
699                 return;
700         }
701
702         if(log_overflow || (!state.schedule_reopen_logs && !need_to_check_log_size())) {
703                 return;
704         }
705
706         maxlog = state.settings.max_log_size * 1024;
707
708         if (state.schedule_reopen_logs) {
709             (void)reopen_logs_internal();
710         }
711
712         if (maxlog && (fstat(state.fd, &st) == 0
713             && st.st_size > maxlog )) {
714                 (void)reopen_logs_internal();
715                 if (state.fd > 2 && (fstat(state.fd, &st) == 0
716                                      && st.st_size > maxlog)) {
717                         char *name = NULL;
718                         
719                         if (asprintf(&name, "%s.old", state.debugf ) < 0) {
720                                 return;
721                         }
722                         (void)rename(state.debugf, name);
723                         
724                         if (!reopen_logs_internal()) {
725                                 /* We failed to reopen a log - continue using the old name. */
726                                 (void)rename(name, state.debugf);
727                         }
728                         SAFE_FREE(name);
729                 }
730         }
731
732         /*
733          * Here's where we need to panic if state.fd == 0 or -1 (invalid values)
734          */
735
736         if (state.fd <= 0) {
737                 /* This code should only be reached in very strange
738                  * circumstances. If we merely fail to open the new log we
739                  * should stick with the old one. ergo this should only be
740                  * reached when opening the logs for the first time: at
741                  * startup or when the log level is increased from zero.
742                  * -dwg 6 June 2000
743                  */
744                 int fd = open( "/dev/console", O_WRONLY, 0);
745                 if (fd != -1) {
746                         state.fd = fd;
747                         DEBUG(0,("check_log_size: open of debug file %s failed - using console.\n",
748                                         state.debugf ));
749                 } else {
750                         /*
751                          * We cannot continue without a debug file handle.
752                          */
753                         abort();
754                 }
755         }
756         debug_count = 0;
757 }
758
759 /*************************************************************************
760  Write an debug message on the debugfile.
761  This is called by dbghdr() and format_debug_text().
762 ************************************************************************/
763
764 static int Debug1( const char *format_str, ... )
765 {
766         va_list ap;
767         int old_errno = errno;
768
769         debug_count++;
770
771         if (state.logtype == DEBUG_CALLBACK) {
772                 char *msg;
773                 int ret;
774                 va_start( ap, format_str );
775                 ret = vasprintf( &msg, format_str, ap );
776                 if (ret != -1) {
777                         if (msg[ret - 1] == '\n') {
778                                 msg[ret - 1] = '\0';
779                         }
780                         state.callback(state.callback_private, current_msg_level, msg);
781                         free(msg);
782                 }
783                 va_end( ap );
784
785                 goto done;
786
787         } else if ( state.logtype != DEBUG_FILE ) {
788                 va_start( ap, format_str );
789                 if (state.fd > 0)
790                         (void)vdprintf( state.fd, format_str, ap );
791                 va_end( ap );
792                 goto done;
793         }
794
795 #ifdef WITH_SYSLOG
796         if( !state.settings.syslog_only)
797 #endif
798         {
799                 if( state.fd <= 0 ) {
800                         mode_t oldumask = umask( 022 );
801                         int fd = open( state.debugf, O_WRONLY|O_APPEND|O_CREAT, 0644 );
802                         (void)umask( oldumask );
803                         if(fd == -1) {
804                                 goto done;
805                         }
806                         state.fd = fd;
807                 }
808         }
809
810
811 #ifdef WITH_SYSLOG
812         if( current_msg_level < state.settings.syslog ) {
813                 /* map debug levels to syslog() priorities
814                  * note that not all DEBUG(0, ...) calls are
815                  * necessarily errors */
816                 static const int priority_map[4] = {
817                         LOG_ERR,     /* 0 */
818                         LOG_WARNING, /* 1 */
819                         LOG_NOTICE,  /* 2 */
820                         LOG_INFO,    /* 3 */
821                 };
822                 int     priority;
823                 char *msgbuf = NULL;
824                 int ret;
825
826                 if( current_msg_level >= ARRAY_SIZE(priority_map) || current_msg_level < 0)
827                         priority = LOG_DEBUG;
828                 else
829                         priority = priority_map[current_msg_level];
830
831                 /*
832                  * Specify the facility to interoperate with other syslog
833                  * callers (vfs_full_audit for example).
834                  */
835                 priority |= SYSLOG_FACILITY;
836
837                 va_start(ap, format_str);
838                 ret = vasprintf(&msgbuf, format_str, ap);
839                 va_end(ap);
840
841                 if (ret != -1) {
842                         syslog(priority, "%s", msgbuf);
843                 }
844                 SAFE_FREE(msgbuf);
845         }
846 #endif
847
848         check_log_size();
849
850 #ifdef WITH_SYSLOG
851         if( !state.settings.syslog_only)
852 #endif
853         {
854                 va_start( ap, format_str );
855                 if (state.fd > 0)
856                         (void)vdprintf( state.fd, format_str, ap );
857                 va_end( ap );
858         }
859
860  done:
861         errno = old_errno;
862
863         return( 0 );
864 }
865
866
867 /**************************************************************************
868  Print the buffer content via Debug1(), then reset the buffer.
869  Input:  none
870  Output: none
871 ****************************************************************************/
872
873 static void bufr_print( void )
874 {
875         format_bufr[format_pos] = '\0';
876         (void)Debug1( "%s", format_bufr );
877         format_pos = 0;
878 }
879
880 /***************************************************************************
881  Format the debug message text.
882
883  Input:  msg - Text to be added to the "current" debug message text.
884
885  Output: none.
886
887  Notes:  The purpose of this is two-fold.  First, each call to syslog()
888          (used by Debug1(), see above) generates a new line of syslog
889          output.  This is fixed by storing the partial lines until the
890          newline character is encountered.  Second, printing the debug
891          message lines when a newline is encountered allows us to add
892          spaces, thus indenting the body of the message and making it
893          more readable.
894 **************************************************************************/
895
896 static void format_debug_text( const char *msg )
897 {
898         size_t i;
899         bool timestamp = (state.logtype == DEBUG_FILE && (state.settings.timestamp_logs));
900
901         debug_init();
902
903         for( i = 0; msg[i]; i++ ) {
904                 /* Indent two spaces at each new line. */
905                 if(timestamp && 0 == format_pos) {
906                         format_bufr[0] = format_bufr[1] = ' ';
907                         format_pos = 2;
908                 }
909
910                 /* If there's room, copy the character to the format buffer. */
911                 if( format_pos < FORMAT_BUFR_MAX )
912                         format_bufr[format_pos++] = msg[i];
913
914                 /* If a newline is encountered, print & restart. */
915                 if( '\n' == msg[i] )
916                         bufr_print();
917
918                 /* If the buffer is full dump it out, reset it, and put out a line
919                  * continuation indicator.
920                  */
921                 if( format_pos >= FORMAT_BUFR_MAX ) {
922                         bufr_print();
923                         (void)Debug1( " +>\n" );
924                 }
925         }
926
927         /* Just to be safe... */
928         format_bufr[format_pos] = '\0';
929 }
930
931 /***************************************************************************
932  Flush debug output, including the format buffer content.
933
934  Input:  none
935  Output: none
936 ***************************************************************************/
937
938 void dbgflush( void )
939 {
940         bufr_print();
941 }
942
943 /***************************************************************************
944  Print a Debug Header.
945
946  Input:  level - Debug level of the message (not the system-wide debug
947                   level. )
948           cls   - Debuglevel class of the calling module.
949           file  - Pointer to a string containing the name of the file
950                   from which this function was called, or an empty string
951                   if the __FILE__ macro is not implemented.
952           func  - Pointer to a string containing the name of the function
953                   from which this function was called, or an empty string
954                   if the __FUNCTION__ macro is not implemented.
955          line  - line number of the call to dbghdr, assuming __LINE__
956                  works.
957
958   Output: Always true.  This makes it easy to fudge a call to dbghdr()
959           in a macro, since the function can be called as part of a test.
960           Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
961
962   Notes:  This function takes care of setting current_msg_level.
963
964 ****************************************************************************/
965
966 bool dbghdrclass(int level, int cls, const char *location, const char *func)
967 {
968         /* Ensure we don't lose any real errno value. */
969         int old_errno = errno;
970         bool verbose = false;
971         char header_str[200];
972         struct timeval tv;
973         struct timeval_buf tvbuf;
974
975         if( format_pos ) {
976                 /* This is a fudge.  If there is stuff sitting in the format_bufr, then
977                  * the *right* thing to do is to call
978                  *   format_debug_text( "\n" );
979                  * to write the remainder, and then proceed with the new header.
980                  * Unfortunately, there are several places in the code at which
981                  * the DEBUG() macro is used to build partial lines.  That in mind,
982                  * we'll work under the assumption that an incomplete line indicates
983                  * that a new header is *not* desired.
984                  */
985                 return( true );
986         }
987
988         /* Set current_msg_level. */
989         current_msg_level = level;
990
991         /* Don't print a header if we're logging to stdout. */
992         if ( state.logtype != DEBUG_FILE ) {
993                 return( true );
994         }
995
996         /* Print the header if timestamps are turned on.  If parameters are
997          * not yet loaded, then default to timestamps on.
998          */
999         if (!(state.settings.timestamp_logs ||
1000               state.settings.debug_prefix_timestamp)) {
1001                 return true;
1002         }
1003
1004         GetTimeOfDay(&tv);
1005         timeval_str_buf(&tv, state.settings.debug_hires_timestamp, &tvbuf);
1006
1007         snprintf(header_str, sizeof(header_str), "[%s, %2d",
1008                  tvbuf.buf, level);
1009
1010         if (unlikely(DEBUGLEVEL_CLASS[ cls ] >= 10)) {
1011                 verbose = true;
1012         }
1013
1014         if (verbose || state.settings.debug_pid) {
1015                 size_t hs_len = strlen(header_str);
1016                 snprintf(header_str + hs_len, sizeof(header_str) - hs_len,
1017                          ", pid=%u", (unsigned int)getpid());
1018         }
1019
1020         if (verbose || state.settings.debug_uid) {
1021                 size_t hs_len = strlen(header_str);
1022                 snprintf(header_str + hs_len, sizeof(header_str) - hs_len,
1023                          ", effective(%u, %u), real(%u, %u)",
1024                          (unsigned int)geteuid(), (unsigned int)getegid(),
1025                          (unsigned int)getuid(), (unsigned int)getgid());
1026         }
1027
1028         if ((verbose || state.settings.debug_class)
1029             && (cls != DBGC_ALL)) {
1030                 size_t hs_len = strlen(header_str);
1031                 snprintf(header_str + hs_len,
1032                          sizeof(header_str) - hs_len,
1033                          ", class=%s",
1034                          classname_table[cls]);
1035         }
1036
1037         strlcat(header_str, "] ", sizeof(header_str));
1038
1039         if (!state.settings.debug_prefix_timestamp) {
1040                 size_t hs_len = strlen(header_str);
1041                 snprintf(header_str + hs_len,
1042                          sizeof(header_str) - hs_len,
1043                          "%s(%s)\n", location, func);
1044         }
1045
1046         (void)Debug1("%s", header_str);
1047
1048         errno = old_errno;
1049         return( true );
1050 }
1051
1052 /***************************************************************************
1053  Add text to the body of the "current" debug message via the format buffer.
1054
1055   Input:  format_str  - Format string, as used in printf(), et. al.
1056           ...         - Variable argument list.
1057
1058   ..or..  va_alist    - Old style variable parameter list starting point.
1059
1060   Output: Always true.  See dbghdr() for more info, though this is not
1061           likely to be used in the same way.
1062
1063 ***************************************************************************/
1064
1065  bool dbgtext( const char *format_str, ... )
1066 {
1067         va_list ap;
1068         char *msgbuf = NULL;
1069         bool ret = true;
1070         int res;
1071
1072         va_start(ap, format_str);
1073         res = vasprintf(&msgbuf, format_str, ap);
1074         va_end(ap);
1075
1076         if (res != -1) {
1077                 format_debug_text(msgbuf);
1078         } else {
1079                 ret = false;
1080         }
1081         SAFE_FREE(msgbuf);
1082         return ret;
1083 }