From c94ccdbef11508dff2a8b3c797b17cf7ebd78a58 Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Wed, 3 Mar 2021 21:29:07 +0100
Subject: [PATCH 01/11] Moved ldb_debug_messages() out of UTILS to SYSDB

---
 src/db/sysdb.c   | 26 ++++++++++++++++++++++++++
 src/db/sysdb.h   |  3 +++
 src/util/debug.c | 26 --------------------------
 src/util/util.h  |  2 --
 4 files changed, 29 insertions(+), 28 deletions(-)

diff --git a/src/db/sysdb.c b/src/db/sysdb.c
index d78991e368..693f687bea 100644
--- a/src/db/sysdb.c
+++ b/src/db/sysdb.c
@@ -2113,3 +2113,29 @@ bool sysdb_entry_attrs_diff(struct sysdb_ctx *sysdb,
     talloc_free(tmp_ctx);
     return differs;
 }
+
+void ldb_debug_messages(void *context, enum ldb_debug_level level,
+                        const char *fmt, va_list ap)
+{
+    int loglevel = SSSDBG_UNRESOLVED;
+
+    switch(level) {
+    case LDB_DEBUG_FATAL:
+        loglevel = SSSDBG_FATAL_FAILURE;
+        break;
+    case LDB_DEBUG_ERROR:
+        loglevel = SSSDBG_CRIT_FAILURE;
+        break;
+    case LDB_DEBUG_WARNING:
+        loglevel = SSSDBG_TRACE_FUNC;
+        break;
+    case LDB_DEBUG_TRACE:
+        loglevel = SSSDBG_TRACE_LDB;
+        break;
+    }
+
+    if (DEBUG_IS_SET(loglevel)) {
+        sss_vdebug_fn(__FILE__, __LINE__, "ldb", loglevel, APPEND_LINE_FEED,
+                      fmt, ap);
+    }
+}
diff --git a/src/db/sysdb.h b/src/db/sysdb.h
index 880f3b7a09..a00efa55f9 100644
--- a/src/db/sysdb.h
+++ b/src/db/sysdb.h
@@ -1529,4 +1529,7 @@ errno_t sysdb_cert_derb64_to_ldap_filter(TALLOC_CTX *mem_ctx,
 /* define old name for backward compatibility */
 #define sysdb_error_to_errno(ldberr) sss_ldb_error_to_errno(ldberr)
 
+void ldb_debug_messages(void *context, enum ldb_debug_level level,
+                        const char *fmt, va_list ap);
+
 #endif /* __SYS_DB_H__ */
diff --git a/src/util/debug.c b/src/util/debug.c
index 95975d398e..3d7b993911 100644
--- a/src/util/debug.c
+++ b/src/util/debug.c
@@ -345,32 +345,6 @@ void sss_debug_fn(const char *file,
     va_end(ap);
 }
 
-void ldb_debug_messages(void *context, enum ldb_debug_level level,
-                        const char *fmt, va_list ap)
-{
-    int loglevel = SSSDBG_UNRESOLVED;
-
-    switch(level) {
-    case LDB_DEBUG_FATAL:
-        loglevel = SSSDBG_FATAL_FAILURE;
-        break;
-    case LDB_DEBUG_ERROR:
-        loglevel = SSSDBG_CRIT_FAILURE;
-        break;
-    case LDB_DEBUG_WARNING:
-        loglevel = SSSDBG_TRACE_FUNC;
-        break;
-    case LDB_DEBUG_TRACE:
-        loglevel = SSSDBG_TRACE_LDB;
-        break;
-    }
-
-    if (DEBUG_IS_SET(loglevel)) {
-        sss_vdebug_fn(__FILE__, __LINE__, "ldb", loglevel, APPEND_LINE_FEED,
-                      fmt, ap);
-    }
-}
-
 /* In cases SSSD used to run as the root user, but runs as the SSSD user now,
  * we need to chown the log files
  */
diff --git a/src/util/util.h b/src/util/util.h
index aec53962b3..6e7d9c5259 100644
--- a/src/util/util.h
+++ b/src/util/util.h
@@ -162,8 +162,6 @@ extern int dbus_activated;
 #include "util/dlinklist.h"
 
 /* From debug.c */
-void ldb_debug_messages(void *context, enum ldb_debug_level level,
-                        const char *fmt, va_list ap);
 int chown_debug_file(const char *filename, uid_t uid, gid_t gid);
 int open_debug_file_ex(const char *filename, FILE **filep, bool want_cloexec);
 int open_debug_file(void);

From d672ba4dcb0465924786b0cb28200f0cdb709303 Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Wed, 3 Mar 2021 22:16:52 +0100
Subject: [PATCH 02/11] Moved declaration of debug related helpers defined in
 debug.c from util.h to debug.h

---
 src/util/debug.h | 8 +++++++-
 src/util/util.h  | 7 -------
 2 files changed, 7 insertions(+), 8 deletions(-)

diff --git a/src/util/debug.h b/src/util/debug.h
index 43d36720fc..47035d879b 100644
--- a/src/util/debug.h
+++ b/src/util/debug.h
@@ -23,7 +23,8 @@
 
 #include "config.h"
 
-#include <stdarg.h>
+#include <stdio.h>
+#include <stdbool.h>
 
 #ifdef HAVE_FUNCTION_ATTRIBUTE_FORMAT
 #define SSS_ATTRIBUTE_PRINTF(a1, a2) __attribute__((format (printf, a1, a2)))
@@ -68,6 +69,11 @@ void sss_debug_fn(const char *file,
 int debug_convert_old_level(int old_level);
 errno_t set_debug_file_from_fd(const int fd);
 int get_fd_from_debug_file(void);
+int chown_debug_file(const char *filename, uid_t uid, gid_t gid);
+int open_debug_file_ex(const char *filename, FILE **filep, bool want_cloexec);
+int open_debug_file(void);
+int rotate_debug_files(void);
+void talloc_log_fn(const char *msg);
 
 #define SSS_DOM_ENV           "_SSS_DOM"
 
diff --git a/src/util/util.h b/src/util/util.h
index 6e7d9c5259..519eafa6ba 100644
--- a/src/util/util.h
+++ b/src/util/util.h
@@ -161,13 +161,6 @@ extern int dbus_activated;
 
 #include "util/dlinklist.h"
 
-/* From debug.c */
-int chown_debug_file(const char *filename, uid_t uid, gid_t gid);
-int open_debug_file_ex(const char *filename, FILE **filep, bool want_cloexec);
-int open_debug_file(void);
-int rotate_debug_files(void);
-void talloc_log_fn(const char *msg);
-
 /* From sss_log.c */
 #define SSS_LOG_EMERG   0   /* system is unusable */
 #define SSS_LOG_ALERT   1   /* action must be taken immediately */

From 7c95d4726fc745094ea08c1b0595a27907e83ff8 Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Thu, 4 Mar 2021 13:52:59 +0100
Subject: [PATCH 03/11] DEBUG: use '--logger' as the only option to configure
 logger type.

This patch gets rid of:
 - 'debug-to-files', 'debug-to-stderr' command line options
 - undocumented 'debug_to_files' sssd.conf option
and makes '--logger' command line option the only "source of truth" for
logger type configuration.

Those options were not used much anyway but made precedence logic obscure
in case contradictory settings were used.

:config: Long time deprecated and undocumented 'debug_to_files' option was
removed.

:relnote: 'debug-to-files', 'debug-to-stderr' command line and undocumented
'debug_to_files' config options were removed.
---
 src/confdb/confdb.h                        |  1 -
 src/config/SSSDConfig/sssdoptions.py       |  1 -
 src/config/SSSDConfigTest.py               |  1 -
 src/config/cfg_rules.ini                   | 11 -----
 src/config/etc/sssd.api.conf               |  1 -
 src/man/sssd.8.xml                         | 25 ++--------
 src/monitor/monitor.c                      |  6 +--
 src/p11_child/p11_child_common.c           |  3 --
 src/providers/ad/ad_gpo_child.c            |  3 --
 src/providers/ipa/selinux_child.c          |  3 --
 src/providers/krb5/krb5_child.c            |  3 --
 src/providers/ldap/ldap_child.c            |  2 -
 src/tests/cmocka/dummy_child.c             |  2 -
 src/tests/debug-tests.c                    |  6 ---
 src/tests/intg/ldap_local_override_test.py |  4 +-
 src/tests/intg/test_enumeration.py         |  2 +-
 src/tests/intg/test_files_provider.py      |  2 +-
 src/tests/intg/test_infopipe.py            |  4 +-
 src/tests/intg/test_ldap.py                |  2 +-
 src/tests/intg/test_local_domain.py        |  2 +-
 src/tests/intg/test_memory_cache.py        |  2 +-
 src/tests/intg/test_netgroup.py            |  2 +-
 src/tests/intg/test_pac_responder.py       |  2 +-
 src/tests/intg/test_pam_responder.py       |  2 +-
 src/tests/intg/test_pysss_nss_idmap.py     |  2 +-
 src/tests/intg/test_resolver.py            |  2 +-
 src/tests/intg/test_session_recording.py   |  4 +-
 src/tests/intg/test_ssh_pubkey.py          |  2 +-
 src/tests/intg/test_sssctl.py              |  2 +-
 src/tests/intg/test_sudo.py                |  2 +-
 src/tests/intg/test_ts_cache.py            |  2 +-
 src/util/child_common.c                    |  2 +-
 src/util/debug.c                           | 54 ++++++++--------------
 src/util/debug.h                           |  8 +---
 src/util/server.c                          | 15 ------
 35 files changed, 46 insertions(+), 141 deletions(-)

diff --git a/src/confdb/confdb.h b/src/confdb/confdb.h
index a2be227ddd..a50bbcbb2d 100644
--- a/src/confdb/confdb.h
+++ b/src/confdb/confdb.h
@@ -61,7 +61,6 @@
 #define CONFDB_SERVICE_DEBUG_LEVEL_ALIAS "debug"
 #define CONFDB_SERVICE_DEBUG_TIMESTAMPS "debug_timestamps"
 #define CONFDB_SERVICE_DEBUG_MICROSECONDS "debug_microseconds"
-#define CONFDB_SERVICE_DEBUG_TO_FILES "debug_to_files"
 #define CONFDB_SERVICE_RECON_RETRIES "reconnection_retries"
 #define CONFDB_SERVICE_FD_LIMIT "fd_limit"
 #define CONFDB_SERVICE_ALLOWED_UIDS "allowed_uids"
diff --git a/src/config/SSSDConfig/sssdoptions.py b/src/config/SSSDConfig/sssdoptions.py
index 5d9946ba8f..8a1a204a2e 100644
--- a/src/config/SSSDConfig/sssdoptions.py
+++ b/src/config/SSSDConfig/sssdoptions.py
@@ -21,7 +21,6 @@ def __init__(self):
         'debug_level': _('Set the verbosity of the debug logging'),
         'debug_timestamps': _('Include timestamps in debug logs'),
         'debug_microseconds': _('Include microseconds in timestamps in debug logs'),
-        'debug_to_files': _('Write debug messages to logfiles'),
         'timeout': _('Watchdog timeout before restarting service'),
         'command': _('Command to start service'),
         'reconnection_retries': _('Number of times to attempt connection to Data Providers'),
diff --git a/src/config/SSSDConfigTest.py b/src/config/SSSDConfigTest.py
index 04c4b35baa..bdf4b3759b 100755
--- a/src/config/SSSDConfigTest.py
+++ b/src/config/SSSDConfigTest.py
@@ -381,7 +381,6 @@ def testListOptions(self):
             'debug_level',
             'debug_timestamps',
             'debug_microseconds',
-            'debug_to_files',
             'command',
             'reconnection_retries',
             'fd_limit',
diff --git a/src/config/cfg_rules.ini b/src/config/cfg_rules.ini
index bf2d03b824..5e03fb2b8f 100644
--- a/src/config/cfg_rules.ini
+++ b/src/config/cfg_rules.ini
@@ -32,7 +32,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -67,7 +66,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -109,7 +107,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -152,7 +149,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -175,7 +171,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -196,7 +191,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -221,7 +215,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -243,7 +236,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -266,7 +258,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -317,7 +308,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
@@ -379,7 +369,6 @@ option = debug
 option = debug_level
 option = debug_timestamps
 option = debug_microseconds
-option = debug_to_files
 option = command
 option = reconnection_retries
 option = fd_limit
diff --git a/src/config/etc/sssd.api.conf b/src/config/etc/sssd.api.conf
index 49ced63859..a95a045b99 100644
--- a/src/config/etc/sssd.api.conf
+++ b/src/config/etc/sssd.api.conf
@@ -8,7 +8,6 @@ debug = int, None, false
 debug_level = int, None, false
 debug_timestamps = bool, None, false
 debug_microseconds = bool, None, false
-debug_to_files = bool, None, false
 command = str, None, false
 reconnection_retries = int, None, false
 fd_limit = int, None, false
diff --git a/src/man/sssd.8.xml b/src/man/sssd.8.xml
index 03d059ce31..bd23dea94f 100644
--- a/src/man/sssd.8.xml
+++ b/src/man/sssd.8.xml
@@ -80,33 +80,13 @@
                     </para>
                 </listitem>
             </varlistentry>
-            <varlistentry>
-                <term>
-                    <option>-f</option>,<option>--debug-to-files</option>
-                </term>
-                <listitem>
-                    <para>
-                        Send the debug output to files instead of stderr. By default, the
-                        log files are stored in <filename>/var/log/sssd</filename> and
-                        there are separate log files for every SSSD service and domain.
-                    </para>
-                    <para>
-                        This option is deprecated. It is replaced by
-                        <option>--logger=files</option>.
-                    </para>
-                </listitem>
-            </varlistentry>
             <varlistentry>
                 <term>
                     <option>--logger=</option><replaceable>value</replaceable>
                 </term>
                 <listitem>
                     <para>
-                        Location where SSSD will send log messages. This option
-                        overrides the value of the deprecated option
-                        <option>--debug-to-files</option>. The deprecated
-                        option will still work if the <option>--logger</option>
-                        is not used.
+                        Location where SSSD will send log messages.
                     </para>
                     <para>
                         <emphasis>stderr</emphasis>: Redirect debug messages to
@@ -123,7 +103,8 @@
                         to systemd-journald
                     </para>
                     <para>
-                        Default: not set
+                        Default: not set (fall back to journald if available,
+                        otherwise to stderr)
                     </para>
                 </listitem>
             </varlistentry>
diff --git a/src/monitor/monitor.c b/src/monitor/monitor.c
index fe5f550b69..857b42efde 100644
--- a/src/monitor/monitor.c
+++ b/src/monitor/monitor.c
@@ -2363,7 +2363,7 @@ int main(int argc, const char *argv[])
     int opt_version = 0;
     int opt_netlinkoff = 0;
     char *opt_config_file = NULL;
-    char *opt_logger = NULL;
+    const char *opt_logger = NULL;
     char *config_file = NULL;
     char *opt_genconf_section = NULL;
     int flags = 0;
@@ -2466,11 +2466,11 @@ int main(int argc, const char *argv[])
     if (opt_daemon) flags |= FLAGS_DAEMON;
     if (opt_interactive) {
         flags |= FLAGS_INTERACTIVE;
-        debug_to_stderr = 1;
+        opt_logger = sss_logger_str[STDERR_LOGGER];
     }
     if (opt_genconf) {
         flags |= FLAGS_GEN_CONF;
-        debug_to_stderr = 1;
+        opt_logger = sss_logger_str[STDERR_LOGGER];
     }
 
     sss_set_logger(opt_logger);
diff --git a/src/p11_child/p11_child_common.c b/src/p11_child/p11_child_common.c
index 704ced4b65..0cb5ee55fa 100644
--- a/src/p11_child/p11_child_common.c
+++ b/src/p11_child/p11_child_common.c
@@ -174,9 +174,6 @@ int main(int argc, const char *argv[])
          _("Show timestamps with microseconds"), NULL},
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
-        {"debug-to-stderr", 0, POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN,
-         &debug_to_stderr, 0,
-         _("Send the debug output to stderr directly."), NULL },
         SSSD_LOGGER_OPTS
         {"auth", 0, POPT_ARG_NONE, NULL, 'a', _("Run in auth mode"), NULL},
         {"pre", 0, POPT_ARG_NONE, NULL, 'p', _("Run in pre-auth mode"), NULL},
diff --git a/src/providers/ad/ad_gpo_child.c b/src/providers/ad/ad_gpo_child.c
index 9205eefae8..7adfc66a92 100644
--- a/src/providers/ad/ad_gpo_child.c
+++ b/src/providers/ad/ad_gpo_child.c
@@ -745,9 +745,6 @@ main(int argc, const char *argv[])
          _("Show timestamps with microseconds"), NULL},
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
-        {"debug-to-stderr", 0, POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN,
-         &debug_to_stderr, 0,
-         _("Send the debug output to stderr directly."), NULL },
         SSSD_LOGGER_OPTS
         POPT_TABLEEND
     };
