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/>.
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"
32 #include "util_strlist.h" /* LIST_SEP */
37 /* define what facility to use for syslog */
38 #ifndef SYSLOG_FACILITY
39 #define SYSLOG_FACILITY LOG_DAEMON
42 /* -------------------------------------------------------------------------- **
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
89 /* state variables for the debug system */
92 enum debug_logtype logtype
; /* The type of logging we are doing: eg stdout, file, stderr */
94 char hostname
[HOST_NAME_MAX
+1];
96 bool schedule_reopen_logs
;
98 struct debug_settings settings
;
99 debug_callback_fn callback
;
100 void *callback_private
;
101 char header_str
[300];
102 char header_str_no_nl
[300];
104 char msg_no_nl
[FORMAT_BUFR_SIZE
];
107 .timestamp_logs
= true
113 * The debug loglevel of the class.
118 * An optional class specific logfile, may be NULL in which case the
119 * "global" logfile is used and fd is -1.
123 /* inode number of the logfile to detect logfile rotation */
128 * default_classname_table[] is read in from debug-classname-table.c
129 * so that test_logging.c can use it too.
131 #include "lib/util/debug-classes/debug-classname-table.c"
134 * This is to allow reading of dbgc_config before the debug
135 * system has been initialized.
137 static struct debug_class debug_class_list_initial
[ARRAY_SIZE(default_classname_table
)] = {
138 [DBGC_ALL
] = { .fd
= 2 },
141 static size_t debug_num_classes
= 0;
142 static struct debug_class
*dbgc_config
= debug_class_list_initial
;
144 static int current_msg_level
= 0;
145 static int current_msg_class
= 0;
148 * DBG_DEV(): when and how to user it.
150 * As a developer, you sometimes want verbose logging between point A and
151 * point B, where the relationship between these points is not easily defined
152 * in terms of the call stack.
154 * For example, you might be interested in what is going on in functions in
155 * lib/util/util_str.c in an ldap worker process after a particular query. If
156 * you use gdb, something will time out and you won't get the full
157 * conversation. If you add fprintf() or DBG_ERR()s to util_str.c, you'll get
158 * a massive flood, and there's a chance one will accidentally slip into a
159 * release and the whole world will flood. DBG_DEV is a solution.
161 * On start-up, DBG_DEV() is switched OFF. Nothing is printed.
163 * 1. Add `DBG_DEV("formatted msg %d, etc\n", i);` where needed.
165 * 2. At each point you want to start debugging, add `debug_developer_enable()`.
167 * 3. At each point you want debugging to stop, add `debug_developer_disable()`.
169 * In DEVELOPER builds, the message will be printed at level 0, as with
170 * DBG_ERR(). In production builds, the macro resolves to nothing.
172 * The messages are printed with a "<function_name>:DEV:<pid>:" prefix.
175 static bool debug_developer_is_enabled
= false;
177 bool debug_developer_enabled(void)
179 return debug_developer_is_enabled
;
183 * debug_developer_disable() will turn DBG_DEV() on in the current
184 * process and children.
186 void debug_developer_enable(void)
188 debug_developer_is_enabled
= true;
192 * debug_developer_disable() will make DBG_DEV() do nothing in the current
193 * process (and children).
195 void debug_developer_disable(void)
197 debug_developer_is_enabled
= false;
201 * Within debug.c, DBG_DEV() always writes to stderr, because some functions
202 * here will attempt infinite recursion with normal DEBUG macros.
206 #define DBG_DEV(fmt, ...) \
207 (void)((debug_developer_enabled()) \
208 && (fprintf(stderr, "%s:DEV:%d: " fmt "%s", \
209 __func__, getpid(), ##__VA_ARGS__, "")) )
213 #if defined(WITH_SYSLOG) || defined(HAVE_LIBSYSTEMD_JOURNAL) || defined(HAVE_LIBSYSTEMD)
214 static int debug_level_to_priority(int level
)
217 * map debug levels to syslog() priorities
219 static const int priority_map
[] = {
233 if (level
< 0 || (size_t)level
>= ARRAY_SIZE(priority_map
))
234 priority
= LOG_DEBUG
;
236 priority
= priority_map
[level
];
242 /* -------------------------------------------------------------------------- **
243 * Produce a version of the given buffer without any trailing newlines.
245 #if defined(HAVE_LIBSYSTEMD_JOURNAL) || defined(HAVE_LIBSYSTEMD) || \
246 defined(HAVE_LTTNG_TRACEF) || defined(HAVE_GPFS)
247 static void copy_no_nl(char *out
,
254 * Some backends already add an extra newline, so also provide
255 * a buffer without the newline character.
257 len
= MIN(in_len
, out_size
- 1);
258 if ((len
> 0) && (in
[len
- 1] == '\n')) {
262 memcpy(out
, in
, len
);
266 static void ensure_copy_no_nl(char *out
,
272 * Assume out is a static buffer that is reused as a cache.
273 * If it isn't empty then this has already been done with the
276 if (out
[0] != '\0') {
280 copy_no_nl(out
, out_size
, in
, in_len
);
284 /* -------------------------------------------------------------------------- **
285 * Debug backends. When logging to DEBUG_FILE, send the log entries to
286 * all active backends.
289 static void debug_file_log(int msg_level
, const char *msg
, size_t msg_len
)
291 struct iovec iov
[] = {
293 .iov_base
= discard_const(state
.header_str
),
294 .iov_len
= state
.hs_len
,
297 .iov_base
= discard_const(msg
),
306 if (dbgc_config
[current_msg_class
].fd
!= -1) {
307 fd
= dbgc_config
[current_msg_class
].fd
;
309 fd
= dbgc_config
[DBGC_ALL
].fd
;
313 ret
= writev(fd
, iov
, ARRAY_SIZE(iov
));
314 } while (ret
== -1 && errno
== EINTR
);
318 static void debug_syslog_reload(bool enabled
, bool previously_enabled
,
319 const char *prog_name
, char *option
)
321 if (enabled
&& !previously_enabled
) {
322 const char *ident
= NULL
;
323 if ((prog_name
!= NULL
) && (prog_name
[0] != '\0')) {
327 openlog(ident
, LOG_PID
, SYSLOG_FACILITY
);
329 /* for old systems that have no facility codes. */
330 openlog(ident
, LOG_PID
);
335 if (!enabled
&& previously_enabled
) {
340 static void debug_syslog_log(int msg_level
, const char *msg
, size_t msg_len
)
344 priority
= debug_level_to_priority(msg_level
);
347 * Specify the facility to interoperate with other syslog
348 * callers (vfs_full_audit for example).
350 priority
|= SYSLOG_FACILITY
;
352 if (state
.hs_len
> 0) {
353 syslog(priority
, "%s", state
.header_str
);
355 syslog(priority
, "%s", msg
);
357 #endif /* WITH_SYSLOG */
359 #if defined(HAVE_LIBSYSTEMD_JOURNAL) || defined(HAVE_LIBSYSTEMD)
360 #include <systemd/sd-journal.h>
361 static void debug_systemd_log(int msg_level
, const char *msg
, size_t msg_len
)
363 if (state
.hs_len
> 0) {
364 ensure_copy_no_nl(state
.header_str_no_nl
,
365 sizeof(state
.header_str_no_nl
),
368 sd_journal_send("MESSAGE=%s",
369 state
.header_str_no_nl
,
371 debug_level_to_priority(msg_level
),
376 ensure_copy_no_nl(state
.msg_no_nl
,
377 sizeof(state
.msg_no_nl
),
379 sd_journal_send("MESSAGE=%s", state
.msg_no_nl
,
380 "PRIORITY=%d", debug_level_to_priority(msg_level
),
381 "LEVEL=%d", msg_level
,
386 #ifdef HAVE_LTTNG_TRACEF
387 #include <lttng/tracef.h>
388 static void debug_lttng_log(int msg_level
, const char *msg
, size_t msg_len
)
390 if (state
.hs_len
> 0) {
391 ensure_copy_no_nl(state
.header_str_no_nl
,
392 sizeof(state
.header_str_no_nl
),
395 tracef(state
.header_str_no_nl
);
397 ensure_copy_no_nl(state
.msg_no_nl
,
398 sizeof(state
.msg_no_nl
),
400 tracef(state
.msg_no_nl
);
402 #endif /* WITH_LTTNG_TRACEF */
405 #include "gpfswrap.h"
406 static void debug_gpfs_reload(bool enabled
, bool previously_enabled
,
407 const char *prog_name
, char *option
)
411 if (enabled
&& !previously_enabled
) {
412 gpfswrap_init_trace();
416 if (!enabled
&& previously_enabled
) {
417 gpfswrap_fini_trace();
423 * Trigger GPFS library to adjust state if necessary.
425 gpfswrap_query_trace();
429 static void debug_gpfs_log(int msg_level
, const char *msg
, size_t msg_len
)
431 if (state
.hs_len
> 0) {
432 ensure_copy_no_nl(state
.header_str_no_nl
,
433 sizeof(state
.header_str_no_nl
),
436 gpfswrap_add_trace(msg_level
, state
.header_str_no_nl
);
438 ensure_copy_no_nl(state
.msg_no_nl
,
439 sizeof(state
.msg_no_nl
),
441 gpfswrap_add_trace(msg_level
, state
.msg_no_nl
);
443 #endif /* HAVE_GPFS */
445 #define DEBUG_RINGBUF_SIZE (1024 * 1024)
446 #define DEBUG_RINGBUF_SIZE_OPT "size="
448 static char *debug_ringbuf
;
449 static size_t debug_ringbuf_size
;
450 static size_t debug_ringbuf_ofs
;
452 /* We ensure in debug_ringbuf_log() that this is always \0 terminated */
453 char *debug_get_ringbuf(void)
455 return debug_ringbuf
;
458 /* Return the size of the ringbuf (including a \0 terminator) */
459 size_t debug_get_ringbuf_size(void)
461 return debug_ringbuf_size
;
464 static void debug_ringbuf_reload(bool enabled
, bool previously_enabled
,
465 const char *prog_name
, char *option
)
468 size_t optlen
= strlen(DEBUG_RINGBUF_SIZE_OPT
);
470 debug_ringbuf_size
= DEBUG_RINGBUF_SIZE
;
471 debug_ringbuf_ofs
= 0;
473 SAFE_FREE(debug_ringbuf
);
479 if (option
!= NULL
) {
480 cmp
= strncmp(option
, DEBUG_RINGBUF_SIZE_OPT
, optlen
);
482 debug_ringbuf_size
= (size_t)strtoull(
483 option
+ optlen
, NULL
, 10);
487 debug_ringbuf
= calloc(debug_ringbuf_size
, sizeof(char));
488 if (debug_ringbuf
== NULL
) {
493 static void _debug_ringbuf_log(int msg_level
, const char *msg
, size_t msg_len
)
497 if (debug_ringbuf
== NULL
) {
501 /* Ensure the buffer is always \0 terminated */
502 allowed_size
= debug_ringbuf_size
- 1;
504 if (msg_len
> allowed_size
) {
508 if ((debug_ringbuf_ofs
+ msg_len
) < debug_ringbuf_ofs
) {
512 if ((debug_ringbuf_ofs
+ msg_len
) > allowed_size
) {
513 debug_ringbuf_ofs
= 0;
516 memcpy(debug_ringbuf
+ debug_ringbuf_ofs
, msg
, msg_len
);
517 debug_ringbuf_ofs
+= msg_len
;
520 static void debug_ringbuf_log(int msg_level
, const char *msg
, size_t msg_len
)
522 if (state
.hs_len
> 0) {
523 _debug_ringbuf_log(msg_level
, state
.header_str
, state
.hs_len
);
525 _debug_ringbuf_log(msg_level
, msg
, msg_len
);
528 static struct debug_backend
{
532 void (*reload
)(bool enabled
, bool prev_enabled
,
533 const char *prog_name
, char *option
);
534 void (*log
)(int msg_level
,
538 } debug_backends
[] = {
541 .log
= debug_file_log
,
546 .reload
= debug_syslog_reload
,
547 .log
= debug_syslog_log
,
551 #if defined(HAVE_LIBSYSTEMD_JOURNAL) || defined(HAVE_LIBSYSTEMD)
554 .log
= debug_systemd_log
,
558 #ifdef HAVE_LTTNG_TRACEF
561 .log
= debug_lttng_log
,
568 .reload
= debug_gpfs_reload
,
569 .log
= debug_gpfs_log
,
574 .log
= debug_ringbuf_log
,
575 .reload
= debug_ringbuf_reload
,
579 static struct debug_backend
*debug_find_backend(const char *name
)
583 for (i
= 0; i
< ARRAY_SIZE(debug_backends
); i
++) {
584 if (strcmp(name
, debug_backends
[i
].name
) == 0) {
585 return &debug_backends
[i
];
593 * parse "backend[:option][@loglevel]
595 static void debug_backend_parse_token(char *tok
)
597 char *backend_name_option
, *backend_name
,*backend_level
, *saveptr
;
598 char *backend_option
;
599 struct debug_backend
*b
;
602 * First parse into backend[:option] and loglevel
604 backend_name_option
= strtok_r(tok
, "@\0", &saveptr
);
605 if (backend_name_option
== NULL
) {
609 backend_level
= strtok_r(NULL
, "\0", &saveptr
);
612 * Now parse backend[:option]
614 backend_name
= strtok_r(backend_name_option
, ":\0", &saveptr
);
615 if (backend_name
== NULL
) {
619 backend_option
= strtok_r(NULL
, "\0", &saveptr
);
622 * Find and update backend
624 b
= debug_find_backend(backend_name
);
629 if (backend_level
== NULL
) {
630 b
->new_log_level
= MAX_DEBUG_LEVEL
;
632 b
->new_log_level
= atoi(backend_level
);
635 if (backend_option
!= NULL
) {
636 b
->option
= strdup(backend_option
);
637 if (b
->option
== NULL
) {
644 * parse "backend1[:option1][@loglevel1] backend2[option2][@loglevel2] ... "
645 * and enable/disable backends accordingly
647 static void debug_set_backends(const char *param
)
649 size_t str_len
= strlen(param
);
655 * initialize new_log_level to detect backends that have been
658 for (i
= 0; i
< ARRAY_SIZE(debug_backends
); i
++) {
659 SAFE_FREE(debug_backends
[i
].option
);
660 debug_backends
[i
].new_log_level
= -1;
663 memcpy(str
, param
, str_len
+ 1);
665 tok
= strtok_r(str
, LIST_SEP
, &saveptr
);
670 while (tok
!= NULL
) {
671 debug_backend_parse_token(tok
);
672 tok
= strtok_r(NULL
, LIST_SEP
, &saveptr
);
676 * Let backends react to config changes
678 for (i
= 0; i
< ARRAY_SIZE(debug_backends
); i
++) {
679 struct debug_backend
*b
= &debug_backends
[i
];
682 bool enabled
= b
->new_log_level
> -1;
683 bool previously_enabled
= b
->log_level
> -1;
685 b
->reload(enabled
, previously_enabled
, state
.prog_name
,
688 b
->log_level
= b
->new_log_level
;
692 static void debug_backends_log(const char *msg
, size_t msg_len
, int msg_level
)
697 * Some backends already add an extra newline, so initialize a
698 * buffer without the newline character. It will be filled by
699 * the first backend that needs it.
701 state
.msg_no_nl
[0] = '\0';
703 for (i
= 0; i
< ARRAY_SIZE(debug_backends
); i
++) {
704 if (msg_level
<= debug_backends
[i
].log_level
) {
705 debug_backends
[i
].log(msg_level
, msg
, msg_len
);
709 /* Only log the header once */
713 int debuglevel_get_class(size_t idx
)
715 return dbgc_config
[idx
].loglevel
;
718 void debuglevel_set_class(size_t idx
, int level
)
720 dbgc_config
[idx
].loglevel
= level
;
724 /* -------------------------------------------------------------------------- **
725 * Internal variables.
727 * debug_count - Number of debug messages that have been output.
728 * Used to check log size.
730 * current_msg_level - Internal copy of the message debug level. Written by
731 * dbghdr() and read by Debug1().
733 * format_bufr - Used to format debug messages. The dbgtext() function
734 * prints debug messages to a string, and then passes the
735 * string to format_debug_text(), which uses format_bufr
736 * to build the formatted output.
738 * format_pos - Marks the first free byte of the format_bufr.
741 * log_overflow - When this variable is true, never attempt to check the
742 * size of the log. This is a hack, so that we can write
743 * a message using DEBUG, from open_logs() when we
744 * are unable to open a new log file for some reason.
747 static int debug_count
= 0;
748 static char format_bufr
[FORMAT_BUFR_SIZE
];
749 static size_t format_pos
= 0;
750 static bool log_overflow
= false;
753 * Define all the debug class selection names here. Names *MUST NOT* contain
754 * white space. There must be one name for each DBGC_<class name>, and they
755 * must be in the table in the order of DBGC_<class name>..
758 static char **classname_table
= NULL
;
761 /* -------------------------------------------------------------------------- **
765 static void debug_init(void);
767 /***************************************************************************
768 Free memory pointed to by global pointers.
769 ****************************************************************************/
771 void gfree_debugsyms(void)
775 TALLOC_FREE(classname_table
);
777 if ( dbgc_config
!= debug_class_list_initial
) {
778 TALLOC_FREE( dbgc_config
);
779 dbgc_config
= discard_const_p(struct debug_class
,
780 debug_class_list_initial
);
783 debug_num_classes
= 0;
785 state
.initialized
= false;
787 for (i
= 0; i
< ARRAY_SIZE(debug_backends
); i
++) {
788 SAFE_FREE(debug_backends
[i
].option
);
792 /****************************************************************************
793 utility lists registered debug class names's
794 ****************************************************************************/
796 char *debug_list_class_names_and_levels(void)
798 char *buf
= talloc_strdup(NULL
, "");
800 /* prepare strings */
801 for (i
= 0; i
< debug_num_classes
; i
++) {
802 talloc_asprintf_addbuf(&buf
,
805 dbgc_config
[i
].loglevel
,
806 i
== (debug_num_classes
- 1) ? "\n" : " ");
811 /****************************************************************************
812 Utility to translate names to debug class index's (internal version).
813 ****************************************************************************/
815 static int debug_lookup_classname_int(const char* classname
)
819 if (classname
== NULL
) {
823 for (i
=0; i
< debug_num_classes
; i
++) {
824 char *entry
= classname_table
[i
];
825 if (entry
!= NULL
&& strcmp(classname
, entry
)==0) {
832 /****************************************************************************
833 Add a new debug class to the system.
834 ****************************************************************************/
836 int debug_add_class(const char *classname
)
839 struct debug_class
*new_class_list
= NULL
;
840 char **new_name_list
;
843 if (classname
== NULL
) {
847 /* check the init has yet been called */
850 ndx
= debug_lookup_classname_int(classname
);
854 ndx
= debug_num_classes
;
856 if (dbgc_config
== debug_class_list_initial
) {
857 /* Initial loading... */
858 new_class_list
= NULL
;
860 new_class_list
= dbgc_config
;
863 default_level
= dbgc_config
[DBGC_ALL
].loglevel
;
865 new_class_list
= talloc_realloc(NULL
,
869 if (new_class_list
== NULL
) {
873 dbgc_config
= new_class_list
;
875 dbgc_config
[ndx
] = (struct debug_class
) {
876 .loglevel
= default_level
,
880 new_name_list
= talloc_realloc(NULL
, classname_table
, char *, ndx
+ 1);
881 if (new_name_list
== NULL
) {
884 classname_table
= new_name_list
;
886 classname_table
[ndx
] = talloc_strdup(classname_table
, classname
);
887 if (classname_table
[ndx
] == NULL
) {
891 debug_num_classes
= ndx
+ 1;
896 /****************************************************************************
897 Utility to translate names to debug class index's (public version).
898 ****************************************************************************/
900 static int debug_lookup_classname(const char *classname
)
904 if (classname
== NULL
|| !*classname
)
907 ndx
= debug_lookup_classname_int(classname
);
912 DBG_WARNING("Unknown classname[%s] -> adding it...\n", classname
);
913 return debug_add_class(classname
);
916 /****************************************************************************
917 Dump the current registered debug levels.
918 ****************************************************************************/
920 static void debug_dump_status(int level
)
924 DEBUG(level
, ("INFO: Current debug levels:\n"));
925 for (q
= 0; q
< debug_num_classes
; q
++) {
926 const char *classname
= classname_table
[q
];
927 DEBUGADD(level
, (" %s: %d\n",
929 dbgc_config
[q
].loglevel
));
933 static bool debug_parse_param(char *param
)
936 char *class_file
= NULL
;
938 char *saveptr
= NULL
;
941 class_name
= strtok_r(param
, ":", &saveptr
);
942 if (class_name
== NULL
) {
946 class_level
= strtok_r(NULL
, "@\0", &saveptr
);
947 if (class_level
== NULL
) {
951 class_file
= strtok_r(NULL
, "\0", &saveptr
);
953 ndx
= debug_lookup_classname(class_name
);
958 dbgc_config
[ndx
].loglevel
= atoi(class_level
);
960 if (class_file
== NULL
) {
964 TALLOC_FREE(dbgc_config
[ndx
].logfile
);
966 dbgc_config
[ndx
].logfile
= talloc_strdup(NULL
, class_file
);
967 if (dbgc_config
[ndx
].logfile
== NULL
) {
973 /****************************************************************************
974 Parse the debug levels from smb.conf. Example debug level string:
975 3 tdb:5 printdrivers:7
976 Note: the 1st param has no "name:" preceding it.
977 ****************************************************************************/
979 bool debug_parse_levels(const char *params_str
)
981 size_t str_len
= strlen(params_str
);
989 memcpy(str
, params_str
, str_len
+1);
991 tok
= strtok_r(str
, LIST_SEP
, &saveptr
);
996 /* Allow DBGC_ALL to be specified w/o requiring its class name e.g."10"
997 * v.s. "all:10", this is the traditional way to set DEBUGLEVEL
999 if (isdigit(tok
[0])) {
1000 dbgc_config
[DBGC_ALL
].loglevel
= atoi(tok
);
1001 tok
= strtok_r(NULL
, LIST_SEP
, &saveptr
);
1003 dbgc_config
[DBGC_ALL
].loglevel
= 0;
1006 /* Array is debug_num_classes long */
1007 for (i
= DBGC_ALL
+1; i
< debug_num_classes
; i
++) {
1008 dbgc_config
[i
].loglevel
= dbgc_config
[DBGC_ALL
].loglevel
;
1009 TALLOC_FREE(dbgc_config
[i
].logfile
);
1012 while (tok
!= NULL
) {
1015 ok
= debug_parse_param(tok
);
1017 DEBUG(0,("debug_parse_params: unrecognized debug "
1018 "class name or format [%s]\n", tok
));
1022 tok
= strtok_r(NULL
, LIST_SEP
, &saveptr
);
1025 debug_dump_status(5);
1030 /* setup for logging of talloc warnings */
1031 static void talloc_log_fn(const char *msg
)
1033 DEBUG(0,("%s", msg
));
1036 void debug_setup_talloc_log(void)
1038 talloc_set_log_fn(talloc_log_fn
);
1042 /****************************************************************************
1043 Init debugging (one time stuff)
1044 ****************************************************************************/
1046 static void debug_init(void)
1050 if (state
.initialized
)
1053 state
.initialized
= true;
1055 debug_setup_talloc_log();
1057 for (i
= 0; i
< ARRAY_SIZE(default_classname_table
); i
++) {
1058 debug_add_class(default_classname_table
[i
]);
1060 dbgc_config
[DBGC_ALL
].fd
= 2;
1062 for (i
= 0; i
< ARRAY_SIZE(debug_backends
); i
++) {
1063 debug_backends
[i
].log_level
= -1;
1064 debug_backends
[i
].new_log_level
= -1;
1068 void debug_set_settings(struct debug_settings
*settings
,
1069 const char *logging_param
,
1070 int syslog_level
, bool syslog_only
)
1072 char fake_param
[256];
1076 * This forces in some smb.conf derived values into the debug
1077 * system. There are no pointers in this structure, so we can
1078 * just structure-assign it in
1080 state
.settings
= *settings
;
1083 * If 'logging' is not set, create backend settings from
1084 * deprecated 'syslog' and 'syslog only' parameters
1086 if (logging_param
!= NULL
) {
1087 len
= strlen(logging_param
);
1091 snprintf(fake_param
, sizeof(fake_param
),
1092 "syslog@%d", syslog_level
- 1);
1094 snprintf(fake_param
, sizeof(fake_param
),
1095 "syslog@%d file@%d", syslog_level
-1,
1099 logging_param
= fake_param
;
1102 debug_set_backends(logging_param
);
1105 static void ensure_hostname(void)
1109 if (state
.hostname
[0] != '\0') {
1113 ret
= gethostname(state
.hostname
, sizeof(state
.hostname
));
1115 strlcpy(state
.hostname
, "unknown", sizeof(state
.hostname
));
1120 * Ensure NUL termination, since POSIX isn't clear about that.
1122 * Don't worry about truncating at the first '.' or similar,
1123 * since this is usually not fully qualified. Trying to
1124 * truncate opens up the multibyte character gates of hell.
1126 state
.hostname
[sizeof(state
.hostname
) - 1] = '\0';
1129 void debug_set_hostname(const char *name
)
1131 strlcpy(state
.hostname
, name
, sizeof(state
.hostname
));
1135 * Ensure debug logs are initialised.
1137 * setup_logging() is called to direct logging to the correct outputs, whether
1138 * those be stderr, stdout, files, or syslog, and set the program name used in
1139 * the logs. It can be called multiple times.
1141 * There is an order of precedence to the log type. Once set to DEBUG_FILE, it
1142 * cannot be reset DEFAULT_DEBUG_STDERR, but can be set to DEBUG_STDERR, after
1143 * which DEBUG_FILE is unavailable). This makes it possible to override for
1144 * debug to stderr on the command line, as the smb.conf cannot reset it back
1145 * to file-based logging. See enum debug_logtype.
1147 * @param prog_name the program name. Directory path component will be
1150 * @param new_logtype the requested destination for the debug log,
1151 * as an enum debug_logtype.
1153 void setup_logging(const char *prog_name
, enum debug_logtype new_logtype
)
1156 if (state
.logtype
< new_logtype
) {
1157 state
.logtype
= new_logtype
;
1160 const char *p
= strrchr(prog_name
, '/');
1166 strlcpy(state
.prog_name
, prog_name
, sizeof(state
.prog_name
));
1168 reopen_logs_internal();
1171 /***************************************************************************
1172 Set the logfile name.
1173 **************************************************************************/
1175 void debug_set_logfile(const char *name
)
1177 if (name
== NULL
|| *name
== 0) {
1178 /* this copes with calls when smb.conf is not loaded yet */
1181 TALLOC_FREE(dbgc_config
[DBGC_ALL
].logfile
);
1182 dbgc_config
[DBGC_ALL
].logfile
= talloc_strdup(NULL
, name
);
1184 reopen_logs_internal();
1187 static void debug_close_fd(int fd
)
1194 enum debug_logtype
debug_get_log_type(void)
1196 return state
.logtype
;
1199 bool debug_get_output_is_stderr(void)
1201 return (state
.logtype
== DEBUG_DEFAULT_STDERR
) || (state
.logtype
== DEBUG_STDERR
);
1204 bool debug_get_output_is_stdout(void)
1206 return (state
.logtype
== DEBUG_DEFAULT_STDOUT
) || (state
.logtype
== DEBUG_STDOUT
);
1209 void debug_set_callback(void *private_ptr
, debug_callback_fn fn
)
1213 state
.logtype
= DEBUG_CALLBACK
;
1214 state
.callback_private
= private_ptr
;
1215 state
.callback
= fn
;
1217 state
.logtype
= DEBUG_DEFAULT_STDERR
;
1218 state
.callback_private
= NULL
;
1219 state
.callback
= NULL
;
1223 static void debug_callback_log(const char *msg
, size_t msg_len
, int msg_level
)
1225 char msg_copy
[msg_len
];
1227 if ((msg_len
> 0) && (msg
[msg_len
-1] == '\n')) {
1228 memcpy(msg_copy
, msg
, msg_len
-1);
1229 msg_copy
[msg_len
-1] = '\0';
1233 state
.callback(state
.callback_private
, msg_level
, msg
);
1236 /**************************************************************************
1237 reopen the log files
1238 note that we now do this unconditionally
1239 We attempt to open the new debug fp before closing the old. This means
1240 if we run out of fd's we just keep using the old fd rather than aborting.
1241 Fix from dgibson@linuxcare.com.
1242 **************************************************************************/
1244 static bool reopen_one_log(struct debug_class
*config
)
1246 int old_fd
= config
->fd
;
1247 const char *logfile
= config
->logfile
;
1252 if (logfile
== NULL
) {
1253 debug_close_fd(old_fd
);
1258 new_fd
= open(logfile
, O_WRONLY
|O_APPEND
|O_CREAT
, 0644);
1260 log_overflow
= true;
1261 DBG_ERR("Unable to open new log file '%s': %s\n",
1262 logfile
, strerror(errno
));
1263 log_overflow
= false;
1267 debug_close_fd(old_fd
);
1268 smb_set_close_on_exec(new_fd
);
1269 config
->fd
= new_fd
;
1271 ret
= fstat(new_fd
, &st
);
1273 log_overflow
= true;
1274 DBG_ERR("Unable to fstat() new log file '%s': %s\n",
1275 logfile
, strerror(errno
));
1276 log_overflow
= false;
1280 config
->ino
= st
.st_ino
;
1285 reopen the log file (usually called because the log file name might have changed)
1287 bool reopen_logs_internal(void)
1289 struct debug_backend
*b
= NULL
;
1294 if (state
.reopening_logs
) {
1298 /* Now clear the SIGHUP induced flag */
1299 state
.schedule_reopen_logs
= false;
1301 switch (state
.logtype
) {
1302 case DEBUG_CALLBACK
:
1305 case DEBUG_DEFAULT_STDOUT
:
1306 debug_close_fd(dbgc_config
[DBGC_ALL
].fd
);
1307 dbgc_config
[DBGC_ALL
].fd
= 1;
1310 case DEBUG_DEFAULT_STDERR
:
1312 debug_close_fd(dbgc_config
[DBGC_ALL
].fd
);
1313 dbgc_config
[DBGC_ALL
].fd
= 2;
1317 b
= debug_find_backend("file");
1320 b
->log_level
= MAX_DEBUG_LEVEL
;
1324 oldumask
= umask( 022 );
1326 for (i
= DBGC_ALL
; i
< debug_num_classes
; i
++) {
1327 if (dbgc_config
[i
].logfile
!= NULL
) {
1331 if (i
== debug_num_classes
) {
1335 state
.reopening_logs
= true;
1337 for (i
= DBGC_ALL
; i
< debug_num_classes
; i
++) {
1338 ok
= reopen_one_log(&dbgc_config
[i
]);
1344 /* Fix from klausr@ITAP.Physik.Uni-Stuttgart.De
1345 * to fix problem where smbd's that generate less
1346 * than 100 messages keep growing the log.
1348 force_check_log_size();
1349 (void)umask(oldumask
);
1352 * If log file was opened or created successfully, take over stderr to
1353 * catch output into logs.
1355 if (!state
.settings
.debug_no_stderr_redirect
&&
1356 dbgc_config
[DBGC_ALL
].fd
> 0) {
1357 if (dup2(dbgc_config
[DBGC_ALL
].fd
, 2) == -1) {
1358 /* Close stderr too, if dup2 can't point it -
1359 at the logfile. There really isn't much
1360 that can be done on such a fundamental
1366 state
.reopening_logs
= false;
1371 /**************************************************************************
1372 Force a check of the log size.
1373 ***************************************************************************/
1375 void force_check_log_size( void )
1380 _PUBLIC_
void debug_schedule_reopen_logs(void)
1382 state
.schedule_reopen_logs
= true;
1386 /***************************************************************************
1387 Check to see if there is any need to check if the logfile has grown too big.
1388 **************************************************************************/
1390 bool need_to_check_log_size(void)
1395 if (debug_count
< 100) {
1399 maxlog
= state
.settings
.max_log_size
* 1024;
1405 if (dbgc_config
[DBGC_ALL
].fd
> 2) {
1409 for (i
= DBGC_ALL
+ 1; i
< debug_num_classes
; i
++) {
1410 if (dbgc_config
[i
].fd
!= -1) {
1419 /**************************************************************************
1420 Check to see if the log has grown to be too big.
1421 **************************************************************************/
1423 static void do_one_check_log_size(off_t maxlog
, struct debug_class
*config
)
1425 char name
[strlen(config
->logfile
) + 5];
1428 bool reopen
= false;
1435 ret
= stat(config
->logfile
, &st
);
1439 if (st
.st_size
>= maxlog
) {
1443 if (st
.st_ino
!= config
->ino
) {
1451 /* reopen_logs_internal() modifies *_fd */
1452 (void)reopen_logs_internal();
1454 if (config
->fd
<= 2) {
1457 ret
= fstat(config
->fd
, &st
);
1459 config
->ino
= (ino_t
)0;
1463 config
->ino
= st
.st_ino
;
1465 if (st
.st_size
< maxlog
) {
1469 snprintf(name
, sizeof(name
), "%s.old", config
->logfile
);
1471 (void)rename(config
->logfile
, name
);
1473 ok
= reopen_logs_internal();
1477 /* We failed to reopen a log - continue using the old name. */
1478 (void)rename(name
, config
->logfile
);
1481 static void do_check_log_size(off_t maxlog
)
1485 for (i
= DBGC_ALL
; i
< debug_num_classes
; i
++) {
1486 if (dbgc_config
[i
].fd
== -1) {
1489 if (dbgc_config
[i
].logfile
== NULL
) {
1492 do_one_check_log_size(maxlog
, &dbgc_config
[i
]);
1496 void check_log_size( void )
1500 if (geteuid() != 0) {
1502 * We need to be root to change the log file (tests use a fake
1503 * geteuid() from third_party/uid_wrapper). Otherwise we skip
1504 * this and let the main smbd loop or some other process do
1510 if(log_overflow
|| (!state
.schedule_reopen_logs
&& !need_to_check_log_size())) {
1514 maxlog
= state
.settings
.max_log_size
* 1024;
1516 if (state
.schedule_reopen_logs
) {
1517 (void)reopen_logs_internal();
1520 do_check_log_size(maxlog
);
1523 * Here's where we need to panic if dbgc_config[DBGC_ALL].fd == 0 or -1
1527 if (dbgc_config
[DBGC_ALL
].fd
<= 0) {
1528 /* This code should only be reached in very strange
1529 * circumstances. If we merely fail to open the new log we
1530 * should stick with the old one. ergo this should only be
1531 * reached when opening the logs for the first time: at
1532 * startup or when the log level is increased from zero.
1535 int fd
= open( "/dev/console", O_WRONLY
, 0);
1537 smb_set_close_on_exec(fd
);
1538 dbgc_config
[DBGC_ALL
].fd
= fd
;
1539 DBG_ERR("check_log_size: open of debug file %s failed "
1540 "- using console.\n",
1541 dbgc_config
[DBGC_ALL
].logfile
);
1544 * We cannot continue without a debug file handle.
1552 /*************************************************************************
1553 Write an debug message on the debugfile.
1554 This is called by format_debug_text().
1555 ************************************************************************/
1557 static void Debug1(const char *msg
, size_t msg_len
)
1559 int old_errno
= errno
;
1560 enum debug_logtype logtype
= state
.logtype
;
1564 if (state
.settings
.debug_syslog_format
== DEBUG_SYSLOG_FORMAT_ALWAYS
) {
1565 switch(state
.logtype
) {
1568 case DEBUG_DEFAULT_STDOUT
:
1569 case DEBUG_DEFAULT_STDERR
:
1570 /* Behave the same as logging to a file */
1571 logtype
= DEBUG_FILE
;
1579 case DEBUG_CALLBACK
:
1580 debug_callback_log(msg
, msg_len
, current_msg_level
);
1584 case DEBUG_DEFAULT_STDOUT
:
1585 case DEBUG_DEFAULT_STDERR
:
1586 if (dbgc_config
[DBGC_ALL
].fd
> 0) {
1589 ret
= write(dbgc_config
[DBGC_ALL
].fd
,
1592 } while (ret
== -1 && errno
== EINTR
);
1596 debug_backends_log(msg
, msg_len
, current_msg_level
);
1603 /**************************************************************************
1604 Print the buffer content via Debug1(), then reset the buffer.
1607 ****************************************************************************/
1609 static void bufr_print( void )
1611 format_bufr
[format_pos
] = '\0';
1612 (void)Debug1(format_bufr
, format_pos
);
1617 * If set (by tevent_thread_call_depth_set()) to value > 0, debug code will use
1618 * it for the trace indentation.
1620 static size_t debug_call_depth
= 0;
1622 size_t *debug_call_depth_addr(void)
1624 return &debug_call_depth
;
1627 /***************************************************************************
1628 Format the debug message text.
1630 Input: msg - Text to be added to the "current" debug message text.
1634 Notes: The purpose of this is two-fold. First, each call to syslog()
1635 (used by Debug1(), see above) generates a new line of syslog
1636 output. This is fixed by storing the partial lines until the
1637 newline character is encountered. Second, printing the debug
1638 message lines when a newline is encountered allows us to add
1639 spaces, thus indenting the body of the message and making it
1641 **************************************************************************/
1643 static void format_debug_text( const char *msg
)
1646 bool timestamp
= (state
.logtype
== DEBUG_FILE
&& (state
.settings
.timestamp_logs
));
1650 for( i
= 0; msg
[i
]; i
++ ) {
1651 /* Indent two spaces at each new line. */
1652 if(timestamp
&& 0 == format_pos
) {
1653 /* Limit the maximum indentation to 20 levels */
1654 size_t depth
= MIN(20, debug_call_depth
);
1655 format_bufr
[0] = format_bufr
[1] = ' ';
1658 * Indent by four spaces for each depth level,
1659 * but only if the current debug level is >= 8.
1661 if (depth
> 0 && debuglevel_get() >= 8 &&
1662 format_pos
+ 4 * depth
< FORMAT_BUFR_SIZE
) {
1663 memset(&format_bufr
[format_pos
],
1666 format_pos
+= 4 * depth
;
1670 /* If there's room, copy the character to the format buffer. */
1671 if (format_pos
< FORMAT_BUFR_SIZE
- 1)
1672 format_bufr
[format_pos
++] = msg
[i
];
1674 /* If a newline is encountered, print & restart. */
1675 if( '\n' == msg
[i
] )
1678 /* If the buffer is full dump it out, reset it, and put out a line
1679 * continuation indicator.
1681 if (format_pos
>= FORMAT_BUFR_SIZE
- 1) {
1682 const char cont
[] = " +>\n";
1684 (void)Debug1(cont
, sizeof(cont
) - 1);
1688 /* Just to be safe... */
1689 format_bufr
[format_pos
] = '\0';
1692 /***************************************************************************
1693 Flush debug output, including the format buffer content.
1697 ***************************************************************************/
1699 void dbgflush( void )
1704 bool dbgsetclass(int level
, int cls
)
1706 /* Set current_msg_level. */
1707 current_msg_level
= level
;
1709 /* Set current message class */
1710 current_msg_class
= cls
;
1715 /***************************************************************************
1716 Put a Debug Header into header_str.
1718 Input: level - Debug level of the message (not the system-wide debug
1720 cls - Debuglevel class of the calling module.
1721 location - Pointer to a string containing the name of the file
1722 from which this function was called, or an empty string
1723 if the __FILE__ macro is not implemented.
1724 func - Pointer to a string containing the name of the function
1725 from which this function was called, or an empty string
1726 if the __FUNCTION__ macro is not implemented.
1728 Output: Always true. This makes it easy to fudge a call to dbghdr()
1729 in a macro, since the function can be called as part of a test.
1730 Eg: ( (level <= DEBUGLEVEL) && (dbghdr(level,"",line)) )
1732 Notes: This function takes care of setting current_msg_level.
1734 ****************************************************************************/
1736 bool dbghdrclass(int level
, int cls
, const char *location
, const char *func
)
1738 /* Ensure we don't lose any real errno value. */
1739 int old_errno
= errno
;
1740 bool verbose
= false;
1742 struct timeval_buf tvbuf
;
1745 * This might be overkill, but if another early return is
1746 * added later then initialising these avoids potential
1750 state
.header_str
[0] = '\0';
1753 /* This is a fudge. If there is stuff sitting in the format_bufr, then
1754 * the *right* thing to do is to call
1755 * format_debug_text( "\n" );
1756 * to write the remainder, and then proceed with the new header.
1757 * Unfortunately, there are several places in the code at which
1758 * the DEBUG() macro is used to build partial lines. That in mind,
1759 * we'll work under the assumption that an incomplete line indicates
1760 * that a new header is *not* desired.
1765 dbgsetclass(level
, cls
);
1768 * Don't print a header if we're logging to stdout,
1769 * unless 'debug syslog format = always'
1771 if (state
.logtype
!= DEBUG_FILE
&&
1772 state
.settings
.debug_syslog_format
!= DEBUG_SYSLOG_FORMAT_ALWAYS
)
1778 * Print the header if timestamps (or debug syslog format) is
1779 * turned on. If parameters are not yet loaded, then default
1782 if (!(state
.settings
.timestamp_logs
||
1783 state
.settings
.debug_prefix_timestamp
||
1784 state
.settings
.debug_syslog_format
!= DEBUG_SYSLOG_FORMAT_NO
))
1791 if (state
.settings
.debug_syslog_format
!= DEBUG_SYSLOG_FORMAT_NO
) {
1792 if (state
.settings
.debug_hires_timestamp
) {
1793 timeval_str_buf(&tv
, true, true, &tvbuf
);
1798 t
= (time_t)tv
.tv_sec
;
1802 len
= strftime(tvbuf
.buf
,
1807 /* Trigger default time format below */
1814 "%ld seconds since the Epoch", (long)t
);
1819 state
.hs_len
= snprintf(state
.header_str
,
1820 sizeof(state
.header_str
),
1823 (int)(sizeof(state
.hostname
) - 1),
1826 (unsigned int) getpid());
1831 timeval_str_buf(&tv
, false, state
.settings
.debug_hires_timestamp
,
1834 state
.hs_len
= snprintf(state
.header_str
,
1835 sizeof(state
.header_str
),
1839 if (state
.hs_len
>= sizeof(state
.header_str
) - 1) {
1843 if (unlikely(dbgc_config
[cls
].loglevel
>= 10)) {
1847 if (verbose
|| state
.settings
.debug_pid
) {
1848 state
.hs_len
+= snprintf(state
.header_str
+ state
.hs_len
,
1849 sizeof(state
.header_str
) - state
.hs_len
,
1851 (unsigned int)getpid());
1852 if (state
.hs_len
>= sizeof(state
.header_str
) - 1) {
1857 if (verbose
|| state
.settings
.debug_uid
) {
1858 state
.hs_len
+= snprintf(state
.header_str
+ state
.hs_len
,
1859 sizeof(state
.header_str
) - state
.hs_len
,
1860 ", effective(%u, %u), real(%u, %u)",
1861 (unsigned int)geteuid(),
1862 (unsigned int)getegid(),
1863 (unsigned int)getuid(),
1864 (unsigned int)getgid());
1865 if (state
.hs_len
>= sizeof(state
.header_str
) - 1) {
1870 if ((verbose
|| state
.settings
.debug_class
)
1871 && (cls
!= DBGC_ALL
)) {
1872 state
.hs_len
+= snprintf(state
.header_str
+ state
.hs_len
,
1873 sizeof(state
.header_str
) - state
.hs_len
,
1875 classname_table
[cls
]);
1876 if (state
.hs_len
>= sizeof(state
.header_str
) - 1) {
1881 if (debug_traceid_get() != 0) {
1882 state
.hs_len
+= snprintf(state
.header_str
+ state
.hs_len
,
1883 sizeof(state
.header_str
) - state
.hs_len
,
1884 ", traceid=%" PRIu64
,
1885 debug_traceid_get());
1886 if (state
.hs_len
>= sizeof(state
.header_str
) - 1) {
1891 if (debug_call_depth
> 0) {
1892 state
.hs_len
+= snprintf(state
.header_str
+ state
.hs_len
,
1893 sizeof(state
.header_str
) - state
.hs_len
,
1896 if (state
.hs_len
>= sizeof(state
.header_str
) - 1) {
1901 state
.header_str
[state
.hs_len
] = ']';
1903 if (state
.hs_len
< sizeof(state
.header_str
) - 1) {
1904 state
.header_str
[state
.hs_len
] = ' ';
1907 state
.header_str
[state
.hs_len
] = '\0';
1909 if (!state
.settings
.debug_prefix_timestamp
) {
1910 state
.hs_len
+= snprintf(state
.header_str
+ state
.hs_len
,
1911 sizeof(state
.header_str
) - state
.hs_len
,
1915 if (state
.hs_len
>= sizeof(state
.header_str
)) {
1922 * Above code never overflows state.header_str and always
1923 * NUL-terminates correctly. However, state.hs_len can point
1924 * past the end of the buffer to indicate that truncation
1925 * occurred, so fix it if necessary, since state.hs_len is
1926 * expected to be used after return.
1928 if (state
.hs_len
>= sizeof(state
.header_str
)) {
1929 state
.hs_len
= sizeof(state
.header_str
) - 1;
1932 state
.header_str_no_nl
[0] = '\0';
1938 /***************************************************************************
1939 Add text to the body of the "current" debug message via the format buffer.
1941 Input: format_str - Format string, as used in printf(), et. al.
1942 ... - Variable argument list.
1944 ..or.. va_alist - Old style variable parameter list starting point.
1946 Output: Always true. See dbghdr() for more info, though this is not
1947 likely to be used in the same way.
1949 ***************************************************************************/
1951 static inline bool __dbgtext_va(const char *format_str
, va_list ap
) PRINTF_ATTRIBUTE(1,0);
1952 static inline bool __dbgtext_va(const char *format_str
, va_list ap
)
1954 char *msgbuf
= NULL
;
1958 res
= vasprintf(&msgbuf
, format_str
, ap
);
1960 format_debug_text(msgbuf
);
1968 bool dbgtext_va(const char *format_str
, va_list ap
)
1970 return __dbgtext_va(format_str
, ap
);
1973 bool dbgtext(const char *format_str
, ... )
1978 va_start(ap
, format_str
);
1979 ret
= __dbgtext_va(format_str
, ap
);
1985 static uint64_t debug_traceid
= 0;
1987 uint64_t debug_traceid_set(uint64_t id
)
1989 uint64_t old_id
= debug_traceid
;
1994 uint64_t debug_traceid_get(void)
1996 return debug_traceid
;