lib: Avoid memcpy in debug_lttng_log()
[Samba.git] / lib / util / debug.c
blob4c10fde1b8e1430786797f017a0cdda7a376c747
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 "replace.h"
23 #include <talloc.h>
24 #include "system/filesys.h"
25 #include "system/syslog.h"
26 #include "system/locale.h"
27 #include "system/network.h"
28 #include "system/time.h"
29 #include "time_basic.h"
30 #include "close_low_fd.h"
31 #include "memory.h"
32 #include "util_strlist.h" /* LIST_SEP */
33 #include "blocking.h"
34 #include "debug.h"
35 #include <assert.h>
37 /* define what facility to use for syslog */
38 #ifndef SYSLOG_FACILITY
39 #define SYSLOG_FACILITY LOG_DAEMON
40 #endif
42 /* -------------------------------------------------------------------------- **
43 * Defines...
47 * format_bufr[FORMAT_BUFR_SIZE - 1] should always be reserved
48 * for a terminating null byte.
50 #define FORMAT_BUFR_SIZE 4096
52 /* -------------------------------------------------------------------------- **
53 * This module implements Samba's debugging utility.
55 * The syntax of a debugging log file is represented as:
57 * <debugfile> :== { <debugmsg> }
59 * <debugmsg> :== <debughdr> '\n' <debugtext>
61 * <debughdr> :== '[' TIME ',' LEVEL ']' [ [FILENAME ':'] [FUNCTION '()'] ]
63 * <debugtext> :== { <debugline> }
65 * <debugline> :== TEXT '\n'
67 * TEXT is a string of characters excluding the newline character.
68 * LEVEL is the DEBUG level of the message (an integer in the range 0..10).
69 * TIME is a timestamp.
70 * FILENAME is the name of the file from which the debug message was generated.
71 * FUNCTION is the function from which the debug message was generated.
73 * Basically, what that all means is:
75 * - A debugging log file is made up of debug messages.
77 * - Each debug message is made up of a header and text. The header is
78 * separated from the text by a newline.
80 * - The header begins with the timestamp and debug level of the message
81 * enclosed in brackets. The filename and function from which the
82 * message was generated may follow. The filename is terminated by a
83 * colon, and the function name is terminated by parenthesis.
85 * - The message text is made up of zero or more lines, each terminated by
86 * a newline.
89 /* state variables for the debug system */
90 static struct {
91 bool initialized;
92 enum debug_logtype logtype; /* The type of logging we are doing: eg stdout, file, stderr */
93 char prog_name[255];
94 char hostname[HOST_NAME_MAX+1];
95 bool reopening_logs;
96 bool schedule_reopen_logs;
97 int forced_log_priority;
99 struct debug_settings settings;
100 debug_callback_fn callback;
101 void *callback_private;
102 char header_str[300];
103 char header_str_no_nl[300];
104 size_t hs_len;
105 char msg_no_nl[FORMAT_BUFR_SIZE];
106 } state = {
107 .settings = {
108 .timestamp_logs = true
112 struct debug_class {
114 * The debug loglevel of the class.
116 int loglevel;
119 * An optional class specific logfile, may be NULL in which case the
120 * "global" logfile is used and fd is -1.
122 char *logfile;
123 int fd;
124 /* inode number of the logfile to detect logfile rotation */
125 ino_t ino;
129 * default_classname_table[] is read in from debug-classname-table.c
130 * so that test_logging.c can use it too.
132 #include "lib/util/debug-classes/debug-classname-table.c"
135 * This is to allow reading of dbgc_config before the debug
136 * system has been initialized.
138 static struct debug_class debug_class_list_initial[ARRAY_SIZE(default_classname_table)] = {
139 [DBGC_ALL] = { .fd = 2 },
142 static size_t debug_num_classes = 0;
143 static struct debug_class *dbgc_config = debug_class_list_initial;
145 static int current_msg_level = 0;
146 static int current_msg_class = 0;
149 * DBG_DEV(): when and how to user it.
151 * As a developer, you sometimes want verbose logging between point A and
152 * point B, where the relationship between these points is not easily defined
153 * in terms of the call stack.
155 * For example, you might be interested in what is going on in functions in
156 * lib/util/util_str.c in an ldap worker process after a particular query. If
157 * you use gdb, something will time out and you won't get the full
158 * conversation. If you add fprintf() or DBG_ERR()s to util_str.c, you'll get
159 * a massive flood, and there's a chance one will accidentally slip into a
160 * release and the whole world will flood. DBG_DEV is a solution.
162 * On start-up, DBG_DEV() is switched OFF. Nothing is printed.
164 * 1. Add `DBG_DEV("formatted msg %d, etc\n", i);` where needed.
166 * 2. At each point you want to start debugging, add `debug_developer_enable()`.
168 * 3. At each point you want debugging to stop, add `debug_developer_disable()`.
170 * In DEVELOPER builds, the message will be printed at level 0, as with
171 * DBG_ERR(). In production builds, the macro resolves to nothing.
173 * The messages are printed with a "<function_name>:DEV:<pid>:" prefix.
176 static bool debug_developer_is_enabled = false;
178 bool debug_developer_enabled(void)
180 return debug_developer_is_enabled;
184 * debug_developer_disable() will turn DBG_DEV() on in the current
185 * process and children.
187 void debug_developer_enable(void)
189 debug_developer_is_enabled = true;
193 * debug_developer_disable() will make DBG_DEV() do nothing in the current
194 * process (and children).
196 void debug_developer_disable(void)
198 debug_developer_is_enabled = false;
202 * Within debug.c, DBG_DEV() always writes to stderr, because some functions
203 * here will attempt infinite recursion with normal DEBUG macros.
205 #ifdef DEVELOPER
206 #undef DBG_DEV
207 #define DBG_DEV(fmt, ...) \
208 (void)((debug_developer_enabled()) \
209 && (fprintf(stderr, "%s:DEV:%d: " fmt "%s", \
210 __func__, getpid(), ##__VA_ARGS__, "")) )
211 #endif
214 #if defined(WITH_SYSLOG) || defined(HAVE_LIBSYSTEMD_JOURNAL) || defined(HAVE_LIBSYSTEMD)
215 static int debug_level_to_priority(int level)
218 * map debug levels to syslog() priorities
220 static const int priority_map[] = {
221 LOG_ERR, /* 0 */
222 LOG_WARNING, /* 1 */
223 LOG_NOTICE, /* 2 */
224 LOG_NOTICE, /* 3 */
225 LOG_NOTICE, /* 4 */
226 LOG_NOTICE, /* 5 */
227 LOG_INFO, /* 6 */
228 LOG_INFO, /* 7 */
229 LOG_INFO, /* 8 */
230 LOG_INFO, /* 9 */
232 int priority;
234 if (state.forced_log_priority != -1) {
235 level = state.forced_log_priority;
238 if (level < 0 || (size_t)level >= ARRAY_SIZE(priority_map))
239 priority = LOG_DEBUG;
240 else
241 priority = priority_map[level];
243 return priority;
245 #endif
247 /* -------------------------------------------------------------------------- **
248 * Produce a version of the given buffer without any trailing newlines.
250 #if defined(HAVE_LIBSYSTEMD_JOURNAL) || defined(HAVE_LIBSYSTEMD) || \
251 defined(HAVE_LTTNG_TRACEF) || defined(HAVE_GPFS)
252 static void copy_no_nl(char *out,
253 size_t out_size,
254 const char *in,
255 size_t in_len)
257 size_t len;
259 * Some backends already add an extra newline, so also provide
260 * a buffer without the newline character.
262 len = MIN(in_len, out_size - 1);
263 if ((len > 0) && (in[len - 1] == '\n')) {
264 len--;
267 memcpy(out, in, len);
268 out[len] = '\0';
271 static void ensure_copy_no_nl(char *out,
272 size_t out_size,
273 const char *in,
274 size_t in_len)
277 * Assume out is a static buffer that is reused as a cache.
278 * If it isn't empty then this has already been done with the
279 * same input.
281 if (out[0] != '\0') {
282 return;
285 copy_no_nl(out, out_size, in, in_len);
287 #endif
289 /* -------------------------------------------------------------------------- **
290 * Debug backends. When logging to DEBUG_FILE, send the log entries to
291 * all active backends.
294 static void debug_file_log(int msg_level, const char *msg, size_t msg_len)
296 struct iovec iov[] = {
298 .iov_base = discard_const(state.header_str),
299 .iov_len = state.hs_len,
302 .iov_base = discard_const(msg),
303 .iov_len = msg_len,
306 ssize_t ret;
307 int fd;
309 check_log_size();
311 if (dbgc_config[current_msg_class].fd != -1) {
312 fd = dbgc_config[current_msg_class].fd;
313 } else {
314 fd = dbgc_config[DBGC_ALL].fd;
317 do {
318 ret = writev(fd, iov, ARRAY_SIZE(iov));
319 } while (ret == -1 && errno == EINTR);
322 #ifdef WITH_SYSLOG
323 static void debug_syslog_reload(bool enabled, bool previously_enabled,
324 const char *prog_name, char *option)
326 if (enabled && !previously_enabled) {
327 const char *ident = NULL;
328 if ((prog_name != NULL) && (prog_name[0] != '\0')) {
329 ident = prog_name;
331 #ifdef LOG_DAEMON
332 openlog(ident, LOG_PID, SYSLOG_FACILITY);
333 #else
334 /* for old systems that have no facility codes. */
335 openlog(ident, LOG_PID);
336 #endif
337 return;
340 if (!enabled && previously_enabled) {
341 closelog();
345 static void debug_syslog_log(int msg_level, const char *msg, size_t msg_len)
347 int priority;
349 priority = debug_level_to_priority(msg_level);
352 * Specify the facility to interoperate with other syslog
353 * callers (vfs_full_audit for example).
355 priority |= SYSLOG_FACILITY;
357 if (state.hs_len > 0) {
358 syslog(priority, "%s", state.header_str);
360 syslog(priority, "%s", msg);
362 #endif /* WITH_SYSLOG */
364 #if defined(HAVE_LIBSYSTEMD_JOURNAL) || defined(HAVE_LIBSYSTEMD)
365 #include <systemd/sd-journal.h>
366 static void debug_systemd_log(int msg_level, const char *msg, size_t msg_len)
368 if (state.hs_len > 0) {
369 size_t len = state.hs_len;
371 if (state.header_str[len - 1] == '\n') {
372 len -= 1;
375 sd_journal_send("MESSAGE=%.*s",
376 (int)len,
377 state.header_str,
378 "PRIORITY=%d",
379 debug_level_to_priority(msg_level),
380 "LEVEL=%d",
381 msg_level,
382 NULL);
385 if ((msg_len > 0) && (msg[msg_len - 1] == '\n')) {
386 msg_len -= 1;
389 sd_journal_send("MESSAGE=%.*s",
390 (int)msg_len,
391 msg,
392 "PRIORITY=%d",
393 debug_level_to_priority(msg_level),
394 "LEVEL=%d",
395 msg_level,
396 NULL);
398 #endif
400 #ifdef HAVE_LTTNG_TRACEF
401 #include <lttng/tracef.h>
402 static void debug_lttng_log(int msg_level, const char *msg, size_t msg_len)
404 if (state.hs_len > 0) {
405 size_t len = state.hs_len;
407 if (state.header_str[len - 1] == '\n') {
408 len -= 1;
411 tracef("%.*s", (int)len, state.header_str);
414 if ((msg_len > 0) && (msg[msg_len - 1] == '\n')) {
415 msg_len -= 1;
417 tracef("%.*s", (int)msg_len, msg);
419 #endif /* WITH_LTTNG_TRACEF */
421 #ifdef HAVE_GPFS
422 #include "gpfswrap.h"
423 static void debug_gpfs_reload(bool enabled, bool previously_enabled,
424 const char *prog_name, char *option)
426 if (enabled) {
427 gpfswrap_init();
430 if (enabled && !previously_enabled) {
431 gpfswrap_init_trace();
432 return;
435 if (!enabled && previously_enabled) {
436 gpfswrap_fini_trace();
437 return;
440 if (enabled) {
442 * Trigger GPFS library to adjust state if necessary.
444 gpfswrap_query_trace();
448 static void debug_gpfs_log(int msg_level, const char *msg, size_t msg_len)
450 if (state.hs_len > 0) {
451 ensure_copy_no_nl(state.header_str_no_nl,
452 sizeof(state.header_str_no_nl),
453 state.header_str,
454 state.hs_len);
455 gpfswrap_add_trace(msg_level, state.header_str_no_nl);
457 ensure_copy_no_nl(state.msg_no_nl,
458 sizeof(state.msg_no_nl),
459 msg, msg_len);
460 gpfswrap_add_trace(msg_level, state.msg_no_nl);
462 #endif /* HAVE_GPFS */
464 #define DEBUG_RINGBUF_SIZE (1024 * 1024)
465 #define DEBUG_RINGBUF_SIZE_OPT "size="
467 static char *debug_ringbuf;
468 static size_t debug_ringbuf_size;
469 static size_t debug_ringbuf_ofs;
471 /* We ensure in debug_ringbuf_log() that this is always \0 terminated */
472 char *debug_get_ringbuf(void)
474 return debug_ringbuf;
477 /* Return the size of the ringbuf (including a \0 terminator) */
478 size_t debug_get_ringbuf_size(void)
480 return debug_ringbuf_size;
483 static void debug_ringbuf_reload(bool enabled, bool previously_enabled,
484 const char *prog_name, char *option)
486 bool cmp;
487 size_t optlen = strlen(DEBUG_RINGBUF_SIZE_OPT);
489 debug_ringbuf_size = DEBUG_RINGBUF_SIZE;
490 debug_ringbuf_ofs = 0;
492 SAFE_FREE(debug_ringbuf);
494 if (!enabled) {
495 return;
498 if (option != NULL) {
499 cmp = strncmp(option, DEBUG_RINGBUF_SIZE_OPT, optlen);
500 if (cmp == 0) {
501 debug_ringbuf_size = (size_t)strtoull(
502 option + optlen, NULL, 10);
506 debug_ringbuf = calloc(debug_ringbuf_size, sizeof(char));
507 if (debug_ringbuf == NULL) {
508 return;
512 static void _debug_ringbuf_log(int msg_level, const char *msg, size_t msg_len)
514 size_t allowed_size;
516 if (debug_ringbuf == NULL) {
517 return;
520 /* Ensure the buffer is always \0 terminated */
521 allowed_size = debug_ringbuf_size - 1;
523 if (msg_len > allowed_size) {
524 return;
527 if ((debug_ringbuf_ofs + msg_len) < debug_ringbuf_ofs) {
528 return;
531 if ((debug_ringbuf_ofs + msg_len) > allowed_size) {
532 debug_ringbuf_ofs = 0;
535 memcpy(debug_ringbuf + debug_ringbuf_ofs, msg, msg_len);
536 debug_ringbuf_ofs += msg_len;
539 static void debug_ringbuf_log(int msg_level, const char *msg, size_t msg_len)
541 if (state.hs_len > 0) {
542 _debug_ringbuf_log(msg_level, state.header_str, state.hs_len);
544 _debug_ringbuf_log(msg_level, msg, msg_len);
547 static struct debug_backend {
548 const char *name;
549 int log_level;
550 int new_log_level;
551 void (*reload)(bool enabled, bool prev_enabled,
552 const char *prog_name, char *option);
553 void (*log)(int msg_level,
554 const char *msg,
555 size_t len);
556 char *option;
557 } debug_backends[] = {
559 .name = "file",
560 .log = debug_file_log,
562 #ifdef WITH_SYSLOG
564 .name = "syslog",
565 .reload = debug_syslog_reload,
566 .log = debug_syslog_log,
568 #endif
570 #if defined(HAVE_LIBSYSTEMD_JOURNAL) || defined(HAVE_LIBSYSTEMD)
572 .name = "systemd",
573 .log = debug_systemd_log,
575 #endif
577 #ifdef HAVE_LTTNG_TRACEF
579 .name = "lttng",
580 .log = debug_lttng_log,
582 #endif
584 #ifdef HAVE_GPFS
586 .name = "gpfs",
587 .reload = debug_gpfs_reload,
588 .log = debug_gpfs_log,
590 #endif
592 .name = "ringbuf",
593 .log = debug_ringbuf_log,
594 .reload = debug_ringbuf_reload,
598 static struct debug_backend *debug_find_backend(const char *name)
600 unsigned i;
602 for (i = 0; i < ARRAY_SIZE(debug_backends); i++) {
603 if (strcmp(name, debug_backends[i].name) == 0) {
604 return &debug_backends[i];
608 return NULL;
612 * parse "backend[:option][@loglevel]
614 static void debug_backend_parse_token(char *tok)
616 char *backend_name_option, *backend_name,*backend_level, *saveptr;
617 char *backend_option;
618 struct debug_backend *b;
621 * First parse into backend[:option] and loglevel
623 backend_name_option = strtok_r(tok, "@\0", &saveptr);
624 if (backend_name_option == NULL) {
625 return;
628 backend_level = strtok_r(NULL, "\0", &saveptr);
631 * Now parse backend[:option]
633 backend_name = strtok_r(backend_name_option, ":\0", &saveptr);
634 if (backend_name == NULL) {
635 return;
638 backend_option = strtok_r(NULL, "\0", &saveptr);
641 * Find and update backend
643 b = debug_find_backend(backend_name);
644 if (b == NULL) {
645 return;
648 if (backend_level == NULL) {
649 b->new_log_level = MAX_DEBUG_LEVEL;
650 } else {
651 b->new_log_level = atoi(backend_level);
654 if (backend_option != NULL) {
655 b->option = strdup(backend_option);
656 if (b->option == NULL) {
657 return;
663 * parse "backend1[:option1][@loglevel1] backend2[option2][@loglevel2] ... "
664 * and enable/disable backends accordingly
666 static void debug_set_backends(const char *param)
668 size_t str_len = strlen(param);
669 char str[str_len+1];
670 char *tok, *saveptr;
671 unsigned i;
674 * initialize new_log_level to detect backends that have been
675 * disabled
677 for (i = 0; i < ARRAY_SIZE(debug_backends); i++) {
678 SAFE_FREE(debug_backends[i].option);
679 debug_backends[i].new_log_level = -1;
682 memcpy(str, param, str_len + 1);
684 tok = strtok_r(str, LIST_SEP, &saveptr);
685 if (tok == NULL) {
686 return;
689 while (tok != NULL) {
690 debug_backend_parse_token(tok);
691 tok = strtok_r(NULL, LIST_SEP, &saveptr);
695 * Let backends react to config changes
697 for (i = 0; i < ARRAY_SIZE(debug_backends); i++) {
698 struct debug_backend *b = &debug_backends[i];
700 if (b->reload) {
701 bool enabled = b->new_log_level > -1;
702 bool previously_enabled = b->log_level > -1;
704 b->reload(enabled, previously_enabled, state.prog_name,
705 b->option);
707 b->log_level = b->new_log_level;
711 static void debug_backends_log(const char *msg, size_t msg_len, int msg_level)
713 size_t i;
716 * Some backends already add an extra newline, so initialize a
717 * buffer without the newline character. It will be filled by
718 * the first backend that needs it.
720 state.msg_no_nl[0] = '\0';
722 for (i = 0; i < ARRAY_SIZE(debug_backends); i++) {
723 if (msg_level <= debug_backends[i].log_level) {
724 debug_backends[i].log(msg_level, msg, msg_len);
728 /* Only log the header once */
729 state.hs_len = 0;
732 int debuglevel_get_class(size_t idx)
734 return dbgc_config[idx].loglevel;
737 void debuglevel_set_class(size_t idx, int level)
739 dbgc_config[idx].loglevel = level;
743 /* -------------------------------------------------------------------------- **
744 * Internal variables.
746 * debug_count - Number of debug messages that have been output.
747 * Used to check log size.
749 * current_msg_level - Internal copy of the message debug level. Written by
750 * dbghdr() and read by Debug1().
752 * format_bufr - Used to format debug messages. The dbgtext() function
753 * prints debug messages to a string, and then passes the
754 * string to format_debug_text(), which uses format_bufr
755 * to build the formatted output.
757 * format_pos - Marks the first free byte of the format_bufr.
760 * log_overflow - When this variable is true, never attempt to check the
761 * size of the log. This is a hack, so that we can write
762 * a message using DEBUG, from open_logs() when we
763 * are unable to open a new log file for some reason.
766 static int debug_count = 0;
767 static char format_bufr[FORMAT_BUFR_SIZE];
768 static size_t format_pos = 0;
769 static bool log_overflow = false;
772 * Define all the debug class selection names here. Names *MUST NOT* contain
773 * white space. There must be one name for each DBGC_<class name>, and they
774 * must be in the table in the order of DBGC_<class name>..
777 static char **classname_table = NULL;
780 /* -------------------------------------------------------------------------- **
781 * Functions...
784 static void debug_init(void);
786 /***************************************************************************
787 Free memory pointed to by global pointers.
788 ****************************************************************************/
790 void gfree_debugsyms(void)
792 unsigned i;
794 TALLOC_FREE(classname_table);
796 if ( dbgc_config != debug_class_list_initial ) {
797 TALLOC_FREE( dbgc_config );
798 dbgc_config = discard_const_p(struct debug_class,
799 debug_class_list_initial);
802 debug_num_classes = 0;
804 state.initialized = false;
806 for (i = 0; i < ARRAY_SIZE(debug_backends); i++) {
807 SAFE_FREE(debug_backends[i].option);
811 /****************************************************************************
812 utility lists registered debug class names's
813 ****************************************************************************/
815 char *debug_list_class_names_and_levels(void)
817 char *buf = talloc_strdup(NULL, "");
818 size_t i;
819 /* prepare strings */
820 for (i = 0; i < debug_num_classes; i++) {
821 talloc_asprintf_addbuf(&buf,
822 "%s:%d%s",
823 classname_table[i],
824 dbgc_config[i].loglevel,
825 i == (debug_num_classes - 1) ? "\n" : " ");
827 return buf;
830 /****************************************************************************
831 Utility to translate names to debug class index's (internal version).
832 ****************************************************************************/
834 static int debug_lookup_classname_int(const char* classname)
836 size_t i;
838 if (classname == NULL) {
839 return -1;
842 for (i=0; i < debug_num_classes; i++) {
843 char *entry = classname_table[i];
844 if (entry != NULL && strcmp(classname, entry)==0) {
845 return i;
848 return -1;
851 /****************************************************************************
852 Add a new debug class to the system.
853 ****************************************************************************/
855 int debug_add_class(const char *classname)
857 int ndx;
858 struct debug_class *new_class_list = NULL;
859 char **new_name_list;
860 int default_level;
862 if (classname == NULL) {
863 return -1;
866 /* check the init has yet been called */
867 debug_init();
869 ndx = debug_lookup_classname_int(classname);
870 if (ndx >= 0) {
871 return ndx;
873 ndx = debug_num_classes;
875 if (dbgc_config == debug_class_list_initial) {
876 /* Initial loading... */
877 new_class_list = NULL;
878 } else {
879 new_class_list = dbgc_config;
882 default_level = dbgc_config[DBGC_ALL].loglevel;
884 new_class_list = talloc_realloc(NULL,
885 new_class_list,
886 struct debug_class,
887 ndx + 1);
888 if (new_class_list == NULL) {
889 return -1;
892 dbgc_config = new_class_list;
894 dbgc_config[ndx] = (struct debug_class) {
895 .loglevel = default_level,
896 .fd = -1,
899 new_name_list = talloc_realloc(NULL, classname_table, char *, ndx + 1);
900 if (new_name_list == NULL) {
901 return -1;
903 classname_table = new_name_list;
905 classname_table[ndx] = talloc_strdup(classname_table, classname);
906 if (classname_table[ndx] == NULL) {
907 return -1;
910 debug_num_classes = ndx + 1;
912 return ndx;
915 /****************************************************************************
916 Utility to translate names to debug class index's (public version).
917 ****************************************************************************/
919 static int debug_lookup_classname(const char *classname)
921 int ndx;
923 if (classname == NULL || !*classname)
924 return -1;
926 ndx = debug_lookup_classname_int(classname);
928 if (ndx != -1)
929 return ndx;
931 DBG_WARNING("Unknown classname[%s] -> adding it...\n", classname);
932 return debug_add_class(classname);
935 /****************************************************************************
936 Dump the current registered debug levels.
937 ****************************************************************************/
939 static void debug_dump_status(int level)
941 size_t q;
943 DEBUG(level, ("INFO: Current debug levels:\n"));
944 for (q = 0; q < debug_num_classes; q++) {
945 const char *classname = classname_table[q];
946 DEBUGADD(level, (" %s: %d\n",
947 classname,
948 dbgc_config[q].loglevel));
952 static bool debug_parse_param(char *param)
954 char *class_name;
955 char *class_file = NULL;
956 char *class_level;
957 char *saveptr = NULL;
958 int ndx;
960 class_name = strtok_r(param, ":", &saveptr);
961 if (class_name == NULL) {
962 return false;
965 class_level = strtok_r(NULL, "@\0", &saveptr);
966 if (class_level == NULL) {
967 return false;
970 class_file = strtok_r(NULL, "\0", &saveptr);
972 ndx = debug_lookup_classname(class_name);
973 if (ndx == -1) {
974 return false;
977 dbgc_config[ndx].loglevel = atoi(class_level);
979 if (class_file == NULL) {
980 return true;
983 TALLOC_FREE(dbgc_config[ndx].logfile);
985 dbgc_config[ndx].logfile = talloc_strdup(NULL, class_file);
986 if (dbgc_config[ndx].logfile == NULL) {
987 return false;
989 return true;
992 /****************************************************************************
993 Parse the debug levels from smb.conf. Example debug level string:
994 3 tdb:5 printdrivers:7
995 Note: the 1st param has no "name:" preceding it.
996 ****************************************************************************/
998 bool debug_parse_levels(const char *params_str)
1000 size_t str_len = strlen(params_str);
1001 char str[str_len+1];
1002 char *tok, *saveptr;
1003 size_t i;
1005 /* Just in case */
1006 debug_init();
1008 memcpy(str, params_str, str_len+1);
1010 tok = strtok_r(str, LIST_SEP, &saveptr);
1011 if (tok == NULL) {
1012 return true;
1015 /* Allow DBGC_ALL to be specified w/o requiring its class name e.g."10"
1016 * v.s. "all:10", this is the traditional way to set DEBUGLEVEL
1018 if (isdigit(tok[0])) {
1019 dbgc_config[DBGC_ALL].loglevel = atoi(tok);
1020 tok = strtok_r(NULL, LIST_SEP, &saveptr);
1021 } else {
1022 dbgc_config[DBGC_ALL].loglevel = 0;
1025 /* Array is debug_num_classes long */
1026 for (i = DBGC_ALL+1; i < debug_num_classes; i++) {
1027 dbgc_config[i].loglevel = dbgc_config[DBGC_ALL].loglevel;
1028 TALLOC_FREE(dbgc_config[i].logfile);
1031 while (tok != NULL) {
1032 bool ok;
1034 ok = debug_parse_param(tok);
1035 if (!ok) {
1036 DEBUG(0,("debug_parse_params: unrecognized debug "
1037 "class name or format [%s]\n", tok));
1038 return false;
1041 tok = strtok_r(NULL, LIST_SEP, &saveptr);
1044 debug_dump_status(5);
1046 return true;
1049 /* setup for logging of talloc warnings */
1050 static void talloc_log_fn(const char *msg)
1052 DEBUG(0,("%s", msg));
1055 void debug_setup_talloc_log(void)
1057 talloc_set_log_fn(talloc_log_fn);
1061 /****************************************************************************
1062 Init debugging (one time stuff)
1063 ****************************************************************************/
1065 static void debug_init(void)
1067 size_t i;
1069 if (state.initialized)
1070 return;
1072 state.initialized = true;
1074 debug_setup_talloc_log();
1076 for (i = 0; i < ARRAY_SIZE(default_classname_table); i++) {
1077 debug_add_class(default_classname_table[i]);
1079 dbgc_config[DBGC_ALL].fd = 2;
1081 for (i = 0; i < ARRAY_SIZE(debug_backends); i++) {
1082 debug_backends[i].log_level = -1;
1083 debug_backends[i].new_log_level = -1;
1087 void debug_set_settings(struct debug_settings *settings,
1088 const char *logging_param,
1089 int syslog_level, bool syslog_only)
1091 char fake_param[256];
1092 size_t len = 0;
1095 * This forces in some smb.conf derived values into the debug
1096 * system. There are no pointers in this structure, so we can
1097 * just structure-assign it in
1099 state.settings = *settings;
1102 * If 'logging' is not set, create backend settings from
1103 * deprecated 'syslog' and 'syslog only' parameters
1105 if (logging_param != NULL) {
1106 len = strlen(logging_param);
1108 if (len == 0) {
1109 if (syslog_only) {
1110 snprintf(fake_param, sizeof(fake_param),
1111 "syslog@%d", syslog_level - 1);
1112 } else {
1113 snprintf(fake_param, sizeof(fake_param),
1114 "syslog@%d file@%d", syslog_level -1,
1115 MAX_DEBUG_LEVEL);
1118 logging_param = fake_param;
1121 debug_set_backends(logging_param);
1124 static void ensure_hostname(void)
1126 int ret;
1128 if (state.hostname[0] != '\0') {
1129 return;
1132 ret = gethostname(state.hostname, sizeof(state.hostname));
1133 if (ret != 0) {
1134 strlcpy(state.hostname, "unknown", sizeof(state.hostname));
1135 return;
1139 * Ensure NUL termination, since POSIX isn't clear about that.
1141 * Don't worry about truncating at the first '.' or similar,
1142 * since this is usually not fully qualified. Trying to
1143 * truncate opens up the multibyte character gates of hell.
1145 state.hostname[sizeof(state.hostname) - 1] = '\0';
1148 void debug_set_hostname(const char *name)
1150 strlcpy(state.hostname, name, sizeof(state.hostname));
1153 void debug_set_forced_log_priority(int forced_log_priority)
1155 state.forced_log_priority = forced_log_priority;
1159 * Ensure debug logs are initialised.
1161 * setup_logging() is called to direct logging to the correct outputs, whether
1162 * those be stderr, stdout, files, or syslog, and set the program name used in
1163 * the logs. It can be called multiple times.
1165 * There is an order of precedence to the log type. Once set to DEBUG_FILE, it
1166 * cannot be reset DEFAULT_DEBUG_STDERR, but can be set to DEBUG_STDERR, after
1167 * which DEBUG_FILE is unavailable). This makes it possible to override for
1168 * debug to stderr on the command line, as the smb.conf cannot reset it back
1169 * to file-based logging. See enum debug_logtype.
1171 * @param prog_name the program name. Directory path component will be
1172 * ignored.
1174 * @param new_logtype the requested destination for the debug log,
1175 * as an enum debug_logtype.
1177 void setup_logging(const char *prog_name, enum debug_logtype new_logtype)
1179 debug_init();
1180 if (state.logtype < new_logtype) {
1181 state.logtype = new_logtype;
1183 if (prog_name) {
1184 const char *p = strrchr(prog_name, '/');
1186 if (p) {
1187 prog_name = p + 1;
1190 strlcpy(state.prog_name, prog_name, sizeof(state.prog_name));
1192 reopen_logs_internal();
1195 /***************************************************************************
1196 Set the logfile name.
1197 **************************************************************************/
1199 void debug_set_logfile(const char *name)
1201 if (name == NULL || *name == 0) {
1202 /* this copes with calls when smb.conf is not loaded yet */
1203 return;
1205 TALLOC_FREE(dbgc_config[DBGC_ALL].logfile);
1206 dbgc_config[DBGC_ALL].logfile = talloc_strdup(NULL, name);
1208 reopen_logs_internal();
1211 static void debug_close_fd(int fd)
1213 if (fd > 2) {
1214 close(fd);
1218 enum debug_logtype debug_get_log_type(void)
1220 return state.logtype;
1223 bool debug_get_output_is_stderr(void)
1225 return (state.logtype == DEBUG_DEFAULT_STDERR) || (state.logtype == DEBUG_STDERR);
1228 bool debug_get_output_is_stdout(void)
1230 return (state.logtype == DEBUG_DEFAULT_STDOUT) || (state.logtype == DEBUG_STDOUT);
1233 void debug_set_callback(void *private_ptr, debug_callback_fn fn)
1235 debug_init();
1236 if (fn) {
1237 state.logtype = DEBUG_CALLBACK;
1238 state.callback_private = private_ptr;
1239 state.callback = fn;
1240 } else {
1241 state.logtype = DEBUG_DEFAULT_STDERR;
1242 state.callback_private = NULL;
1243 state.callback = NULL;
1247 static void debug_callback_log(const char *msg, size_t msg_len, int msg_level)
1249 char msg_copy[msg_len];
1251 if ((msg_len > 0) && (msg[msg_len-1] == '\n')) {
1252 memcpy(msg_copy, msg, msg_len-1);
1253 msg_copy[msg_len-1] = '\0';
1254 msg = msg_copy;
1257 state.callback(state.callback_private, msg_level, msg);
1260 /**************************************************************************
1261 reopen the log files
1262 note that we now do this unconditionally
1263 We attempt to open the new debug fp before closing the old. This means
1264 if we run out of fd's we just keep using the old fd rather than aborting.
1265 Fix from dgibson@linuxcare.com.
1266 **************************************************************************/
1268 static bool reopen_one_log(struct debug_class *config)
1270 int old_fd = config->fd;
1271 const char *logfile = config->logfile;
1272 struct stat st;
1273 int new_fd;
1274 int ret;
1276 if (logfile == NULL) {
1277 debug_close_fd(old_fd);
1278 config->fd = -1;
1279 return true;
1282 new_fd = open(logfile, O_WRONLY|O_APPEND|O_CREAT, 0644);
1283 if (new_fd == -1) {
1284 log_overflow = true;
1285 DBG_ERR("Unable to open new log file '%s': %s\n",
1286 logfile, strerror(errno));
1287 log_overflow = false;
1288 return false;
1291 debug_close_fd(old_fd);
1292 smb_set_close_on_exec(new_fd);
1293 config->fd = new_fd;
1295 ret = fstat(new_fd, &st);
1296 if (ret != 0) {
1297 log_overflow = true;
1298 DBG_ERR("Unable to fstat() new log file '%s': %s\n",
1299 logfile, strerror(errno));
1300 log_overflow = false;
1301 return false;
1304 config->ino = st.st_ino;
1305 return true;
1309 reopen the log file (usually called because the log file name might have changed)
1311 bool reopen_logs_internal(void)
1313 struct debug_backend *b = NULL;
1314 mode_t oldumask;
1315 size_t i;
1316 bool ok = true;
1318 if (state.reopening_logs) {
1319 return true;
1322 /* Now clear the SIGHUP induced flag */
1323 state.schedule_reopen_logs = false;
1325 switch (state.logtype) {
1326 case DEBUG_CALLBACK:
1327 return true;
1328 case DEBUG_STDOUT:
1329 case DEBUG_DEFAULT_STDOUT:
1330 debug_close_fd(dbgc_config[DBGC_ALL].fd);
1331 dbgc_config[DBGC_ALL].fd = 1;
1332 return true;
1334 case DEBUG_DEFAULT_STDERR:
1335 case DEBUG_STDERR:
1336 debug_close_fd(dbgc_config[DBGC_ALL].fd);
1337 dbgc_config[DBGC_ALL].fd = 2;
1338 return true;
1340 case DEBUG_FILE:
1341 b = debug_find_backend("file");
1342 assert(b != NULL);
1344 b->log_level = MAX_DEBUG_LEVEL;
1345 break;
1348 oldumask = umask( 022 );
1350 for (i = DBGC_ALL; i < debug_num_classes; i++) {
1351 if (dbgc_config[i].logfile != NULL) {
1352 break;
1355 if (i == debug_num_classes) {
1356 return false;
1359 state.reopening_logs = true;
1361 for (i = DBGC_ALL; i < debug_num_classes; i++) {
1362 ok = reopen_one_log(&dbgc_config[i]);
1363 if (!ok) {
1364 break;
1368 /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
1369 * to fix problem where smbd's that generate less
1370 * than 100 messages keep growing the log.
1372 force_check_log_size();
1373 (void)umask(oldumask);
1376 * If log file was opened or created successfully, take over stderr to
1377 * catch output into logs.
1379 if (!state.settings.debug_no_stderr_redirect &&
1380 dbgc_config[DBGC_ALL].fd > 0) {
1381 if (dup2(dbgc_config[DBGC_ALL].fd, 2) == -1) {
1382 /* Close stderr too, if dup2 can't point it -
1383 at the logfile. There really isn't much
1384 that can be done on such a fundamental
1385 failure... */
1386 close_low_fd(2);
1390 state.reopening_logs = false;
1392 return ok;
1395 /**************************************************************************
1396 Force a check of the log size.
1397 ***************************************************************************/
1399 void force_check_log_size( void )
1401 debug_count = 100;
1404 _PUBLIC_ void debug_schedule_reopen_logs(void)
1406 state.schedule_reopen_logs = true;
1410 /***************************************************************************
1411 Check to see if there is any need to check if the logfile has grown too big.
1412 **************************************************************************/
1414 bool need_to_check_log_size(void)
1416 int maxlog;
1417 size_t i;
1419 if (debug_count < 100) {
1420 return false;
1423 maxlog = state.settings.max_log_size * 1024;
1424 if (maxlog <= 0) {
1425 debug_count = 0;
1426 return false;
1429 if (dbgc_config[DBGC_ALL].fd > 2) {
1430 return true;
1433 for (i = DBGC_ALL + 1; i < debug_num_classes; i++) {
1434 if (dbgc_config[i].fd != -1) {
1435 return true;
1439 debug_count = 0;
1440 return false;
1443 /**************************************************************************
1444 Check to see if the log has grown to be too big.
1445 **************************************************************************/
1447 static void do_one_check_log_size(off_t maxlog, struct debug_class *config)
1449 char name[strlen(config->logfile) + 5];
1450 struct stat st;
1451 int ret;
1452 bool reopen = false;
1453 bool ok;
1455 if (maxlog == 0) {
1456 return;
1459 ret = stat(config->logfile, &st);
1460 if (ret != 0) {
1461 return;
1463 if (st.st_size >= maxlog ) {
1464 reopen = true;
1467 if (st.st_ino != config->ino) {
1468 reopen = true;
1471 if (!reopen) {
1472 return;
1475 /* reopen_logs_internal() modifies *_fd */
1476 (void)reopen_logs_internal();
1478 if (config->fd <= 2) {
1479 return;
1481 ret = fstat(config->fd, &st);
1482 if (ret != 0) {
1483 config->ino = (ino_t)0;
1484 return;
1487 config->ino = st.st_ino;
1489 if (st.st_size < maxlog) {
1490 return;
1493 snprintf(name, sizeof(name), "%s.old", config->logfile);
1495 (void)rename(config->logfile, name);
1497 ok = reopen_logs_internal();
1498 if (ok) {
1499 return;
1501 /* We failed to reopen a log - continue using the old name. */
1502 (void)rename(name, config->logfile);
1505 static void do_check_log_size(off_t maxlog)
1507 size_t i;
1509 for (i = DBGC_ALL; i < debug_num_classes; i++) {
1510 if (dbgc_config[i].fd == -1) {
1511 continue;
1513 if (dbgc_config[i].logfile == NULL) {
1514 continue;
1516 do_one_check_log_size(maxlog, &dbgc_config[i]);
1520 void check_log_size( void )
1522 off_t maxlog;
1524 if (geteuid() != 0) {
1526 * We need to be root to change the log file (tests use a fake
1527 * geteuid() from third_party/uid_wrapper). Otherwise we skip
1528 * this and let the main smbd loop or some other process do
1529 * the work.
1531 return;
1534 if(log_overflow || (!state.schedule_reopen_logs && !need_to_check_log_size())) {
1535 return;
1538 maxlog = state.settings.max_log_size * 1024;
1540 if (state.schedule_reopen_logs) {
1541 (void)reopen_logs_internal();
1544 do_check_log_size(maxlog);
1547 * Here's where we need to panic if dbgc_config[DBGC_ALL].fd == 0 or -1
1548 * (invalid values)
1551 if (dbgc_config[DBGC_ALL].fd <= 0) {
1552 /* This code should only be reached in very strange
1553 * circumstances. If we merely fail to open the new log we
1554 * should stick with the old one. ergo this should only be
1555 * reached when opening the logs for the first time: at
1556 * startup or when the log level is increased from zero.
1557 * -dwg 6 June 2000
1559 int fd = open( "/dev/console", O_WRONLY, 0);
1560 if (fd != -1) {
1561 smb_set_close_on_exec(fd);
1562 dbgc_config[DBGC_ALL].fd = fd;
1563 DBG_ERR("check_log_size: open of debug file %s failed "
1564 "- using console.\n",
1565 dbgc_config[DBGC_ALL].logfile);
1566 } else {
1568 * We cannot continue without a debug file handle.
1570 abort();
1573 debug_count = 0;
1576 /*************************************************************************
1577 Write an debug message on the debugfile.
1578 This is called by format_debug_text().
1579 ************************************************************************/
1581 static void Debug1(const char *msg, size_t msg_len)
1583 int old_errno = errno;
1585 debug_count++;
1587 switch(state.logtype) {
1588 case DEBUG_CALLBACK:
1589 debug_callback_log(msg, msg_len, current_msg_level);
1590 break;
1591 case DEBUG_STDOUT:
1592 case DEBUG_STDERR:
1593 case DEBUG_DEFAULT_STDOUT:
1594 case DEBUG_DEFAULT_STDERR:
1595 if (state.settings.debug_syslog_format ==
1596 DEBUG_SYSLOG_FORMAT_ALWAYS) {
1597 debug_file_log(current_msg_level, msg, msg_len);
1598 } else {
1599 if (dbgc_config[DBGC_ALL].fd > 0) {
1600 ssize_t ret;
1601 do {
1602 ret = write(dbgc_config[DBGC_ALL].fd,
1603 msg,
1604 msg_len);
1605 } while (ret == -1 && errno == EINTR);
1608 break;
1609 case DEBUG_FILE:
1610 debug_backends_log(msg, msg_len, current_msg_level);
1611 break;
1614 errno = old_errno;
1617 /**************************************************************************
1618 Print the buffer content via Debug1(), then reset the buffer.
1619 Input: none
1620 Output: none
1621 ****************************************************************************/
1623 static void bufr_print( void )
1625 format_bufr[format_pos] = '\0';
1626 (void)Debug1(format_bufr, format_pos);
1627 format_pos = 0;
1631 * If set (by tevent_thread_call_depth_set()) to value > 0, debug code will use
1632 * it for the trace indentation.
1634 static size_t debug_call_depth = 0;
1636 size_t *debug_call_depth_addr(void)
1638 return &debug_call_depth;
1641 /***************************************************************************
1642 Format the debug message text.
1644 Input: msg - Text to be added to the "current" debug message text.
1646 Output: none.
1648 Notes: The purpose of this is two-fold. First, each call to syslog()
1649 (used by Debug1(), see above) generates a new line of syslog
1650 output. This is fixed by storing the partial lines until the
1651 newline character is encountered. Second, printing the debug
1652 message lines when a newline is encountered allows us to add
1653 spaces, thus indenting the body of the message and making it
1654 more readable.
1655 **************************************************************************/
1657 static void format_debug_text( const char *msg )
1659 size_t i;
1660 bool timestamp = (state.logtype == DEBUG_FILE && (state.settings.timestamp_logs));
1662 debug_init();
1664 for( i = 0; msg[i]; i++ ) {
1665 /* Indent two spaces at each new line. */
1666 if(timestamp && 0 == format_pos) {
1667 /* Limit the maximum indentation to 20 levels */
1668 size_t depth = MIN(20, debug_call_depth);
1669 format_bufr[0] = format_bufr[1] = ' ';
1670 format_pos = 2;
1672 * Indent by four spaces for each depth level,
1673 * but only if the current debug level is >= 8.
1675 if (depth > 0 && debuglevel_get() >= 8 &&
1676 format_pos + 4 * depth < FORMAT_BUFR_SIZE) {
1677 memset(&format_bufr[format_pos],
1678 ' ',
1679 4 * depth);
1680 format_pos += 4 * depth;
1684 /* If there's room, copy the character to the format buffer. */
1685 if (format_pos < FORMAT_BUFR_SIZE - 1)
1686 format_bufr[format_pos++] = msg[i];
1688 /* If a newline is encountered, print & restart. */
1689 if( '\n' == msg[i] )
1690 bufr_print();
1692 /* If the buffer is full dump it out, reset it, and put out a line
1693 * continuation indicator.
1695 if (format_pos >= FORMAT_BUFR_SIZE - 1) {
1696 const char cont[] = " +>\n";
1697 bufr_print();
1698 (void)Debug1(cont , sizeof(cont) - 1);
1702 /* Just to be safe... */
1703 format_bufr[format_pos] = '\0';
1706 /***************************************************************************
1707 Flush debug output, including the format buffer content.
1709 Input: none
1710 Output: none
1711 ***************************************************************************/
1713 void dbgflush( void )
1715 bufr_print();
1718 bool dbgsetclass(int level, int cls)
1720 /* Set current_msg_level. */
1721 current_msg_level = level;
1723 /* Set current message class */
1724 current_msg_class = cls;
1726 return true;
1729 /***************************************************************************
1730 Put a Debug Header into header_str.
1732 Input: level - Debug level of the message (not the system-wide debug
1733 level. )
1734 cls - Debuglevel class of the calling module.
1735 location - Pointer to a string containing the name of the file
1736 from which this function was called, or an empty string
1737 if the __FILE__ macro is not implemented.
1738 func - Pointer to a string containing the name of the function
1739 from which this function was called, or an empty string
1740 if the __FUNCTION__ macro is not implemented.
1742 Output: Always true. This makes it easy to fudge a call to dbghdr()
1743 in a macro, since the function can be called as part of a test.
1744 Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
1746 Notes: This function takes care of setting current_msg_level.
1748 ****************************************************************************/
1750 bool dbghdrclass(int level, int cls, const char *location, const char *func)
1752 /* Ensure we don't lose any real errno value. */
1753 int old_errno = errno;
1754 bool verbose = false;
1755 struct timeval tv;
1756 struct timeval_buf tvbuf;
1759 * This might be overkill, but if another early return is
1760 * added later then initialising these avoids potential
1761 * problems
1763 state.hs_len = 0;
1764 state.header_str[0] = '\0';
1766 if( format_pos ) {
1767 /* This is a fudge. If there is stuff sitting in the format_bufr, then
1768 * the *right* thing to do is to call
1769 * format_debug_text( "\n" );
1770 * to write the remainder, and then proceed with the new header.
1771 * Unfortunately, there are several places in the code at which
1772 * the DEBUG() macro is used to build partial lines. That in mind,
1773 * we'll work under the assumption that an incomplete line indicates
1774 * that a new header is *not* desired.
1776 return( true );
1779 dbgsetclass(level, cls);
1782 * Don't print a header if we're logging to stdout,
1783 * unless 'debug syslog format = always'
1785 if (state.logtype != DEBUG_FILE &&
1786 state.settings.debug_syslog_format != DEBUG_SYSLOG_FORMAT_ALWAYS)
1788 return true;
1792 * Print the header if timestamps (or debug syslog format) is
1793 * turned on. If parameters are not yet loaded, then default
1794 * to timestamps on.
1796 if (!(state.settings.timestamp_logs ||
1797 state.settings.debug_prefix_timestamp ||
1798 state.settings.debug_syslog_format != DEBUG_SYSLOG_FORMAT_NO))
1800 return true;
1803 GetTimeOfDay(&tv);
1805 if (state.settings.debug_syslog_format != DEBUG_SYSLOG_FORMAT_NO) {
1806 if (state.settings.debug_hires_timestamp) {
1807 timeval_str_buf(&tv, true, true, &tvbuf);
1808 } else {
1809 time_t t;
1810 struct tm *tm;
1812 t = (time_t)tv.tv_sec;
1813 tm = localtime(&t);
1814 if (tm != NULL) {
1815 size_t len;
1816 len = strftime(tvbuf.buf,
1817 sizeof(tvbuf.buf),
1818 "%b %e %T",
1819 tm);
1820 if (len == 0) {
1821 /* Trigger default time format below */
1822 tm = NULL;
1825 if (tm == NULL) {
1826 snprintf(tvbuf.buf,
1827 sizeof(tvbuf.buf),
1828 "%ld seconds since the Epoch", (long)t);
1832 ensure_hostname();
1833 state.hs_len = snprintf(state.header_str,
1834 sizeof(state.header_str),
1835 "%s %.*s %s[%u]: ",
1836 tvbuf.buf,
1837 (int)(sizeof(state.hostname) - 1),
1838 state.hostname,
1839 state.prog_name,
1840 (unsigned int) getpid());
1842 goto full;
1845 timeval_str_buf(&tv, false, state.settings.debug_hires_timestamp,
1846 &tvbuf);
1848 state.hs_len = snprintf(state.header_str,
1849 sizeof(state.header_str),
1850 "[%s, %2d",
1851 tvbuf.buf,
1852 level);
1853 if (state.hs_len >= sizeof(state.header_str) - 1) {
1854 goto full;
1857 if (unlikely(dbgc_config[cls].loglevel >= 10)) {
1858 verbose = true;
1861 if (verbose || state.settings.debug_pid) {
1862 state.hs_len += snprintf(state.header_str + state.hs_len,
1863 sizeof(state.header_str) - state.hs_len,
1864 ", pid=%u",
1865 (unsigned int)getpid());
1866 if (state.hs_len >= sizeof(state.header_str) - 1) {
1867 goto full;
1871 if (verbose || state.settings.debug_uid) {
1872 state.hs_len += snprintf(state.header_str + state.hs_len,
1873 sizeof(state.header_str) - state.hs_len,
1874 ", effective(%u, %u), real(%u, %u)",
1875 (unsigned int)geteuid(),
1876 (unsigned int)getegid(),
1877 (unsigned int)getuid(),
1878 (unsigned int)getgid());
1879 if (state.hs_len >= sizeof(state.header_str) - 1) {
1880 goto full;
1884 if ((verbose || state.settings.debug_class)
1885 && (cls != DBGC_ALL)) {
1886 state.hs_len += snprintf(state.header_str + state.hs_len,
1887 sizeof(state.header_str) - state.hs_len,
1888 ", class=%s",
1889 classname_table[cls]);
1890 if (state.hs_len >= sizeof(state.header_str) - 1) {
1891 goto full;
1895 if (debug_traceid_get() != 0) {
1896 state.hs_len += snprintf(state.header_str + state.hs_len,
1897 sizeof(state.header_str) - state.hs_len,
1898 ", traceid=%" PRIu64,
1899 debug_traceid_get());
1900 if (state.hs_len >= sizeof(state.header_str) - 1) {
1901 goto full;
1905 if (debug_call_depth > 0) {
1906 state.hs_len += snprintf(state.header_str + state.hs_len,
1907 sizeof(state.header_str) - state.hs_len,
1908 ", depth=%zu",
1909 debug_call_depth);
1910 if (state.hs_len >= sizeof(state.header_str) - 1) {
1911 goto full;
1915 state.header_str[state.hs_len] = ']';
1916 state.hs_len++;
1917 if (state.hs_len < sizeof(state.header_str) - 1) {
1918 state.header_str[state.hs_len] = ' ';
1919 state.hs_len++;
1921 state.header_str[state.hs_len] = '\0';
1923 if (!state.settings.debug_prefix_timestamp) {
1924 state.hs_len += snprintf(state.header_str + state.hs_len,
1925 sizeof(state.header_str) - state.hs_len,
1926 "%s(%s)\n",
1927 location,
1928 func);
1929 if (state.hs_len >= sizeof(state.header_str)) {
1930 goto full;
1934 full:
1936 * Above code never overflows state.header_str and always
1937 * NUL-terminates correctly. However, state.hs_len can point
1938 * past the end of the buffer to indicate that truncation
1939 * occurred, so fix it if necessary, since state.hs_len is
1940 * expected to be used after return.
1942 if (state.hs_len >= sizeof(state.header_str)) {
1943 state.hs_len = sizeof(state.header_str) - 1;
1946 state.header_str_no_nl[0] = '\0';
1948 errno = old_errno;
1949 return( true );
1952 /***************************************************************************
1953 Add text to the body of the "current" debug message via the format buffer.
1955 Input: format_str - Format string, as used in printf(), et. al.
1956 ... - Variable argument list.
1958 ..or.. va_alist - Old style variable parameter list starting point.
1960 Output: Always true. See dbghdr() for more info, though this is not
1961 likely to be used in the same way.
1963 ***************************************************************************/
1965 static inline bool __dbgtext_va(const char *format_str, va_list ap) PRINTF_ATTRIBUTE(1,0);
1966 static inline bool __dbgtext_va(const char *format_str, va_list ap)
1968 char *msgbuf = NULL;
1969 bool ret = true;
1970 int res;
1972 res = vasprintf(&msgbuf, format_str, ap);
1973 if (res != -1) {
1974 format_debug_text(msgbuf);
1975 } else {
1976 ret = false;
1978 SAFE_FREE(msgbuf);
1979 return ret;
1982 bool dbgtext_va(const char *format_str, va_list ap)
1984 return __dbgtext_va(format_str, ap);
1987 bool dbgtext(const char *format_str, ... )
1989 va_list ap;
1990 bool ret;
1992 va_start(ap, format_str);
1993 ret = __dbgtext_va(format_str, ap);
1994 va_end(ap);
1996 return ret;
1999 static uint64_t debug_traceid = 0;
2001 uint64_t debug_traceid_set(uint64_t id)
2003 uint64_t old_id = debug_traceid;
2004 debug_traceid = id;
2005 return old_id;
2008 uint64_t debug_traceid_get(void)
2010 return debug_traceid;