diff --git a/src/providers/ipa/selinux_child.c b/src/providers/ipa/selinux_child.c
index 8e5f02a28e..a1242e85cb 100644
--- a/src/providers/ipa/selinux_child.c
+++ b/src/providers/ipa/selinux_child.c
@@ -228,9 +228,6 @@ int main(int argc, const char *argv[])
          _("Show timestamps with microseconds"), NULL},
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
-        {"debug-to-stderr", 0, POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN,
-         &debug_to_stderr, 0,
-         _("Send the debug output to stderr directly."), NULL },
         SSSD_LOGGER_OPTS
         POPT_TABLEEND
     };
diff --git a/src/providers/krb5/krb5_child.c b/src/providers/krb5/krb5_child.c
index e3221b604f..631984bc38 100644
--- a/src/providers/krb5/krb5_child.c
+++ b/src/providers/krb5/krb5_child.c
@@ -3278,9 +3278,6 @@ int main(int argc, const char *argv[])
          _("Show timestamps with microseconds"), NULL},
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
-        {"debug-to-stderr", 0, POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN,
-         &debug_to_stderr, 0,
-         _("Send the debug output to stderr directly."), NULL },
         SSSD_LOGGER_OPTS
         {CHILD_OPT_FAST_CCACHE_UID, 0, POPT_ARG_INT, &fast_uid, 0,
           _("The user to create FAST ccache as"), NULL},
diff --git a/src/providers/ldap/ldap_child.c b/src/providers/ldap/ldap_child.c
index 8580e27856..6524a1a948 100644
--- a/src/providers/ldap/ldap_child.c
+++ b/src/providers/ldap/ldap_child.c
@@ -642,8 +642,6 @@ int main(int argc, const char *argv[])
          _("Show timestamps with microseconds"), NULL},
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
-        {"debug-to-stderr", 0, POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN, &debug_to_stderr, 0, \
-         _("Send the debug output to stderr directly."), NULL }, \
         SSSD_LOGGER_OPTS
         POPT_TABLEEND
     };
diff --git a/src/tests/cmocka/dummy_child.c b/src/tests/cmocka/dummy_child.c
index 811cb40490..149f1f14df 100644
--- a/src/tests/cmocka/dummy_child.c
+++ b/src/tests/cmocka/dummy_child.c
@@ -54,8 +54,6 @@ int main(int argc, const char *argv[])
          _("Show timestamps with microseconds"), NULL},
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
-        {"debug-to-stderr", 0, POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN, &debug_to_stderr, 0, \
-         _("Send the debug output to stderr directly."), NULL },
         SSSD_LOGGER_OPTS
         {"guitar", 0, POPT_ARG_STRING, &guitar, 0, _("Who plays guitar"), NULL },
         {"drums", 0, POPT_ARG_STRING, &drums, 0, _("Who plays drums"), NULL },
diff --git a/src/tests/debug-tests.c b/src/tests/debug-tests.c
index 092ccf684e..077fa6dadb 100644
--- a/src/tests/debug-tests.c
+++ b/src/tests/debug-tests.c
@@ -344,7 +344,6 @@ START_TEST(test_debug_is_set_single_no_timestamp)
 
     debug_timestamps = 0;
     debug_microseconds = 0;
-    debug_to_file = 1;
     debug_prg_name = "sssd";
     sss_set_logger(sss_logger_str[FILES_LOGGER]);
 
@@ -385,7 +384,6 @@ START_TEST(test_debug_is_set_single_timestamp)
 
     debug_timestamps = 1;
     debug_microseconds = 0;
-    debug_to_file = 1;
     debug_prg_name = "sssd";
     sss_set_logger(sss_logger_str[FILES_LOGGER]);
 
@@ -430,7 +428,6 @@ START_TEST(test_debug_is_set_single_timestamp_microseconds)
 
     debug_timestamps = 1;
     debug_microseconds = 1;
-    debug_to_file = 1;
     debug_prg_name = "sssd";
     sss_set_logger(sss_logger_str[FILES_LOGGER]);
 
@@ -476,7 +473,6 @@ START_TEST(test_debug_is_notset_no_timestamp)
 
     debug_timestamps = 0;
     debug_microseconds = 0;
-    debug_to_file = 1;
     debug_prg_name = "sssd";
     sss_set_logger(sss_logger_str[FILES_LOGGER]);
 
@@ -519,7 +515,6 @@ START_TEST(test_debug_is_notset_timestamp)
 
     debug_timestamps = 0;
     debug_microseconds = 0;
-    debug_to_file = 1;
     debug_prg_name = "sssd";
     sss_set_logger(sss_logger_str[FILES_LOGGER]);
 
@@ -562,7 +557,6 @@ START_TEST(test_debug_is_notset_timestamp_microseconds)
 
     debug_timestamps = 0;
     debug_microseconds = 1;
-    debug_to_file = 1;
     debug_prg_name = "sssd";
     sss_set_logger(sss_logger_str[FILES_LOGGER]);
 
diff --git a/src/tests/intg/ldap_local_override_test.py b/src/tests/intg/ldap_local_override_test.py
index 3cd65965b9..4db4e5e96d 100644
--- a/src/tests/intg/ldap_local_override_test.py
+++ b/src/tests/intg/ldap_local_override_test.py
@@ -111,7 +111,7 @@ def stop_sssd():
 
 def start_sssd():
     """Start sssd"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
@@ -122,7 +122,7 @@ def restart_sssd():
 
 def create_sssd_fixture(request):
     """Start sssd and add teardown for stopping it and removing state"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
     def teardown():
diff --git a/src/tests/intg/test_enumeration.py b/src/tests/intg/test_enumeration.py
index 31c3d75c0d..53fe5e8d65 100644
--- a/src/tests/intg/test_enumeration.py
+++ b/src/tests/intg/test_enumeration.py
@@ -195,7 +195,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_process():
     """Start the SSSD process"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_files_provider.py b/src/tests/intg/test_files_provider.py
index 90be198c3c..3ea326c27e 100644
--- a/src/tests/intg/test_files_provider.py
+++ b/src/tests/intg/test_files_provider.py
@@ -96,7 +96,7 @@ def start_sssd():
     """Start sssd and add teardown for stopping it and removing state"""
     os.environ["SSS_FILES_PASSWD"] = os.environ["NSS_WRAPPER_PASSWD"]
     os.environ["SSS_FILES_GROUP"] = os.environ["NSS_WRAPPER_GROUP"]
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_infopipe.py b/src/tests/intg/test_infopipe.py
index 2167fc6655..6cd7c49a8d 100644
--- a/src/tests/intg/test_infopipe.py
+++ b/src/tests/intg/test_infopipe.py
@@ -207,7 +207,7 @@ def format_basic_conf(ldap_conn, schema):
         # it need to be executed with valgrind because there is a problem
         # problem with "ifp" + client registration in monitor
         # There is not such problem in 1st test. Just in following tests.
-        command = {ifp_command} --uid 0 --gid 0 --debug-to-files
+        command = {ifp_command} --uid 0 --gid 0 --logger=files
         user_attributes = +extraName
 
         [domain/LDAP]
@@ -265,7 +265,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_process():
     """Start the SSSD process"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_ldap.py b/src/tests/intg/test_ldap.py
