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