debug: In dbghdrclass, don't call strlen repeatedly
[Samba.git] / lib / util / debug.c
blobcd2c60880560c067261d7d91b1191cc75e5d0ce9
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
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.
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.
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/>.
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "system/syslog.h"
25 #include "lib/util/time_basic.h"
27 /* define what facility to use for syslog */
28 #ifndef SYSLOG_FACILITY
29 #define SYSLOG_FACILITY LOG_DAEMON
30 #endif
32 /* -------------------------------------------------------------------------- **
33 * Defines...
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.
40 #define FORMAT_BUFR_SIZE 1024
41 #define FORMAT_BUFR_MAX (FORMAT_BUFR_SIZE - 1)
43 /* -------------------------------------------------------------------------- **
44 * This module implements Samba's debugging utility.
46 * The syntax of a debugging log file is represented as:
48 * <debugfile> :== { <debugmsg> }
50 * <debugmsg> :== <debughdr> '\n' <debugtext>
52 * <debughdr> :== '[' TIME ',' LEVEL ']' [ [FILENAME ':'] [FUNCTION '()'] ]
54 * <debugtext> :== { <debugline> }
56 * <debugline> :== TEXT '\n'
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.
64 * Basically, what that all means is:
66 * - A debugging log file is made up of debug messages.
68 * - Each debug message is made up of a header and text. The header is
69 * separated from the text by a newline.
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.
76 * - The message text is made up of zero or more lines, each terminated by
77 * a newline.
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;
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
97 .fd = 2 /* stderr by default */
100 /* -------------------------------------------------------------------------- **
101 * External variables.
105 used to check if the user specified a
106 logfile on the command line
108 bool override_logfile;
111 * This is to allow reading of DEBUGLEVEL_CLASS before the debug
112 * system has been initialized.
114 static const int debug_class_list_initial[DBGC_MAX_FIXED + 1];
116 static int debug_num_classes = 0;
117 int *DEBUGLEVEL_CLASS = discard_const_p(int, debug_class_list_initial);
120 /* -------------------------------------------------------------------------- **
121 * Internal variables.
123 * debug_count - Number of debug messages that have been output.
124 * Used to check log size.
126 * current_msg_level - Internal copy of the message debug level. Written by
127 * dbghdr() and read by Debug1().
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.
134 * format_pos - Marks the first free byte of the format_bufr.
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.
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;
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>..
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
181 static char **classname_table = NULL;
184 /* -------------------------------------------------------------------------- **
185 * Functions...
188 static void debug_init(void);
190 /***************************************************************************
191 Free memory pointed to by global pointers.
192 ****************************************************************************/
194 void gfree_debugsyms(void)
196 TALLOC_FREE(classname_table);
198 if ( DEBUGLEVEL_CLASS != debug_class_list_initial ) {
199 TALLOC_FREE( DEBUGLEVEL_CLASS );
200 DEBUGLEVEL_CLASS = discard_const_p(int, debug_class_list_initial);
203 debug_num_classes = 0;
205 state.initialized = false;
208 /****************************************************************************
209 utility lists registered debug class names's
210 ****************************************************************************/
212 char *debug_list_class_names_and_levels(void)
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;
227 return buf;
230 /****************************************************************************
231 Utility to translate names to debug class index's (internal version).
232 ****************************************************************************/
234 static int debug_lookup_classname_int(const char* classname)
236 int i;
238 if (!classname) return -1;
240 for (i=0; i < debug_num_classes; i++) {
241 if (strcmp(classname, classname_table[i])==0)
242 return i;
244 return -1;
247 /****************************************************************************
248 Add a new debug class to the system.
249 ****************************************************************************/
251 int debug_add_class(const char *classname)
253 int ndx;
254 int *new_class_list;
255 char **new_name_list;
256 int default_level;
258 if (!classname)
259 return -1;
261 /* check the init has yet been called */
262 debug_init();
264 ndx = debug_lookup_classname_int(classname);
265 if (ndx >= 0)
266 return ndx;
267 ndx = debug_num_classes;
269 if (DEBUGLEVEL_CLASS == debug_class_list_initial) {
270 /* Initial loading... */
271 new_class_list = NULL;
272 } else {
273 new_class_list = DEBUGLEVEL_CLASS;
276 default_level = DEBUGLEVEL_CLASS[DBGC_ALL];
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;
283 DEBUGLEVEL_CLASS[ndx] = default_level;
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;
290 classname_table[ndx] = talloc_strdup(classname_table, classname);
291 if (! classname_table[ndx])
292 return -1;
294 debug_num_classes = ndx + 1;
296 return ndx;
299 /****************************************************************************
300 Utility to translate names to debug class index's (public version).
301 ****************************************************************************/
303 int debug_lookup_classname(const char *classname)
305 int ndx;
307 if (!classname || !*classname)
308 return -1;
310 ndx = debug_lookup_classname_int(classname);
312 if (ndx != -1)
313 return ndx;
315 DEBUG(0, ("debug_lookup_classname(%s): Unknown class\n",
316 classname));
317 return debug_add_class(classname);
320 /****************************************************************************
321 Dump the current registered debug levels.
322 ****************************************************************************/
324 static void debug_dump_status(int level)
326 int q;
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]));
337 static bool debug_parse_param(char *param)
339 char *class_name;
340 char *class_level;
341 char *saveptr;
342 int ndx;
344 class_name = strtok_r(param, ":", &saveptr);
345 if (class_name == NULL) {
346 return false;
349 class_level = strtok_r(NULL, "\0", &saveptr);
350 if (class_level == NULL) {
351 return false;
354 ndx = debug_lookup_classname(class_name);
355 if (ndx == -1) {
356 return false;
359 DEBUGLEVEL_CLASS[ndx] = atoi(class_level);
361 return true;
364 /****************************************************************************
365 parse the debug levels from smbcontrol. Example debug level parameter:
366 printdrivers:7
367 ****************************************************************************/
369 static bool debug_parse_params(char **params)
371 int i, ndx;
373 if (!params)
374 return false;
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
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 */
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];
392 /* Fill in new debug class levels */
393 for (; params[i]; i++) {
394 bool ok;
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;
404 return true;
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 ****************************************************************************/
413 bool debug_parse_levels(const char *params_str)
415 char **params;
416 bool ok;
418 /* Just in case */
419 debug_init();
421 params = str_list_make(NULL, params_str, NULL);
423 ok = debug_parse_params(params);
424 if (ok) {
425 debug_dump_status(5);
428 TALLOC_FREE(params);
429 return ok;
432 /* setup for logging of talloc warnings */
433 static void talloc_log_fn(const char *msg)
435 DEBUG(0,("%s", msg));
438 void debug_setup_talloc_log(void)
440 talloc_set_log_fn(talloc_log_fn);
444 /****************************************************************************
445 Init debugging (one time stuff)
446 ****************************************************************************/
448 static void debug_init(void)
450 const char **p;
452 if (state.initialized)
453 return;
455 state.initialized = true;
457 debug_setup_talloc_log();
459 for(p = default_classname_table; *p; p++) {
460 debug_add_class(*p);
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)
469 state.settings = *settings;
473 control the name of the logfile and whether logging will be to stdout, stderr
474 or a file, and set up syslog
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
482 void setup_logging(const char *prog_name, enum debug_logtype new_logtype)
484 debug_init();
485 if (state.logtype < new_logtype) {
486 state.logtype = new_logtype;
488 if (prog_name) {
489 state.prog_name = prog_name;
491 reopen_logs_internal();
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
508 /***************************************************************************
509 Set the logfile name.
510 **************************************************************************/
512 void debug_set_logfile(const char *name)
514 if (name == NULL || *name == 0) {
515 /* this copes with calls when smb.conf is not loaded yet */
516 return;
518 TALLOC_FREE(state.debugf);
519 state.debugf = talloc_strdup(NULL, name);
522 static void debug_close_fd(int fd)
524 if (fd > 2) {
525 close(fd);
529 bool debug_get_output_is_stderr(void)
531 return (state.logtype == DEBUG_DEFAULT_STDERR) || (state.logtype == DEBUG_STDERR);
534 bool debug_get_output_is_stdout(void)
536 return (state.logtype == DEBUG_DEFAULT_STDOUT) || (state.logtype == DEBUG_STDOUT);
539 void debug_set_callback(void *private_ptr, debug_callback_fn fn)
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;
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 **************************************************************************/
562 reopen the log file (usually called because the log file name might have changed)
564 bool reopen_logs_internal(void)
566 mode_t oldumask;
567 int new_fd = 0;
568 int old_fd = 0;
569 bool ret = true;
571 if (state.reopening_logs) {
572 return true;
575 /* Now clear the SIGHUP induced flag */
576 state.schedule_reopen_logs = false;
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;
587 case DEBUG_DEFAULT_STDERR:
588 case DEBUG_STDERR:
589 debug_close_fd(state.fd);
590 state.fd = 2;
591 return true;
593 case DEBUG_FILE:
594 break;
597 oldumask = umask( 022 );
599 if (!state.debugf) {
600 return false;
603 state.reopening_logs = true;
605 new_fd = open( state.debugf, O_WRONLY|O_APPEND|O_CREAT, 0644);
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);
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.
622 force_check_log_size();
623 (void)umask(oldumask);
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 fundamental
631 failure... */
632 close_low_fds(false, false, true);
636 state.reopening_logs = false;
638 return ret;
641 /**************************************************************************
642 Force a check of the log size.
643 ***************************************************************************/
645 void force_check_log_size( void )
647 debug_count = 100;
650 _PUBLIC_ void debug_schedule_reopen_logs(void)
652 state.schedule_reopen_logs = true;
656 /***************************************************************************
657 Check to see if there is any need to check if the logfile has grown too big.
658 **************************************************************************/
660 bool need_to_check_log_size( void )
662 int maxlog;
664 if( debug_count < 100)
665 return( false );
667 maxlog = state.settings.max_log_size * 1024;
668 if ( state.fd <=2 || maxlog <= 0 ) {
669 debug_count = 0;
670 return(false);
672 return( true );
675 /**************************************************************************
676 Check to see if the log has grown to be too big.
677 **************************************************************************/
679 void check_log_size( void )
681 int maxlog;
682 struct stat st;
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.
689 #if _SAMBA_BUILD_ == 3
690 if (geteuid() != sec_initial_uid())
691 #else
692 if( geteuid() != 0)
693 #endif
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;
702 if(log_overflow || (!state.schedule_reopen_logs && !need_to_check_log_size())) {
703 return;
706 maxlog = state.settings.max_log_size * 1024;
708 if (state.schedule_reopen_logs) {
709 (void)reopen_logs_internal();
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;
719 if (asprintf(&name, "%s.old", state.debugf ) < 0) {
720 return;
722 (void)rename(state.debugf, name);
724 if (!reopen_logs_internal()) {
725 /* We failed to reopen a log - continue using the old name. */
726 (void)rename(name, state.debugf);
728 SAFE_FREE(name);
733 * Here's where we need to panic if state.fd == 0 or -1 (invalid values)
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
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 {
751 * We cannot continue without a debug file handle.
753 abort();
756 debug_count = 0;
759 /*************************************************************************
760 Write an debug message on the debugfile.
761 This is called by dbghdr() and format_debug_text().
762 ************************************************************************/
764 static int Debug1(const char *msg)
766 int old_errno = errno;
768 debug_count++;
770 if (state.logtype == DEBUG_CALLBACK) {
771 size_t msg_len = strlen(msg);
772 char msg_copy[msg_len];
774 if ((msg_len > 0) && (msg[msg_len-1] == '\n')) {
775 memcpy(msg_copy, msg, msg_len-1);
776 msg_copy[msg_len-1] = '\0';
777 msg = msg_copy;
780 state.callback(state.callback_private, current_msg_level, msg);
781 goto done;
784 if ( state.logtype != DEBUG_FILE ) {
785 if (state.fd > 0) {
786 write(state.fd, msg, strlen(msg));
788 goto done;
791 #ifdef WITH_SYSLOG
792 if( !state.settings.syslog_only)
793 #endif
795 if( state.fd <= 0 ) {
796 mode_t oldumask = umask( 022 );
797 int fd = open( state.debugf, O_WRONLY|O_APPEND|O_CREAT, 0644 );
798 (void)umask( oldumask );
799 if(fd == -1) {
800 goto done;
802 state.fd = fd;
807 #ifdef WITH_SYSLOG
808 if( current_msg_level < state.settings.syslog ) {
809 /* map debug levels to syslog() priorities
810 * note that not all DEBUG(0, ...) calls are
811 * necessarily errors */
812 static const int priority_map[4] = {
813 LOG_ERR, /* 0 */
814 LOG_WARNING, /* 1 */
815 LOG_NOTICE, /* 2 */
816 LOG_INFO, /* 3 */
818 int priority;
820 if( current_msg_level >= ARRAY_SIZE(priority_map) || current_msg_level < 0)
821 priority = LOG_DEBUG;
822 else
823 priority = priority_map[current_msg_level];
826 * Specify the facility to interoperate with other syslog
827 * callers (vfs_full_audit for example).
829 priority |= SYSLOG_FACILITY;
831 syslog(priority, "%s", msg);
833 #endif
835 check_log_size();
837 #ifdef WITH_SYSLOG
838 if( !state.settings.syslog_only)
839 #endif
841 if (state.fd > 0) {
842 write(state.fd, msg, strlen(msg));
846 done:
847 errno = old_errno;
849 return( 0 );
853 /**************************************************************************
854 Print the buffer content via Debug1(), then reset the buffer.
855 Input: none
856 Output: none
857 ****************************************************************************/
859 static void bufr_print( void )
861 format_bufr[format_pos] = '\0';
862 (void)Debug1(format_bufr);
863 format_pos = 0;
866 /***************************************************************************
867 Format the debug message text.
869 Input: msg - Text to be added to the "current" debug message text.
871 Output: none.
873 Notes: The purpose of this is two-fold. First, each call to syslog()
874 (used by Debug1(), see above) generates a new line of syslog
875 output. This is fixed by storing the partial lines until the
876 newline character is encountered. Second, printing the debug
877 message lines when a newline is encountered allows us to add
878 spaces, thus indenting the body of the message and making it
879 more readable.
880 **************************************************************************/
882 static void format_debug_text( const char *msg )
884 size_t i;
885 bool timestamp = (state.logtype == DEBUG_FILE && (state.settings.timestamp_logs));
887 debug_init();
889 for( i = 0; msg[i]; i++ ) {
890 /* Indent two spaces at each new line. */
891 if(timestamp && 0 == format_pos) {
892 format_bufr[0] = format_bufr[1] = ' ';
893 format_pos = 2;
896 /* If there's room, copy the character to the format buffer. */
897 if( format_pos < FORMAT_BUFR_MAX )
898 format_bufr[format_pos++] = msg[i];
900 /* If a newline is encountered, print & restart. */
901 if( '\n' == msg[i] )
902 bufr_print();
904 /* If the buffer is full dump it out, reset it, and put out a line
905 * continuation indicator.
907 if( format_pos >= FORMAT_BUFR_MAX ) {
908 bufr_print();
909 (void)Debug1( " +>\n" );
913 /* Just to be safe... */
914 format_bufr[format_pos] = '\0';
917 /***************************************************************************
918 Flush debug output, including the format buffer content.
920 Input: none
921 Output: none
922 ***************************************************************************/
924 void dbgflush( void )
926 bufr_print();
929 /***************************************************************************
930 Print a Debug Header.
932 Input: level - Debug level of the message (not the system-wide debug
933 level. )
934 cls - Debuglevel class of the calling module.
935 file - Pointer to a string containing the name of the file
936 from which this function was called, or an empty string
937 if the __FILE__ macro is not implemented.
938 func - Pointer to a string containing the name of the function
939 from which this function was called, or an empty string
940 if the __FUNCTION__ macro is not implemented.
941 line - line number of the call to dbghdr, assuming __LINE__
942 works.
944 Output: Always true. This makes it easy to fudge a call to dbghdr()
945 in a macro, since the function can be called as part of a test.
946 Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
948 Notes: This function takes care of setting current_msg_level.
950 ****************************************************************************/
952 bool dbghdrclass(int level, int cls, const char *location, const char *func)
954 /* Ensure we don't lose any real errno value. */
955 int old_errno = errno;
956 bool verbose = false;
957 char header_str[200];
958 size_t hs_len;
959 struct timeval tv;
960 struct timeval_buf tvbuf;
962 if( format_pos ) {
963 /* This is a fudge. If there is stuff sitting in the format_bufr, then
964 * the *right* thing to do is to call
965 * format_debug_text( "\n" );
966 * to write the remainder, and then proceed with the new header.
967 * Unfortunately, there are several places in the code at which
968 * the DEBUG() macro is used to build partial lines. That in mind,
969 * we'll work under the assumption that an incomplete line indicates
970 * that a new header is *not* desired.
972 return( true );
975 /* Set current_msg_level. */
976 current_msg_level = level;
978 /* Don't print a header if we're logging to stdout. */
979 if ( state.logtype != DEBUG_FILE ) {
980 return( true );
983 /* Print the header if timestamps are turned on. If parameters are
984 * not yet loaded, then default to timestamps on.
986 if (!(state.settings.timestamp_logs ||
987 state.settings.debug_prefix_timestamp)) {
988 return true;
991 GetTimeOfDay(&tv);
992 timeval_str_buf(&tv, state.settings.debug_hires_timestamp, &tvbuf);
994 hs_len = snprintf(header_str, sizeof(header_str), "[%s, %2d",
995 tvbuf.buf, level);
996 if (hs_len >= sizeof(header_str)) {
997 goto full;
1000 if (unlikely(DEBUGLEVEL_CLASS[ cls ] >= 10)) {
1001 verbose = true;
1004 if (verbose || state.settings.debug_pid) {
1005 hs_len += snprintf(
1006 header_str + hs_len, sizeof(header_str) - hs_len,
1007 ", pid=%u", (unsigned int)getpid());
1008 if (hs_len >= sizeof(header_str)) {
1009 goto full;
1013 if (verbose || state.settings.debug_uid) {
1014 hs_len += snprintf(
1015 header_str + hs_len, sizeof(header_str) - hs_len,
1016 ", effective(%u, %u), real(%u, %u)",
1017 (unsigned int)geteuid(), (unsigned int)getegid(),
1018 (unsigned int)getuid(), (unsigned int)getgid());
1019 if (hs_len >= sizeof(header_str)) {
1020 goto full;
1024 if ((verbose || state.settings.debug_class)
1025 && (cls != DBGC_ALL)) {
1026 hs_len += snprintf(
1027 header_str + hs_len, sizeof(header_str) - hs_len,
1028 ", class=%s", classname_table[cls]);
1029 if (hs_len >= sizeof(header_str)) {
1030 goto full;
1035 * No +=, see man man strlcat
1037 hs_len = strlcat(header_str, "] ", sizeof(header_str));
1038 if (hs_len >= sizeof(header_str)) {
1039 goto full;
1042 if (!state.settings.debug_prefix_timestamp) {
1043 hs_len += snprintf(
1044 header_str + hs_len, sizeof(header_str) - hs_len,
1045 "%s(%s)\n", location, func);
1046 if (hs_len >= sizeof(header_str)) {
1047 goto full;
1051 full:
1052 (void)Debug1(header_str);
1054 errno = old_errno;
1055 return( true );
1058 /***************************************************************************
1059 Add text to the body of the "current" debug message via the format buffer.
1061 Input: format_str - Format string, as used in printf(), et. al.
1062 ... - Variable argument list.
1064 ..or.. va_alist - Old style variable parameter list starting point.
1066 Output: Always true. See dbghdr() for more info, though this is not
1067 likely to be used in the same way.
1069 ***************************************************************************/
1071 bool dbgtext( const char *format_str, ... )
1073 va_list ap;
1074 char *msgbuf = NULL;
1075 bool ret = true;
1076 int res;
1078 va_start(ap, format_str);
1079 res = vasprintf(&msgbuf, format_str, ap);
1080 va_end(ap);
1082 if (res != -1) {
1083 format_debug_text(msgbuf);
1084 } else {
1085 ret = false;
1087 SAFE_FREE(msgbuf);
1088 return ret;