index 6a78c960fd..7e4aebc014 100644
--- a/src/tests/intg/test_ldap.py
+++ b/src/tests/intg/test_ldap.py
@@ -197,7 +197,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_process():
     """Start the SSSD process"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_local_domain.py b/src/tests/intg/test_local_domain.py
index a85e52a6fa..c9bfad2478 100644
--- a/src/tests/intg/test_local_domain.py
+++ b/src/tests/intg/test_local_domain.py
@@ -53,7 +53,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_fixture(request):
     """Start sssd and add teardown for stopping it and removing state"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
     def teardown():
diff --git a/src/tests/intg/test_memory_cache.py b/src/tests/intg/test_memory_cache.py
index 6ed696e00a..b9116fb9ff 100644
--- a/src/tests/intg/test_memory_cache.py
+++ b/src/tests/intg/test_memory_cache.py
@@ -98,7 +98,7 @@ def stop_sssd():
 
 def create_sssd_fixture(request):
     """Start sssd and add teardown for stopping it and removing state"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
     def teardown():
diff --git a/src/tests/intg/test_netgroup.py b/src/tests/intg/test_netgroup.py
index 3d7f980e9b..6a33423cda 100644
--- a/src/tests/intg/test_netgroup.py
+++ b/src/tests/intg/test_netgroup.py
@@ -149,7 +149,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_process():
     """Start the SSSD process"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_pac_responder.py b/src/tests/intg/test_pac_responder.py
index b5b5b47695..2390f31908 100644
--- a/src/tests/intg/test_pac_responder.py
+++ b/src/tests/intg/test_pac_responder.py
@@ -56,7 +56,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_fixture(request):
     """Start sssd and add teardown for stopping it and removing state"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
     def teardown():
diff --git a/src/tests/intg/test_pam_responder.py b/src/tests/intg/test_pam_responder.py
index eab64e9291..f0bcf42fb9 100644
--- a/src/tests/intg/test_pam_responder.py
+++ b/src/tests/intg/test_pam_responder.py
@@ -276,7 +276,7 @@ def create_sssd_process():
     """Start the SSSD process"""
     os.environ["SSS_FILES_PASSWD"] = os.environ["NSS_WRAPPER_PASSWD"]
     os.environ["SSS_FILES_GROUP"] = os.environ["NSS_WRAPPER_GROUP"]
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_pysss_nss_idmap.py b/src/tests/intg/test_pysss_nss_idmap.py
index b32f7dbd71..89d4ecc086 100644
--- a/src/tests/intg/test_pysss_nss_idmap.py
+++ b/src/tests/intg/test_pysss_nss_idmap.py
@@ -118,7 +118,7 @@ def cleanup_conf_file():
 
 def create_sssd_process():
     """Start the SSSD process"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_resolver.py b/src/tests/intg/test_resolver.py
index 4dc470e24c..2184f65175 100644
--- a/src/tests/intg/test_resolver.py
+++ b/src/tests/intg/test_resolver.py
@@ -163,7 +163,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_process():
     """Start the SSSD process"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_session_recording.py b/src/tests/intg/test_session_recording.py
index 34a586e4a2..27d1a8d18a 100644
--- a/src/tests/intg/test_session_recording.py
+++ b/src/tests/intg/test_session_recording.py
@@ -49,7 +49,7 @@ def stop_sssd():
 
 def start_sssd():
     """Start sssd"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
@@ -188,7 +188,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_process():
     """Start the SSSD process"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_ssh_pubkey.py b/src/tests/intg/test_ssh_pubkey.py
index a103a9cbe1..24b5c258c6 100644
--- a/src/tests/intg/test_ssh_pubkey.py
+++ b/src/tests/intg/test_ssh_pubkey.py
@@ -169,7 +169,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_process():
     """Start the SSSD process"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_sssctl.py b/src/tests/intg/test_sssctl.py
index c7bc500960..2cef1c29bd 100644
--- a/src/tests/intg/test_sssctl.py
+++ b/src/tests/intg/test_sssctl.py
@@ -100,7 +100,7 @@ def stop_sssd():
 
 def create_sssd_fixture(request):
     """Start sssd and add teardown for stopping it and removing state"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
     def teardown():
diff --git a/src/tests/intg/test_sudo.py b/src/tests/intg/test_sudo.py
index 9e229fa6f5..7e8c232edc 100644
--- a/src/tests/intg/test_sudo.py
+++ b/src/tests/intg/test_sudo.py
@@ -167,7 +167,7 @@ def create_conf_fixture(request, contents):
 
 def create_sssd_process():
     """Start the SSSD process"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
 
diff --git a/src/tests/intg/test_ts_cache.py b/src/tests/intg/test_ts_cache.py
index 8ce6731269..740cc20160 100644
--- a/src/tests/intg/test_ts_cache.py
+++ b/src/tests/intg/test_ts_cache.py
@@ -107,7 +107,7 @@ def stop_sssd():
 
 def create_sssd_fixture(request):
     """Start sssd and add teardown for stopping it and removing state"""
-    if subprocess.call(["sssd", "-D", "-f"]) != 0:
+    if subprocess.call(["sssd", "-D", "--logger=files"]) != 0:
         raise Exception("sssd start failed")
 
     def teardown():
diff --git a/src/util/child_common.c b/src/util/child_common.c
index 3ae9806b3b..1ae0fddd50 100644
--- a/src/util/child_common.c
+++ b/src/util/child_common.c
@@ -644,7 +644,7 @@ static errno_t prepare_child_argv(TALLOC_CTX *mem_ctx,
     }
 
     /*
-     * program name, debug_level, debug_to_file, debug_timestamps,
+     * program name, debug_level, debug_timestamps,
      * debug_microseconds and NULL
      */
     argv  = talloc_array(mem_ctx, char *, argc);
diff --git a/src/util/debug.c b/src/util/debug.c
index 3d7b993911..cfa0ab7b14 100644
--- a/src/util/debug.c
+++ b/src/util/debug.c
@@ -41,9 +41,7 @@ const char *debug_prg_name = "sssd";
 int debug_level = SSSDBG_UNRESOLVED;
 int debug_timestamps = SSSDBG_TIMESTAMP_UNRESOLVED;
 int debug_microseconds = SSSDBG_MICROSECONDS_UNRESOLVED;
-int debug_to_file = 0;
-int debug_to_stderr = 0;
-enum sss_logger_t sss_logger;
+enum sss_logger_t sss_logger = STDERR_LOGGER;
 const char *debug_log_file = "sssd";
 static FILE *debug_file;
 
@@ -56,47 +54,31 @@ const char *sss_logger_str[] = {
         NULL,
 };
 
-#ifdef WITH_JOURNALD
-#define JOURNALD_STR " journald,"
-#else
-#define JOURNALD_STR ""
-#endif
-
 void sss_set_logger(const char *logger)
 {
-    /* use old flags */
     if (logger == NULL) {
-        if (debug_to_stderr != 0) {
-            sss_logger = STDERR_LOGGER;
-        }
-        /* It is never described what should be used in case of
-         * debug_to_stderr == 1 && debug_to_file == 1. Because neither
-         * of binaries provide both command line arguments.
-         * Let files have higher priority.
-         */
-        if (debug_to_file != 0) {
-            sss_logger = FILES_LOGGER;
-        }
+        sss_logger = STDERR_LOGGER;
 #ifdef WITH_JOURNALD
-        if (debug_to_file == 0 && debug_to_stderr == 0) {
-            sss_logger = JOURNALD_LOGGER;
-        }
+        sss_logger = JOURNALD_LOGGER;
+#endif
+    } else if (strcmp(logger, "stderr") == 0) {
+        sss_logger = STDERR_LOGGER;
+    } else if (strcmp(logger, "files") == 0) {
+        sss_logger = FILES_LOGGER;
+#ifdef WITH_JOURNALD
+    } else if (strcmp(logger, "journald") == 0) {
+        sss_logger = JOURNALD_LOGGER;
 #endif
     } else {
-        if (strcmp(logger, "stderr") == 0) {
-            sss_logger = STDERR_LOGGER;
-        } else if (strcmp(logger, "files") == 0) {
-            sss_logger = FILES_LOGGER;
+        /* unexpected value */
+        fprintf(stderr, "Unexpected logger: %s\nExpected: ", logger);
+        fprintf(stderr, "%s", sss_logger_str[STDERR_LOGGER]);
+        fprintf(stderr, "|%s", sss_logger_str[FILES_LOGGER]);
 #ifdef WITH_JOURNALD
-        } else if (strcmp(logger, "journald") == 0) {
-            sss_logger = JOURNALD_LOGGER;
+        fprintf(stderr, "|%s", sss_logger_str[JOURNALD_LOGGER]);
 #endif
-        } else {
-            /* unexpected value */
-            fprintf(stderr, "Unexpected logger: %s\nExpected:%s stderr, "
-                            "files\n", logger, JOURNALD_STR);
-            sss_logger = STDERR_LOGGER;
-        }
+        fprintf(stderr, "\n");
+        sss_logger = STDERR_LOGGER;
     }
 }
 
diff --git a/src/util/debug.h b/src/util/debug.h
index 47035d879b..4a5775ba0d 100644
--- a/src/util/debug.h
+++ b/src/util/debug.h
@@ -47,8 +47,6 @@ extern const char *debug_prg_name;
 extern int debug_level;
 extern int debug_timestamps;
 extern int debug_microseconds;
-extern int debug_to_file;
-extern int debug_to_stderr;
 extern enum sss_logger_t sss_logger;
 extern const char *debug_log_file;
 
@@ -114,10 +112,6 @@ void talloc_log_fn(const char *msg);
 #define SSSD_DEBUG_OPTS \
         {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0, \
          _("Debug level"), NULL}, \
-        {"debug-to-files", 'f', POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN, &debug_to_file, 0, \
-         _("Send the debug output to files instead of stderr"), NULL }, \
-        {"debug-to-stderr", 0, POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN, &debug_to_stderr, 0, \
-         _("Send the debug output to stderr directly."), NULL }, \
         {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0, \
          _("Add debug timestamps"), NULL}, \
         {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0, \
@@ -165,7 +159,7 @@ void talloc_log_fn(const char *msg);
  */
 #define DEBUG_CLI_INIT(dbg_lvl) do { \
     DEBUG_INIT(dbg_lvl);             \
-    debug_to_stderr = 1;             \
+    sss_logger = STDERR_LOGGER;      \
 } while (0)
 
 #define PRINT(fmt, ...) fprintf(stdout, gettext(fmt), ##__VA_ARGS__)
diff --git a/src/util/server.c b/src/util/server.c
index 869ed62a67..f1ed5d9b08 100644
--- a/src/util/server.c
+++ b/src/util/server.c
@@ -454,7 +454,6 @@ int server_setup(const char *name, int flags,
     char *conf_db;
     int ret = EOK;
     bool dt;
-    bool dl = false;
     bool dm;
     struct tevent_signal *tes;
     struct logrotate_ctx *lctx;
@@ -643,20 +642,6 @@ int server_setup(const char *name, int flags,
         else debug_microseconds = 0;
     }
 
-    /* same for debug to file */
-    ret = confdb_get_bool(ctx->confdb_ctx, conf_entry,
-                          CONFDB_SERVICE_DEBUG_TO_FILES,
-                          false, &dl);
-    if (ret != EOK) {
-        DEBUG(SSSDBG_FATAL_FAILURE, "Error reading from confdb (%d) [%s]\n",
-                                     ret, strerror(ret));
-        return ret;
-    }
-    if (dl) {
-        debug_to_file = 1;
-        sss_set_logger(sss_logger_str[FILES_LOGGER]);
-    }
-
     /* before opening the log file set up log rotation */
     lctx = talloc_zero(ctx, struct logrotate_ctx);
     if (!lctx) return ENOMEM;

From 83cf4ec89f4282d88ceb67feedfbd2f4016c0f48 Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Thu, 4 Mar 2021 22:09:27 +0100
Subject: [PATCH 04/11] DEBUG: make use of existing SSSD_DEBUG_OPTS macro

---
 src/p11_child/p11_child_common.c  | 7 +------
 src/providers/ad/ad_gpo_child.c   | 7 +------
 src/providers/ipa/selinux_child.c | 7 +------
 src/providers/krb5/krb5_child.c   | 7 +------
 src/providers/ldap/ldap_child.c   | 7 +------
 src/tests/cmocka/dummy_child.c    | 7 +------
 src/tests/crypto-tests.c          | 2 +-
 src/tests/fail_over-tests.c       | 2 +-
 src/tests/files-tests.c           | 2 +-
 src/tests/refcount-tests.c        | 2 +-
 src/tests/resolv-tests.c          | 2 +-
 11 files changed, 11 insertions(+), 41 deletions(-)

diff --git a/src/p11_child/p11_child_common.c b/src/p11_child/p11_child_common.c
index 0cb5ee55fa..d56a029be9 100644
--- a/src/p11_child/p11_child_common.c
+++ b/src/p11_child/p11_child_common.c
@@ -166,12 +166,7 @@ int main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0,
-         _("Debug level"), NULL},
-        {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0,
-         _("Add debug timestamps"), NULL},
-        {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0,
-         _("Show timestamps with microseconds"), NULL},
+        SSSD_DEBUG_OPTS
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
         SSSD_LOGGER_OPTS
diff --git a/src/providers/ad/ad_gpo_child.c b/src/providers/ad/ad_gpo_child.c
index 7adfc66a92..ec8ec133b6 100644
--- a/src/providers/ad/ad_gpo_child.c
+++ b/src/providers/ad/ad_gpo_child.c
@@ -737,12 +737,7 @@ main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0,
-         _("Debug level"), NULL},
-        {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0,
-         _("Add debug timestamps"), NULL},
-        {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0,
-         _("Show timestamps with microseconds"), NULL},
+        SSSD_DEBUG_OPTS
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
         SSSD_LOGGER_OPTS
diff --git a/src/providers/ipa/selinux_child.c b/src/providers/ipa/selinux_child.c
index a1242e85cb..6032f6c5dc 100644
--- a/src/providers/ipa/selinux_child.c
+++ b/src/providers/ipa/selinux_child.c
@@ -220,12 +220,7 @@ int main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0,
-         _("Debug level"), NULL},
-        {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0,
-         _("Add debug timestamps"), NULL},
-        {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0,
-         _("Show timestamps with microseconds"), NULL},
+        SSSD_DEBUG_OPTS
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
         SSSD_LOGGER_OPTS
diff --git a/src/providers/krb5/krb5_child.c b/src/providers/krb5/krb5_child.c
index 631984bc38..d525c5fc65 100644
--- a/src/providers/krb5/krb5_child.c
+++ b/src/providers/krb5/krb5_child.c
@@ -3270,12 +3270,7 @@ int main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0,
-         _("Debug level"), NULL},
-        {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0,
-         _("Add debug timestamps"), NULL},
-        {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0,
-         _("Show timestamps with microseconds"), NULL},
+        SSSD_DEBUG_OPTS
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
         SSSD_LOGGER_OPTS
diff --git a/src/providers/ldap/ldap_child.c b/src/providers/ldap/ldap_child.c
index 6524a1a948..b4fa1e6f9c 100644
--- a/src/providers/ldap/ldap_child.c
+++ b/src/providers/ldap/ldap_child.c
@@ -634,12 +634,7 @@ int main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0,
-         _("Debug level"), NULL},
-        {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0,
-         _("Add debug timestamps"), NULL},
-        {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0,
-         _("Show timestamps with microseconds"), NULL},
+        SSSD_DEBUG_OPTS
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
         SSSD_LOGGER_OPTS
diff --git a/src/tests/cmocka/dummy_child.c b/src/tests/cmocka/dummy_child.c
index 149f1f14df..191b1f6139 100644
--- a/src/tests/cmocka/dummy_child.c
+++ b/src/tests/cmocka/dummy_child.c
@@ -46,12 +46,7 @@ int main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0,
-         _("Debug level"), NULL},
-        {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0,
-         _("Add debug timestamps"), NULL},
-        {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0,
-         _("Show timestamps with microseconds"), NULL},
+        SSSD_DEBUG_OPTS
         {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
          _("An open file descriptor for the debug logs"), NULL},
         SSSD_LOGGER_OPTS
diff --git a/src/tests/crypto-tests.c b/src/tests/crypto-tests.c
index f5e31660f9..c950c17561 100644
--- a/src/tests/crypto-tests.c
+++ b/src/tests/crypto-tests.c
@@ -244,7 +244,7 @@ int main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        { "debug-level", 'd', POPT_ARG_INT, &debug_level, 0, "Set debug level", NULL },
+        SSSD_DEBUG_OPTS
         POPT_TABLEEND
     };
 
diff --git a/src/tests/fail_over-tests.c b/src/tests/fail_over-tests.c
index d7bd173d67..964248a087 100644
--- a/src/tests/fail_over-tests.c
+++ b/src/tests/fail_over-tests.c
@@ -319,7 +319,7 @@ main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        { "debug-level", 'd', POPT_ARG_INT, &debug_level, 0, "Set debug level", NULL },
+        SSSD_DEBUG_OPTS
         { "use-net-test", 'n', POPT_ARG_NONE, 0, 'n', "Run tests that need an active internet connection", NULL },
         POPT_TABLEEND
     };
diff --git a/src/tests/files-tests.c b/src/tests/files-tests.c
index d0fcd6cda3..2087bdb160 100644
--- a/src/tests/files-tests.c
+++ b/src/tests/files-tests.c
@@ -444,7 +444,7 @@ int main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        { "debug-level", 'd', POPT_ARG_INT, &debug, 0, "Set debug level", NULL },
+        SSSD_DEBUG_OPTS
         POPT_TABLEEND
     };
 
diff --git a/src/tests/refcount-tests.c b/src/tests/refcount-tests.c
index 4907ab5fb3..9db97af560 100644
--- a/src/tests/refcount-tests.c
+++ b/src/tests/refcount-tests.c
@@ -205,7 +205,7 @@ int main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        { "debug-level", 'd', POPT_ARG_INT, &debug, 0, "Set debug level", NULL },
+        SSSD_DEBUG_OPTS
         POPT_TABLEEND
     };
 
diff --git a/src/tests/resolv-tests.c b/src/tests/resolv-tests.c
index 59bda4373a..a6c42bfd78 100644
--- a/src/tests/resolv-tests.c
+++ b/src/tests/resolv-tests.c
@@ -1022,7 +1022,7 @@ int main(int argc, const char *argv[])
 
     struct poptOption long_options[] = {
         POPT_AUTOHELP
-        { "debug-level", 'd', POPT_ARG_INT, &debug, 0, "Set debug level", NULL },
+        SSSD_DEBUG_OPTS
         { "use-net-test", 'n', POPT_ARG_NONE, 0, 'n', "Run tests that need an active internet connection", NULL },
         { "txt-host", 't', POPT_ARG_STRING, 0, 't', "Specify the host used for TXT record testing", NULL },
         { "srv-host", 's', POPT_ARG_STRING, 0, 's', "Specify the host used for SRV record testing", NULL },

From 753c7700f2477057e010c41fee2e9d936b9e314c Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Sat, 6 Mar 2021 17:03:18 +0100
Subject: [PATCH 05/11] DEBUG: incorporate sss_set_logger() into DEBUG_INIT

This makes code less error-prone reducing amount of function calls required
for debug initialization.
---
 Makefile.am                                  |  1 +
 src/monitor/monitor.c                        | 19 +++++-------
 src/p11_child/p11_child_common.c             | 11 +++----
 src/providers/ad/ad_gpo_child.c              | 11 +++----
 src/providers/data_provider_be.c             |  5 +--
 src/providers/ipa/selinux_child.c            | 11 +++----
 src/providers/krb5/krb5_child.c              | 11 +++----
 src/providers/ldap/ldap_child.c              | 11 +++----
 src/providers/proxy/proxy_child.c            |  4 +--
 src/responder/autofs/autofssrv.c             |  5 +--
 src/responder/ifp/ifpsrv.c                   |  5 +--
 src/responder/kcm/kcm.c                      |  5 +--
 src/responder/nss/nsssrv.c                   |  5 +--
 src/responder/pac/pacsrv.c                   |  5 +--
 src/responder/pam/pamsrv.c                   |  5 +--
 src/responder/secrets/secsrv.c               |  5 +--
 src/responder/ssh/sshsrv.c                   |  5 +--
 src/responder/sudo/sudosrv.c                 |  5 +--
 src/sss_client/ssh/sss_ssh_authorizedkeys.c  |  2 +-
 src/sss_client/ssh/sss_ssh_knownhostsproxy.c |  2 +-
 src/tests/cmocka/dummy_child.c               |  2 +-
 src/tools/sss_seed.c                         |  8 ++---
 src/util/debug.c                             | 12 ++++++++
 src/util/debug.h                             | 32 +++++++++-----------
 src/util/server.c                            | 10 +++---
 25 files changed, 82 insertions(+), 115 deletions(-)

diff --git a/Makefile.am b/Makefile.am
index cae9eae838..95ee1c6ada 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -3492,6 +3492,7 @@ dummy_child_SOURCES = \
     $(NULL)
 dummy_child_LDADD = \
     $(POPT_LIBS) \
+    $(TALLOC_LIBS) \
     $(SSSD_INTERNAL_LTLIBS) \
     $(NULL)
 
diff --git a/src/monitor/monitor.c b/src/monitor/monitor.c
index 857b42efde..48d126c2ea 100644
--- a/src/monitor/monitor.c
+++ b/src/monitor/monitor.c
@@ -1099,9 +1099,9 @@ static int get_service_config(struct mt_ctx *ctx, const char *name,
             return ENOMEM;
         }
 
-        if (cmdline_debug_level != SSSDBG_UNRESOLVED) {
+        if (cmdline_debug_level != SSSDBG_INVALID) {
             svc->command = talloc_asprintf_append(
-                svc->command, " -d %#.4x", cmdline_debug_level
+                svc->command, " -d %#.5x", cmdline_debug_level
             );
             if (!svc->command) {
                 talloc_free(svc);
@@ -1251,9 +1251,9 @@ static int get_provider_config(struct mt_ctx *ctx, const char *name,
             return ENOMEM;
         }
 
-        if (cmdline_debug_level != SSSDBG_UNRESOLVED) {
+        if (cmdline_debug_level != SSSDBG_INVALID) {
             svc->command = talloc_asprintf_append(
-                svc->command, " -d %#.4x", cmdline_debug_level
+                svc->command, " -d %#.5x", cmdline_debug_level
             );
             if (!svc->command) {
                 talloc_free(svc);
@@ -2411,8 +2411,6 @@ int main(int argc, const char *argv[])
         }
     }
 
-    DEBUG_INIT(debug_level);
-
     if (opt_version) {
         puts(VERSION""PRERELEASE_VERSION);
         return EXIT_SUCCESS;
@@ -2433,13 +2431,13 @@ int main(int argc, const char *argv[])
     cmdline_debug_microseconds = debug_microseconds;
 
     if (opt_daemon && opt_interactive) {
-        fprintf(stderr, "Option -i|--interactive is not allowed together with -D|--daemon\n");
+        ERROR("Option -i|--interactive is not allowed together with -D|--daemon\n");
         poptPrintUsage(pc, stderr, 0);
         return 1;
     }
 
     if (opt_genconf && (opt_daemon || opt_interactive)) {
-        fprintf(stderr, "Option -g is incompatible with -D or -i\n");
+        ERROR("Option -g is incompatible with -D or -i\n");
         poptPrintUsage(pc, stderr, 0);
         return 1;
     }
@@ -2452,8 +2450,7 @@ int main(int argc, const char *argv[])
 
     uid = getuid();
     if (uid != 0) {
-        DEBUG(SSSDBG_FATAL_FAILURE,
-              "Running under %"SPRIuid", must be root\n", uid);
+        ERROR("Running under %"SPRIuid", must be root\n", uid);
         sss_log(SSS_LOG_ALERT, "sssd must be run as root");
         return 8;
     }
@@ -2473,7 +2470,7 @@ int main(int argc, const char *argv[])
         opt_logger = sss_logger_str[STDERR_LOGGER];
     }
 
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     if (opt_config_file) {
         config_file = talloc_strdup(tmp_ctx, opt_config_file);
diff --git a/src/p11_child/p11_child_common.c b/src/p11_child/p11_child_common.c
index d56a029be9..9ee2562496 100644
--- a/src/p11_child/p11_child_common.c
+++ b/src/p11_child/p11_child_common.c
@@ -298,23 +298,22 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     debug_prg_name = talloc_asprintf(NULL, "p11_child[%d]", getpid());
     if (debug_prg_name == NULL) {
-        DEBUG(SSSDBG_CRIT_FAILURE, "talloc_asprintf failed.\n");
+        ERROR("talloc_asprintf failed.\n");
         goto fail;
     }
 
     if (debug_fd != -1) {
+        opt_logger = sss_logger_str[FILES_LOGGER];
         ret = set_debug_file_from_fd(debug_fd);
         if (ret != EOK) {
-            DEBUG(SSSDBG_CRIT_FAILURE, "set_debug_file_from_fd failed.\n");
+            opt_logger = sss_logger_str[STDERR_LOGGER];
+            ERROR("set_debug_file_from_fd failed.\n");
         }
-        opt_logger = sss_logger_str[FILES_LOGGER];
     }
 
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     DEBUG(SSSDBG_TRACE_FUNC, "p11_child started.\n");
 
diff --git a/src/providers/ad/ad_gpo_child.c b/src/providers/ad/ad_gpo_child.c
index ec8ec133b6..8a3a87195b 100644
--- a/src/providers/ad/ad_gpo_child.c
+++ b/src/providers/ad/ad_gpo_child.c
@@ -760,23 +760,22 @@ main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     debug_prg_name = talloc_asprintf(NULL, "gpo_child[%d]", getpid());
     if (debug_prg_name == NULL) {
-        DEBUG(SSSDBG_CRIT_FAILURE, "talloc_asprintf failed.\n");
+        ERROR("talloc_asprintf failed.\n");
         goto fail;
     }
 
     if (debug_fd != -1) {
+        opt_logger = sss_logger_str[FILES_LOGGER];
         ret = set_debug_file_from_fd(debug_fd);
         if (ret != EOK) {
-            DEBUG(SSSDBG_CRIT_FAILURE, "set_debug_file_from_fd failed.\n");
+            opt_logger = sss_logger_str[STDERR_LOGGER];
+            ERROR("set_debug_file_from_fd failed.\n");
         }
-        opt_logger = sss_logger_str[FILES_LOGGER];
     }
 
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     DEBUG(SSSDBG_TRACE_FUNC, "gpo_child started.\n");
 
diff --git a/src/providers/data_provider_be.c b/src/providers/data_provider_be.c
index e3f8c71c5a..e2d38cd891 100644
--- a/src/providers/data_provider_be.c
+++ b/src/providers/data_provider_be.c
@@ -738,13 +738,10 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = talloc_asprintf(NULL, "sssd_%s", be_domain);
     if (!debug_log_file) return 2;
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     srv_name = talloc_asprintf(NULL, "be[%s]", be_domain);
     if (!srv_name) return 2;
diff --git a/src/providers/ipa/selinux_child.c b/src/providers/ipa/selinux_child.c
index 6032f6c5dc..d9b6e15c93 100644
--- a/src/providers/ipa/selinux_child.c
+++ b/src/providers/ipa/selinux_child.c
@@ -243,23 +243,22 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     debug_prg_name = talloc_asprintf(NULL, "selinux_child[%d]", getpid());
     if (debug_prg_name == NULL) {
-        DEBUG(SSSDBG_CRIT_FAILURE, "talloc_asprintf failed.\n");
+        ERROR("talloc_asprintf failed.\n");
         goto fail;
     }
 
     if (debug_fd != -1) {
+        opt_logger = sss_logger_str[FILES_LOGGER];
         ret = set_debug_file_from_fd(debug_fd);
         if (ret != EOK) {
-            DEBUG(SSSDBG_CRIT_FAILURE, "set_debug_file_from_fd failed.\n");
+            opt_logger = sss_logger_str[STDERR_LOGGER];
+            ERROR("set_debug_file_from_fd failed.\n");
         }
-        opt_logger = sss_logger_str[FILES_LOGGER];
     }
 
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     DEBUG(SSSDBG_TRACE_FUNC, "selinux_child started.\n");
     DEBUG(SSSDBG_TRACE_INTERNAL,
diff --git a/src/providers/krb5/krb5_child.c b/src/providers/krb5/krb5_child.c
index d525c5fc65..877d0b293a 100644
--- a/src/providers/krb5/krb5_child.c
+++ b/src/providers/krb5/krb5_child.c
@@ -3317,25 +3317,24 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     debug_prg_name = talloc_asprintf(NULL, "krb5_child[%d]", getpid());
     if (!debug_prg_name) {
         debug_prg_name = "krb5_child";
-        DEBUG(SSSDBG_CRIT_FAILURE, "talloc_asprintf failed.\n");
+        ERROR("talloc_asprintf failed.\n");
         ret = ENOMEM;
         goto done;
     }
 
     if (debug_fd != -1) {
+        opt_logger = sss_logger_str[FILES_LOGGER];
         ret = set_debug_file_from_fd(debug_fd);
         if (ret != EOK) {
-            DEBUG(SSSDBG_CRIT_FAILURE, "set_debug_file_from_fd failed.\n");
+            opt_logger = sss_logger_str[STDERR_LOGGER];
+            ERROR("set_debug_file_from_fd failed.\n");
         }
-        opt_logger = sss_logger_str[FILES_LOGGER];
     }
 
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     DEBUG(SSSDBG_TRACE_FUNC, "krb5_child started.\n");
 
diff --git a/src/providers/ldap/ldap_child.c b/src/providers/ldap/ldap_child.c
index b4fa1e6f9c..146d8e0430 100644
--- a/src/providers/ldap/ldap_child.c
+++ b/src/providers/ldap/ldap_child.c
@@ -657,24 +657,23 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     debug_prg_name = talloc_asprintf(NULL, "ldap_child[%d]", getpid());
     if (!debug_prg_name) {
         debug_prg_name = "ldap_child";
-        DEBUG(SSSDBG_CRIT_FAILURE, "talloc_asprintf failed.\n");
+        ERROR("talloc_asprintf failed.\n");
         goto fail;
     }
 
     if (debug_fd != -1) {
+        opt_logger = sss_logger_str[FILES_LOGGER];
         ret = set_debug_file_from_fd(debug_fd);
         if (ret != EOK) {
-            DEBUG(SSSDBG_CRIT_FAILURE, "set_debug_file_from_fd failed.\n");
+            opt_logger = sss_logger_str[STDERR_LOGGER];
+            ERROR("set_debug_file_from_fd failed.\n");
         }
-        opt_logger = sss_logger_str[FILES_LOGGER];
     }
 
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     BlockSignals(false, SIGTERM);
     CatchSignal(SIGTERM, sig_term_handler);
diff --git a/src/providers/proxy/proxy_child.c b/src/providers/proxy/proxy_child.c
index c5a049752e..d9e3d0d874 100644
--- a/src/providers/proxy/proxy_child.c
+++ b/src/providers/proxy/proxy_child.c
@@ -544,13 +544,11 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = talloc_asprintf(NULL, "proxy_child_%s", domain);
     if (!debug_log_file) return 2;
 
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     srv_name = talloc_asprintf(NULL, "proxy_child[%s]", domain);
     if (!srv_name) return 2;
diff --git a/src/responder/autofs/autofssrv.c b/src/responder/autofs/autofssrv.c
index 130eaf775d..2f2271312b 100644
--- a/src/responder/autofs/autofssrv.c
+++ b/src/responder/autofs/autofssrv.c
@@ -209,12 +209,9 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = "sssd_autofs";
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     ret = server_setup("autofs", 0, uid, gid,
                        CONFDB_AUTOFS_CONF_ENTRY, &main_ctx);
diff --git a/src/responder/ifp/ifpsrv.c b/src/responder/ifp/ifpsrv.c
index ee14527289..6de2e00a01 100644
--- a/src/responder/ifp/ifpsrv.c
+++ b/src/responder/ifp/ifpsrv.c
@@ -334,12 +334,9 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = "sssd_ifp";
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     ret = server_setup("ifp", 0, 0, 0,
                        CONFDB_IFP_CONF_ENTRY, &main_ctx);
diff --git a/src/responder/kcm/kcm.c b/src/responder/kcm/kcm.c
index f1fc958be2..e2670659e9 100644
--- a/src/responder/kcm/kcm.c
+++ b/src/responder/kcm/kcm.c
@@ -305,12 +305,9 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = "sssd_kcm";
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     ret = server_setup("kcm", 0, uid, gid, CONFDB_KCM_CONF_ENTRY,
                        &main_ctx);
diff --git a/src/responder/nss/nsssrv.c b/src/responder/nss/nsssrv.c
index 2b7958e805..1977d565fa 100644
--- a/src/responder/nss/nsssrv.c
+++ b/src/responder/nss/nsssrv.c
@@ -625,12 +625,9 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = "sssd_nss";
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     ret = server_setup("nss", 0, uid, gid, CONFDB_NSS_CONF_ENTRY,
                        &main_ctx);
diff --git a/src/responder/pac/pacsrv.c b/src/responder/pac/pacsrv.c
index 96935150b0..7a90c6c2ab 100644
--- a/src/responder/pac/pacsrv.c
+++ b/src/responder/pac/pacsrv.c
@@ -197,12 +197,9 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = "sssd_pac";
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     ret = server_setup("pac", 0, uid, gid,
                        CONFDB_PAC_CONF_ENTRY, &main_ctx);
diff --git a/src/responder/pam/pamsrv.c b/src/responder/pam/pamsrv.c
index f6bed9cf07..14aa094360 100644
--- a/src/responder/pam/pamsrv.c
+++ b/src/responder/pam/pamsrv.c
@@ -455,12 +455,9 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = "sssd_pam";
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     if (!is_socket_activated()) {
         /* Create pipe file descriptors here before privileges are dropped
diff --git a/src/responder/secrets/secsrv.c b/src/responder/secrets/secsrv.c
index 5cba4958b7..de9c283df8 100644
--- a/src/responder/secrets/secsrv.c
+++ b/src/responder/secrets/secsrv.c
@@ -279,12 +279,9 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = "sssd_secrets";
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     ret = server_setup("secrets", 0, uid, gid, CONFDB_SEC_CONF_ENTRY,
                        &main_ctx);
diff --git a/src/responder/ssh/sshsrv.c b/src/responder/ssh/sshsrv.c
index e79a0438cf..bd5a42e6da 100644
--- a/src/responder/ssh/sshsrv.c
+++ b/src/responder/ssh/sshsrv.c
@@ -194,12 +194,9 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = "sssd_ssh";
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     /* server_setup() might switch to an unprivileged user, so the permissions
      * for p11_child.log have to be fixed first. We might call p11_child to
diff --git a/src/responder/sudo/sudosrv.c b/src/responder/sudo/sudosrv.c
index dc4a44b2ff..d7ab0cecf5 100644
--- a/src/responder/sudo/sudosrv.c
+++ b/src/responder/sudo/sudosrv.c
@@ -171,12 +171,9 @@ int main(int argc, const char *argv[])
 
     poptFreeContext(pc);
 
-    DEBUG_INIT(debug_level);
-
     /* set up things like debug, signals, daemonization, etc. */
     debug_log_file = "sssd_sudo";
-
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     if (!is_socket_activated()) {
         /* Create pipe file descriptors here with right ownerschip */
diff --git a/src/sss_client/ssh/sss_ssh_authorizedkeys.c b/src/sss_client/ssh/sss_ssh_authorizedkeys.c
index 877c002998..e356f28c31 100644
--- a/src/sss_client/ssh/sss_ssh_authorizedkeys.c
+++ b/src/sss_client/ssh/sss_ssh_authorizedkeys.c
@@ -72,7 +72,7 @@ int main(int argc, const char **argv)
     while ((ret = poptGetNextOpt(pc)) > 0)
         ;
 
-    DEBUG_INIT(pc_debug);
+    DEBUG_CLI_INIT(pc_debug);
 
     if (ret != -1) {
         BAD_POPT_PARAMS(pc, poptStrerror(ret), ret, fini);
diff --git a/src/sss_client/ssh/sss_ssh_knownhostsproxy.c b/src/sss_client/ssh/sss_ssh_knownhostsproxy.c
index 1102fd4ab7..3cd12b4806 100644
--- a/src/sss_client/ssh/sss_ssh_knownhostsproxy.c
+++ b/src/sss_client/ssh/sss_ssh_knownhostsproxy.c
@@ -224,7 +224,7 @@ int main(int argc, const char **argv)
     while ((ret = poptGetNextOpt(pc)) > 0)
         ;
 
-    DEBUG_INIT(pc_debug);
+    DEBUG_CLI_INIT(pc_debug);
 
     if (ret != -1) {
         BAD_POPT_PARAMS(pc, poptStrerror(ret), ret, fini);
diff --git a/src/tests/cmocka/dummy_child.c b/src/tests/cmocka/dummy_child.c
index 191b1f6139..62bccf0895 100644
--- a/src/tests/cmocka/dummy_child.c
+++ b/src/tests/cmocka/dummy_child.c
@@ -71,7 +71,7 @@ int main(int argc, const char *argv[])
     }
     poptFreeContext(pc);
 
-    sss_set_logger(opt_logger);
+    DEBUG_INIT(debug_level, opt_logger);
 
     action = getenv("TEST_CHILD_ACTION");
     if (action) {
diff --git a/src/tools/sss_seed.c b/src/tools/sss_seed.c
index 283974b5c6..1189604a30 100644
--- a/src/tools/sss_seed.c
+++ b/src/tools/sss_seed.c
@@ -505,14 +505,14 @@ static int seed_init(TALLOC_CTX *mem_ctx,
 
     sctx = talloc_zero(tmp_ctx, struct seed_ctx);
     if (sctx == NULL) {
-        DEBUG(SSSDBG_CRIT_FAILURE, "Could not allocate tools context\n");
+        ERROR("Could not allocate tools context\n");
         ret = ENOMEM;
         goto fini;
     }
 
     sctx->uctx = talloc_zero(sctx, struct user_ctx);
     if (sctx->uctx == NULL) {
-        DEBUG(SSSDBG_CRIT_FAILURE, "Could not allocate user data context\n");
+        ERROR("Could not allocate user data context\n");
         ret = ENOMEM;
         goto fini;
     }
@@ -520,9 +520,7 @@ static int seed_init(TALLOC_CTX *mem_ctx,
     debug_prg_name = argv[0];
     ret = set_locale();
     if (ret != EOK) {
-        DEBUG(SSSDBG_CRIT_FAILURE, "set_locale failed (%d): %s\n",
-                                    ret, strerror(ret));
-        ERROR("Error setting the locale\n");
+        ERROR("set_locale failed (%d): %s\n", ret, strerror(ret));
         ret = EINVAL;
         goto fini;
     }
diff --git a/src/util/debug.c b/src/util/debug.c
index cfa0ab7b14..e99834b8e6 100644
--- a/src/util/debug.c
+++ b/src/util/debug.c
@@ -54,6 +54,7 @@ const char *sss_logger_str[] = {
         NULL,
 };
 
+
 void sss_set_logger(const char *logger)
 {
     if (logger == NULL) {
@@ -82,6 +83,17 @@ void sss_set_logger(const char *logger)
     }
 }
 
+void _sss_debug_init(int dbg_lvl, const char *logger)
+{
+    if (dbg_lvl != SSSDBG_INVALID) {
+        debug_level = debug_convert_old_level(dbg_lvl);
+    } else {
+        debug_level = SSSDBG_UNRESOLVED;
+    }
+
+    sss_set_logger(logger);
+}
+
 errno_t set_debug_file_from_fd(const int fd)
 {
     FILE *dummy;
diff --git a/src/util/debug.h b/src/util/debug.h
index 4a5775ba0d..4ecd21c2fc 100644
--- a/src/util/debug.h
+++ b/src/util/debug.h
@@ -50,6 +50,17 @@ extern int debug_microseconds;
 extern enum sss_logger_t sss_logger;
 extern const char *debug_log_file;
 
+
+#define DEBUG_INIT(dbg_lvl, logger) do { \
+    _sss_debug_init(dbg_lvl, logger);    \
+    talloc_set_log_fn(talloc_log_fn);    \
+} while (0)
+
+/* CLI tools shall debug to stderr */
+#define DEBUG_CLI_INIT(dbg_lvl) do {                    \
+    DEBUG_INIT(dbg_lvl, sss_logger_str[STDERR_LOGGER]); \
+} while (0)
+
 void sss_set_logger(const char *logger);
 
 void sss_vdebug_fn(const char *file,
@@ -144,25 +155,10 @@ void talloc_log_fn(const char *msg);
                                             (level & (SSSDBG_FATAL_FAILURE | \
                                                       SSSDBG_CRIT_FAILURE))))
 
-#define DEBUG_INIT(dbg_lvl) do { \
-    if (dbg_lvl != SSSDBG_INVALID) { \
-        debug_level = debug_convert_old_level(dbg_lvl); \
-    } else { \
-        debug_level = SSSDBG_UNRESOLVED; \
-    } \
-\
-    talloc_set_log_fn(talloc_log_fn); \
-} while (0)
-
-/* CLI tools shall debug to stderr even when SSSD was compiled with journald
- * support
- */
-#define DEBUG_CLI_INIT(dbg_lvl) do { \
-    DEBUG_INIT(dbg_lvl);             \
-    sss_logger = STDERR_LOGGER;      \
-} while (0)
-
 #define PRINT(fmt, ...) fprintf(stdout, gettext(fmt), ##__VA_ARGS__)
 #define ERROR(fmt, ...) fprintf(stderr, gettext(fmt), ##__VA_ARGS__)
 
+/* not to be used explictly, ise 'DEBUG_INIT' instead */
+void _sss_debug_init(int dbg_lvl, const char *logger);
+
 #endif /* __SSSD_DEBUG_H__ */
diff --git a/src/util/server.c b/src/util/server.c
index f1ed5d9b08..f9a29c1f81 100644
--- a/src/util/server.c
+++ b/src/util/server.c
@@ -463,6 +463,11 @@ int server_setup(const char *name, int flags,
     char *pidfile_name;
     int cfg_debug_level = SSSDBG_INVALID;
 
+    debug_prg_name = strdup(name);
+    if (!debug_prg_name) {
+        return ENOMEM;
+    }
+
     my_pid = getpid();
     ret = setpgid(my_pid, my_pid);
     if (ret != EOK) {
@@ -488,11 +493,6 @@ int server_setup(const char *name, int flags,
         }
     }
 
-    debug_prg_name = strdup(name);
-    if (!debug_prg_name) {
-        return ENOMEM;
-    }
-
     setenv("_SSS_LOOPS", "NO", 0);
 
     /* To make sure the domain cannot be set from the environment, unset the

From 506edcdebea473a07feae44871c74858069440a5 Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Sat, 6 Mar 2021 17:46:20 +0100
Subject: [PATCH 06/11] DEBUG: remove sss_set_logger() from public API

---
 src/tests/debug-tests.c | 2 ++
 src/util/debug.c        | 1 +
 src/util/debug.h        | 2 --
 3 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/src/tests/debug-tests.c b/src/tests/debug-tests.c
index 077fa6dadb..e27fee4578 100644
--- a/src/tests/debug-tests.c
+++ b/src/tests/debug-tests.c
@@ -30,6 +30,8 @@
 #include "util/util.h"
 #include "tests/common.h"
 
+void sss_set_logger(const char *logger);  /* from debug.c */
+
 #define DEBUG_TEST_ERROR    -1
 #define DEBUG_TEST_NOK      1
 #define DEBUG_TEST_NOK_TS   2
diff --git a/src/util/debug.c b/src/util/debug.c
index e99834b8e6..559c4ecc6e 100644
--- a/src/util/debug.c
+++ b/src/util/debug.c
@@ -55,6 +55,7 @@ const char *sss_logger_str[] = {
 };
 
 
+/* this function isn't static to let access from debug-tests.c */
 void sss_set_logger(const char *logger)
 {
     if (logger == NULL) {
diff --git a/src/util/debug.h b/src/util/debug.h
index 4ecd21c2fc..9291e3a351 100644
--- a/src/util/debug.h
+++ b/src/util/debug.h
@@ -61,8 +61,6 @@ extern const char *debug_log_file;
     DEBUG_INIT(dbg_lvl, sss_logger_str[STDERR_LOGGER]); \
 } while (0)
 
-void sss_set_logger(const char *logger);
-
 void sss_vdebug_fn(const char *file,
                    long line,
                    const char *function,

From 8957212b36220e5cf94270f5725fd015ce563f4c Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Sat, 6 Mar 2021 19:22:16 +0100
Subject: [PATCH 07/11] DEBUG: added several comments to debug.h API and moved
 rarely used / "private" functions to the bottom.

---
 src/util/debug.c |   2 +-
 src/util/debug.h | 112 +++++++++++++++++++++++++++++------------------
 2 files changed, 70 insertions(+), 44 deletions(-)

diff --git a/src/util/debug.c b/src/util/debug.c
index 559c4ecc6e..c742fb2b31 100644
--- a/src/util/debug.c
+++ b/src/util/debug.c
@@ -481,7 +481,7 @@ int rotate_debug_files(void)
     return open_debug_file();
 }
 
-void talloc_log_fn(const char *message)
+void _sss_talloc_log_fn(const char *message)
 {
     DEBUG(SSSDBG_FATAL_FAILURE, "%s\n", message);
 }
diff --git a/src/util/debug.h b/src/util/debug.h
index 9291e3a351..39ddfb4027 100644
--- a/src/util/debug.h
+++ b/src/util/debug.h
@@ -26,13 +26,12 @@
 #include <stdio.h>
 #include <stdbool.h>
 
-#ifdef HAVE_FUNCTION_ATTRIBUTE_FORMAT
-#define SSS_ATTRIBUTE_PRINTF(a1, a2) __attribute__((format (printf, a1, a2)))
-#else
-#define SSS_ATTRIBUTE_PRINTF(a1, a2)
-#endif
+#define SSSDBG_TIMESTAMP_UNRESOLVED      -1
+#define SSSDBG_TIMESTAMP_DEFAULT          1
+
+#define SSSDBG_MICROSECONDS_UNRESOLVED   -1
+#define SSSDBG_MICROSECONDS_DEFAULT       0
 
-#define APPEND_LINE_FEED 0x1
 
 enum sss_logger_t {
     STDERR_LOGGER = 0,
@@ -42,18 +41,18 @@ enum sss_logger_t {
 #endif
 };
 
-extern const char *sss_logger_str[];
+extern const char *sss_logger_str[]; /* mapping: sss_logger_t -> string */
 extern const char *debug_prg_name;
 extern int debug_level;
 extern int debug_timestamps;
 extern int debug_microseconds;
 extern enum sss_logger_t sss_logger;
-extern const char *debug_log_file;
+extern const char *debug_log_file;   /* only file name, excluding path */
 
 
-#define DEBUG_INIT(dbg_lvl, logger) do { \
-    _sss_debug_init(dbg_lvl, logger);    \
-    talloc_set_log_fn(talloc_log_fn);    \
+#define DEBUG_INIT(dbg_lvl, logger) do {   \
+    _sss_debug_init(dbg_lvl, logger);      \
+    talloc_set_log_fn(_sss_talloc_log_fn); \
 } while (0)
 
 /* CLI tools shall debug to stderr */
@@ -61,26 +60,30 @@ extern const char *debug_log_file;
     DEBUG_INIT(dbg_lvl, sss_logger_str[STDERR_LOGGER]); \
 } while (0)
 
-void sss_vdebug_fn(const char *file,
-                   long line,
-                   const char *function,
-                   int level,
-                   int flags,
-                   const char *format,
-                   va_list ap);
-void sss_debug_fn(const char *file,
-                  long line,
-                  const char *function,
-                  int level,
-                  const char *format, ...) SSS_ATTRIBUTE_PRINTF(5, 6);
+/* debug_convert_old_level() converts "old" style decimal notation
+ * to bitmask composed of SSSDBG_*
+ * Used explicitly, for example, while processing user input
+ * in sssctl_logs.
+ */
 int debug_convert_old_level(int old_level);
+
+/* set_debug_file_from_fd() is used by *_child processes as those
+ * don't manage logs files on their own but instead receive fd arg
+ * on command line.
+ */
 errno_t set_debug_file_from_fd(const int fd);
+
+/* get_fd_from_debug_file() is used to redirect STDERR_FILENO
+ * to currently open log file fd while running external helpers
+ * (e.g. nsupdate, ipa_get_keytab)
+ */
 int get_fd_from_debug_file(void);
+
+/* chown_debug_file() uses 'debug_log_file' in case 'filename == NULL' */
 int chown_debug_file(const char *filename, uid_t uid, gid_t gid);
 int open_debug_file_ex(const char *filename, FILE **filep, bool want_cloexec);
 int open_debug_file(void);
 int rotate_debug_files(void);
-void talloc_log_fn(const char *msg);
 
 #define SSS_DOM_ENV           "_SSS_DOM"
 
@@ -107,24 +110,6 @@ void talloc_log_fn(const char *msg);
 #define SSSDBG_MASK_ALL  0x1F7F0
 #define SSSDBG_DEFAULT   (SSSDBG_FATAL_FAILURE|SSSDBG_CRIT_FAILURE|SSSDBG_OP_FAILURE)
 
-#define SSSDBG_TIMESTAMP_UNRESOLVED   -1
-#define SSSDBG_TIMESTAMP_DEFAULT       1
-
-#define SSSDBG_MICROSECONDS_UNRESOLVED   -1
-#define SSSDBG_MICROSECONDS_DEFAULT       0
-
-#define SSSD_LOGGER_OPTS \
-        {"logger", '\0', POPT_ARG_STRING, &opt_logger, 0, \
-         _("Set logger"), "stderr|files|journald"},
-
-
-#define SSSD_DEBUG_OPTS \
-        {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0, \
-         _("Debug level"), NULL}, \
-        {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0, \
-         _("Add debug timestamps"), NULL}, \
-        {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0, \
-         _("Show timestamps with microseconds"), NULL},
 
 /** \def DEBUG(level, format, ...)
     \brief macro to generate debug messages
@@ -153,10 +138,51 @@ void talloc_log_fn(const char *msg);
                                             (level & (SSSDBG_FATAL_FAILURE | \
                                                       SSSDBG_CRIT_FAILURE))))
 
+/* SSSD_*_OPTS are used as 'poptOption' entries */
+#define SSSD_LOGGER_OPTS \
+        {"logger", '\0', POPT_ARG_STRING, &opt_logger, 0, \
+         _("Set logger"), "stderr|files|journald"},
+
+#define SSSD_DEBUG_OPTS \
+        {"debug-level", 'd', POPT_ARG_INT, &debug_level, 0, \
+         _("Debug level"), NULL}, \
+        {"debug-timestamps", 0, POPT_ARG_INT, &debug_timestamps, 0, \
+         _("Add debug timestamps"), NULL}, \
+        {"debug-microseconds", 0, POPT_ARG_INT, &debug_microseconds, 0, \
+         _("Show timestamps with microseconds"), NULL},
+
+
 #define PRINT(fmt, ...) fprintf(stdout, gettext(fmt), ##__VA_ARGS__)
 #define ERROR(fmt, ...) fprintf(stderr, gettext(fmt), ##__VA_ARGS__)
 
-/* not to be used explictly, ise 'DEBUG_INIT' instead */
+
+#ifdef HAVE_FUNCTION_ATTRIBUTE_FORMAT
+#define SSS_ATTRIBUTE_PRINTF(a1, a2) __attribute__((format (printf, a1, a2)))
+#else
+#define SSS_ATTRIBUTE_PRINTF(a1, a2)
+#endif
+
+/* sss_*debug_fn() are rarely needed to be used explicitly
+ * (common example: provision of a logger function to 3rd party lib)
+ * For normal logs use DEBUG() instead.
+ */
+void sss_vdebug_fn(const char *file,
+                   long line,
+                   const char *function,
+                   int level,
+                   int flags,
+                   const char *format,
+                   va_list ap);
+void sss_debug_fn(const char *file,
+                  long line,
+                  const char *function,
+                  int level,
+                  const char *format, ...) SSS_ATTRIBUTE_PRINTF(5, 6);
+
+#define APPEND_LINE_FEED 0x1 /* can be used as a sss_vdebug_fn() flag */
+
+/* not to be used explictly, use 'DEBUG_INIT' instead */
 void _sss_debug_init(int dbg_lvl, const char *logger);
+void _sss_talloc_log_fn(const char *msg);
 
 #endif /* __SSSD_DEBUG_H__ */

From 1390251857c5148977e51a31d20df1f4367f9bc8 Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Sat, 6 Mar 2021 19:47:51 +0100
Subject: [PATCH 08/11] Moved SSSDBG_MASK_ALL out of debug.h since is it is
 only used in tests.

---
 src/tests/common.h | 5 +++++
 src/util/debug.h   | 8 ++------
 2 files changed, 7 insertions(+), 6 deletions(-)

diff --git a/src/tests/common.h b/src/tests/common.h
index 3ce92098ba..8ef24f4ca3 100644
--- a/src/tests/common.h
+++ b/src/tests/common.h
@@ -25,6 +25,11 @@
 #ifndef __TESTS_COMMON_H__
 #define __TESTS_COMMON_H__
 
+/* used to enable all debug levels in debug-tests.c and find_uid-tests.c
+ * 0x0800 isn't used for historical reasons: 0x1FFF0 - 0x0800 = 0x1F7F0
+ */
+#define SSSDBG_MASK_ALL  0x1F7F0
+
 #include "config.h"
 
 #include <talloc.h>
diff --git a/src/util/debug.h b/src/util/debug.h
index 39ddfb4027..f9a127151d 100644
--- a/src/util/debug.h
+++ b/src/util/debug.h
@@ -87,6 +87,7 @@ int rotate_debug_files(void);
 
 #define SSS_DOM_ENV           "_SSS_DOM"
 
+/* 0x0800 isn't used for historical reasons */
 #define SSSDBG_FATAL_FAILURE  0x0010   /* level 0 */
 #define SSSDBG_CRIT_FAILURE   0x0020   /* level 1 */
 #define SSSDBG_OP_FAILURE     0x0040   /* level 2 */
@@ -102,12 +103,7 @@ int rotate_debug_files(void);
 #define SSSDBG_IMPORTANT_INFO SSSDBG_OP_FAILURE
 
 #define SSSDBG_INVALID        -1
-#define SSSDBG_UNRESOLVED     0
-
-/* enables all debug levels;
-   0x0800 isn't used for historical reasons: 0x1FFF0 - 0x0800 = 0x1F7F0
-*/
-#define SSSDBG_MASK_ALL  0x1F7F0
+#define SSSDBG_UNRESOLVED      0
 #define SSSDBG_DEFAULT   (SSSDBG_FATAL_FAILURE|SSSDBG_CRIT_FAILURE|SSSDBG_OP_FAILURE)
 
 

From c7a3a49632852a1119248eda1f83296d153b572c Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Sat, 6 Mar 2021 20:46:12 +0100
Subject: [PATCH 09/11] DEBUG: incorporate open_debug_file() into DEBUG_INIT

This makes code less error-prone reducing amount of function calls required
for debug initialization.
---
 src/monitor/monitor.c          | 10 +---------
 src/tests/cmocka/dummy_child.c |  4 +---
 src/util/debug.c               | 22 ++++++++++++++++------
 src/util/debug.h               |  5 ++++-
 src/util/server.c              |  9 ---------
 5 files changed, 22 insertions(+), 28 deletions(-)

diff --git a/src/monitor/monitor.c b/src/monitor/monitor.c
index 48d126c2ea..e168bb4993 100644
--- a/src/monitor/monitor.c
+++ b/src/monitor/monitor.c
@@ -2470,6 +2470,7 @@ int main(int argc, const char *argv[])
         opt_logger = sss_logger_str[STDERR_LOGGER];
     }
 
+    /* default value of 'debug_prg_name' will be used */
     DEBUG_INIT(debug_level, opt_logger);
 
     if (opt_config_file) {
@@ -2494,15 +2495,6 @@ int main(int argc, const char *argv[])
     /* the monitor should not run a watchdog on itself */
     flags |= FLAGS_NO_WATCHDOG;
 
-    /* Open before server_setup() does to have logging
-     * during configuration checking */
-    if (sss_logger == FILES_LOGGER) {
-        ret = open_debug_file();
-        if (ret) {
-            return 7;
-        }
-    }
-
 #ifdef USE_KEYRING
     /* Do this before all the forks, it sets the session key ring so all
      * keys are private to the daemon and cannot be read by any other process
diff --git a/src/tests/cmocka/dummy_child.c b/src/tests/cmocka/dummy_child.c
index 62bccf0895..33b8c77fcb 100644
--- a/src/tests/cmocka/dummy_child.c
+++ b/src/tests/cmocka/dummy_child.c
@@ -33,7 +33,6 @@
 int main(int argc, const char *argv[])
 {
     int opt;
-    int debug_fd = -1;
     char *opt_logger = NULL;
     poptContext pc;
     ssize_t len;
@@ -47,8 +46,6 @@ int main(int argc, const char *argv[])
     struct poptOption long_options[] = {
         POPT_AUTOHELP
         SSSD_DEBUG_OPTS
-        {"debug-fd", 0, POPT_ARG_INT, &debug_fd, 0,
-         _("An open file descriptor for the debug logs"), NULL},
         SSSD_LOGGER_OPTS
         {"guitar", 0, POPT_ARG_STRING, &guitar, 0, _("Who plays guitar"), NULL },
         {"drums", 0, POPT_ARG_STRING, &drums, 0, _("Who plays drums"), NULL },
@@ -71,6 +68,7 @@ int main(int argc, const char *argv[])
     }
     poptFreeContext(pc);
 
+    debug_log_file = "test_dummy_child";
     DEBUG_INIT(debug_level, opt_logger);
 
     action = getenv("TEST_CHILD_ACTION");
diff --git a/src/util/debug.c b/src/util/debug.c
index c742fb2b31..2e01311bf1 100644
--- a/src/util/debug.c
+++ b/src/util/debug.c
@@ -84,6 +84,11 @@ void sss_set_logger(const char *logger)
     }
 }
 
+static int _sss_open_debug_file(void)
+{
+    return open_debug_file_ex(NULL, NULL, true);
+}
+
 void _sss_debug_init(int dbg_lvl, const char *logger)
 {
     if (dbg_lvl != SSSDBG_INVALID) {
@@ -93,6 +98,16 @@ void _sss_debug_init(int dbg_lvl, const char *logger)
     }
 
     sss_set_logger(logger);
+
+    /* if 'FILES_LOGGER' is requested then open log file, if it wasn't
+     * initialized before via set_debug_file_from_fd().
+     */
+    if ((sss_logger == FILES_LOGGER) && (debug_file == NULL)) {
+        if (_sss_open_debug_file() != 0) {
+            ERROR("Error opening log file, falling back to stderr\n");
+            sss_logger = STDERR_LOGGER;
+        }
+    }
 }
 
 errno_t set_debug_file_from_fd(const int fd)
@@ -435,11 +450,6 @@ int open_debug_file_ex(const char *filename, FILE **filep, bool want_cloexec)
     return EOK;
 }
 
-int open_debug_file(void)
-{
-    return open_debug_file_ex(NULL, NULL, true);
-}
-
 int rotate_debug_files(void)
 {
     int ret;
@@ -478,7 +488,7 @@ int rotate_debug_files(void)
 
     debug_file = NULL;
 
-    return open_debug_file();
+    return _sss_open_debug_file();
 }
 
 void _sss_talloc_log_fn(const char *message)
diff --git a/src/util/debug.h b/src/util/debug.h
index f9a127151d..a3adfe5761 100644
--- a/src/util/debug.h
+++ b/src/util/debug.h
@@ -50,6 +50,7 @@ extern enum sss_logger_t sss_logger;
 extern const char *debug_log_file;   /* only file name, excluding path */
 
 
+/* converts log level from "old" notation and opens log file if needed */
 #define DEBUG_INIT(dbg_lvl, logger) do {   \
     _sss_debug_init(dbg_lvl, logger);      \
     talloc_set_log_fn(_sss_talloc_log_fn); \
@@ -81,8 +82,10 @@ int get_fd_from_debug_file(void);
 
 /* chown_debug_file() uses 'debug_log_file' in case 'filename == NULL' */
 int chown_debug_file(const char *filename, uid_t uid, gid_t gid);
+
+/* open_debug_file_ex() is used to open log file for *_child processes */
 int open_debug_file_ex(const char *filename, FILE **filep, bool want_cloexec);
-int open_debug_file(void);
+
 int rotate_debug_files(void);
 
 #define SSS_DOM_ENV           "_SSS_DOM"
diff --git a/src/util/server.c b/src/util/server.c
index f9a29c1f81..9c4273f305 100644
--- a/src/util/server.c
+++ b/src/util/server.c
@@ -655,15 +655,6 @@ int server_setup(const char *name, int flags,
         return EIO;
     }
 
-    /* open log file if told so */
-    if (sss_logger == FILES_LOGGER) {
-        ret = open_debug_file();
-        if (ret != EOK) {
-            DEBUG(SSSDBG_FATAL_FAILURE, "Error setting up logging (%d) "
-                                         "[%s]\n", ret, strerror(ret));
-            return ret;
-        }
-    }
     DEBUG(SSSDBG_IMPORTANT_INFO,
           "Starting with debug level = %#.4x\n", debug_level);
 

From 72fdfc56b3098cad2cae1d8a68976170eb0f58ae Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Fri, 12 Mar 2021 18:04:31 +0100
Subject: [PATCH 10/11] MONITOR: added logging of cmd used to start services

---
 src/monitor/monitor.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/src/monitor/monitor.c b/src/monitor/monitor.c
index e168bb4993..d5fe688056 100644
--- a/src/monitor/monitor.c
+++ b/src/monitor/monitor.c
@@ -1136,6 +1136,13 @@ static int get_service_config(struct mt_ctx *ctx, const char *name,
             talloc_free(svc);
             return ENOMEM;
         }
+
+        DEBUG(SSSDBG_CONF_SETTINGS, "Formed command '%s' for service '%s'\n",
+              svc->command, svc->name);
+    } else {
+        DEBUG(SSSDBG_CONF_SETTINGS,
+              "Using custom command '%s' for service '%s'\n",
+              svc->command, svc->name);
     }
 
     svc->last_restart = now;
@@ -1288,6 +1295,13 @@ static int get_provider_config(struct mt_ctx *ctx, const char *name,
             talloc_free(svc);
             return ENOMEM;
         }
+
+        DEBUG(SSSDBG_CONF_SETTINGS, "Formed command '%s' for provider '%s'\n",
+              svc->command, svc->identity);
+    } else {
+        DEBUG(SSSDBG_CONF_SETTINGS,
+              "Using custom command '%s' for provider '%s'\n",
+              svc->command, svc->identity);
     }
 
     svc->last_restart = now;

From 5dcd0dc2d43bce3674560014a37716d42ee5f5bc Mon Sep 17 00:00:00 2001
From: Alexey Tikhonov <atikhono@redhat.com>
Date: Fri, 12 Mar 2021 19:27:12 +0100
Subject: [PATCH 11/11] DEBUG: introduce SSSDBG_TOOLS_DEFAULT

Resolves: https://github.com/SSSD/sssd/issues/5488
---
 src/sss_client/ssh/sss_ssh_authorizedkeys.c  | 2 +-
 src/sss_client/ssh/sss_ssh_knownhostsproxy.c | 2 +-
 src/tools/common/sss_tools.c                 | 2 +-
 src/tools/sss_cache.c                        | 2 +-
 src/tools/sss_groupadd.c                     | 2 +-
 src/tools/sss_groupdel.c                     | 2 +-
 src/tools/sss_groupmod.c                     | 2 +-
 src/tools/sss_groupshow.c                    | 2 +-
 src/tools/sss_seed.c                         | 2 +-
 src/tools/sss_useradd.c                      | 2 +-
 src/tools/sss_userdel.c                      | 2 +-
 src/tools/sss_usermod.c                      | 2 +-
 src/util/debug.h                             | 1 +
 13 files changed, 13 insertions(+), 12 deletions(-)

diff --git a/src/sss_client/ssh/sss_ssh_authorizedkeys.c b/src/sss_client/ssh/sss_ssh_authorizedkeys.c
index e356f28c31..324e5e3a30 100644
--- a/src/sss_client/ssh/sss_ssh_authorizedkeys.c
+++ b/src/sss_client/ssh/sss_ssh_authorizedkeys.c
@@ -32,7 +32,7 @@
 int main(int argc, const char **argv)
 {
     TALLOC_CTX *mem_ctx = NULL;
-    int pc_debug = SSSDBG_FATAL_FAILURE;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     const char *pc_domain = NULL;
     const char *pc_user = NULL;
     struct poptOption long_options[] = {
diff --git a/src/sss_client/ssh/sss_ssh_knownhostsproxy.c b/src/sss_client/ssh/sss_ssh_knownhostsproxy.c
index 3cd12b4806..170ba30a3c 100644
--- a/src/sss_client/ssh/sss_ssh_knownhostsproxy.c
+++ b/src/sss_client/ssh/sss_ssh_knownhostsproxy.c
@@ -174,7 +174,7 @@ connect_proxy_command(char **args)
 int main(int argc, const char **argv)
 {
     TALLOC_CTX *mem_ctx = NULL;
-    int pc_debug = SSSDBG_FATAL_FAILURE;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     int pc_port = 22;
     const char *pc_domain = NULL;
     const char *pc_host = NULL;
diff --git a/src/tools/common/sss_tools.c b/src/tools/common/sss_tools.c
index 368d09ae28..637e251f6e 100644
--- a/src/tools/common/sss_tools.c
+++ b/src/tools/common/sss_tools.c
@@ -56,7 +56,7 @@ static void sss_tool_common_opts(struct sss_tool_ctx *tool_ctx,
                                  int *argc, const char **argv)
 {
     poptContext pc;
-    int debug = SSSDBG_DEFAULT;
+    int debug = SSSDBG_TOOLS_DEFAULT;
     int orig_argc = *argc;
     int help = 0;
 
diff --git a/src/tools/sss_cache.c b/src/tools/sss_cache.c
index cea900bf1d..b5391b16d5 100644
--- a/src/tools/sss_cache.c
+++ b/src/tools/sss_cache.c
@@ -709,7 +709,7 @@ static errno_t init_context(int argc, const char *argv[],
     struct cache_tool_ctx *ctx = NULL;
     int idb = INVALIDATE_NONE;
     struct input_values values = { 0 };
-    int debug = SSSDBG_DEFAULT;
+    int debug = SSSDBG_TOOLS_DEFAULT;
     errno_t ret = EOK;
 
     poptContext pc = NULL;
diff --git a/src/tools/sss_groupadd.c b/src/tools/sss_groupadd.c
index f71d6dde72..91559116dc 100644
--- a/src/tools/sss_groupadd.c
+++ b/src/tools/sss_groupadd.c
@@ -34,7 +34,7 @@
 int main(int argc, const char **argv)
 {
     gid_t pc_gid = 0;
-    int pc_debug = SSSDBG_DEFAULT;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     struct poptOption long_options[] = {
         POPT_AUTOHELP
         { "debug",'\0', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_debug,
diff --git a/src/tools/sss_groupdel.c b/src/tools/sss_groupdel.c
index 5dcc2056db..e644417585 100644
--- a/src/tools/sss_groupdel.c
+++ b/src/tools/sss_groupdel.c
@@ -33,7 +33,7 @@
 int main(int argc, const char **argv)
 {
     int ret = EXIT_SUCCESS;
-    int pc_debug = SSSDBG_DEFAULT;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     const char *pc_groupname = NULL;
     struct tools_ctx *tctx = NULL;
 
diff --git a/src/tools/sss_groupmod.c b/src/tools/sss_groupmod.c
index eddc7034a7..8770b66840 100644
--- a/src/tools/sss_groupmod.c
+++ b/src/tools/sss_groupmod.c
@@ -35,7 +35,7 @@
 int main(int argc, const char **argv)
 {
     gid_t pc_gid = 0;
-    int pc_debug = SSSDBG_DEFAULT;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     struct poptOption long_options[] = {
         POPT_AUTOHELP
         { "debug", '\0', POPT_ARG_INT | POPT_ARGFLAG_DOC_HIDDEN, &pc_debug,
diff --git a/src/tools/sss_groupshow.c b/src/tools/sss_groupshow.c
index 7b0fbe1177..aa618eecb1 100644
--- a/src/tools/sss_groupshow.c
+++ b/src/tools/sss_groupshow.c
@@ -654,7 +654,7 @@ static void print_recursive(struct group_info **group_members, unsigned level)
 int main(int argc, const char **argv)
 {
     int ret = EXIT_SUCCESS;
-    int pc_debug = SSSDBG_DEFAULT;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     bool pc_recursive = false;
     const char *pc_groupname = NULL;
     struct tools_ctx *tctx = NULL;
diff --git a/src/tools/sss_seed.c b/src/tools/sss_seed.c
index 1189604a30..17ba819565 100644
--- a/src/tools/sss_seed.c
+++ b/src/tools/sss_seed.c
@@ -460,7 +460,7 @@ static int seed_init(TALLOC_CTX *mem_ctx,
                      struct seed_ctx **_sctx)
 {
     TALLOC_CTX *tmp_ctx = NULL;
-    int pc_debug = SSSDBG_DEFAULT;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     const char *pc_domain = NULL;
     const char *pc_name = NULL;
     uid_t pc_uid = 0;
diff --git a/src/tools/sss_useradd.c b/src/tools/sss_useradd.c
index ca2cbd6c11..fa1091ec8c 100644
--- a/src/tools/sss_useradd.c
+++ b/src/tools/sss_useradd.c
@@ -38,7 +38,7 @@ int main(int argc, const char **argv)
     const char *pc_gecos = NULL;
     const char *pc_home = NULL;
     char *pc_shell = NULL;
-    int pc_debug = SSSDBG_DEFAULT;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     int pc_create_home = 0;
     const char *pc_username = NULL;
     const char *pc_skeldir = NULL;
diff --git a/src/tools/sss_userdel.c b/src/tools/sss_userdel.c
index bd703fd2e5..60bb0f8359 100644
--- a/src/tools/sss_userdel.c
+++ b/src/tools/sss_userdel.c
@@ -125,7 +125,7 @@ int main(int argc, const char **argv)
     struct tools_ctx *tctx = NULL;
     const char *pc_username = NULL;
 
-    int pc_debug = SSSDBG_DEFAULT;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     int pc_remove = 0;
     int pc_force = 0;
     int pc_kick = 0;
diff --git a/src/tools/sss_usermod.c b/src/tools/sss_usermod.c
index 6a818f13ad..0f3230d272 100644
--- a/src/tools/sss_usermod.c
+++ b/src/tools/sss_usermod.c
@@ -40,7 +40,7 @@ int main(int argc, const char **argv)
     char *pc_gecos = NULL;
     char *pc_home = NULL;
     char *pc_shell = NULL;
-    int pc_debug = SSSDBG_DEFAULT;
+    int pc_debug = SSSDBG_TOOLS_DEFAULT;
     const char *pc_selinux_user = NULL;
     struct poptOption long_options[] = {
         POPT_AUTOHELP
diff --git a/src/util/debug.h b/src/util/debug.h
index a3adfe5761..54a7e39346 100644
--- a/src/util/debug.h
+++ b/src/util/debug.h
@@ -108,6 +108,7 @@ int rotate_debug_files(void);
 #define SSSDBG_INVALID        -1
 #define SSSDBG_UNRESOLVED      0
 #define SSSDBG_DEFAULT   (SSSDBG_FATAL_FAILURE|SSSDBG_CRIT_FAILURE|SSSDBG_OP_FAILURE)
+#define SSSDBG_TOOLS_DEFAULT (SSSDBG_FATAL_FAILURE)
 
 
 /** \def DEBUG(level, format, ...)
