"Fossies" - the Fresh Open Source Software Archive

Member "sssd-2.4.2/src/monitor/monitor.c" (19 Feb 2021, 78176 Bytes) of package /linux/misc/sssd-2.4.2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "monitor.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.4.1_vs_2.4.2.

    1 /*
    2    SSSD
    3 
    4    Service monitor
    5 
    6    Copyright (C) Simo Sorce         2008
    7 
    8    This program is free software; you can redistribute it and/or modify
    9    it under the terms of the GNU General Public License as published by
   10    the Free Software Foundation; either version 3 of the License, or
   11    (at your option) any later version.
   12 
   13    This program is distributed in the hope that it will be useful,
   14    but WITHOUT ANY WARRANTY; without even the implied warranty of
   15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   16    GNU General Public License for more details.
   17 
   18    You should have received a copy of the GNU General Public License
   19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
   20 */
   21 
   22 #include "util/util.h"
   23 #include "util/child_common.h"
   24 #include <sys/types.h>
   25 #include <sys/wait.h>
   26 #include <sys/time.h>
   27 #include <sys/param.h>
   28 #include <time.h>
   29 #include <string.h>
   30 #include <signal.h>
   31 #ifdef HAVE_SYS_INOTIFY_H
   32 #include <sys/inotify.h>
   33 #endif
   34 #include <sys/stat.h>
   35 #include <unistd.h>
   36 #include <fcntl.h>
   37 #include <popt.h>
   38 #include <tevent.h>
   39 
   40 /* Needed for res_init() */
   41 #include <netinet/in.h>
   42 #include <arpa/nameser.h>
   43 #include <resolv.h>
   44 
   45 #include "confdb/confdb.h"
   46 #include "confdb/confdb_setup.h"
   47 #include "db/sysdb.h"
   48 #include "monitor/monitor.h"
   49 #include "util/inotify.h"
   50 #include "sss_iface/sss_iface_async.h"
   51 
   52 #ifdef USE_KEYRING
   53 #include <keyutils.h>
   54 #endif
   55 
   56 #ifdef HAVE_SYSTEMD
   57 #include <systemd/sd-daemon.h>
   58 #endif
   59 
   60 #define MONITOR_VERSION 0x0001
   61 
   62 /* terminate the child after this interval by default if it
   63  * doesn't shutdown on receiving SIGTERM */
   64 #define MONITOR_DEF_FORCE_TIME 60
   65 
   66 /* TODO: get the restart related values from config */
   67 #define MONITOR_RESTART_CNT_INTERVAL_RESET   30
   68 /* maximum allowed number of service restarts if the restarts
   69  * were less than MONITOR_RESTART_CNT_INTERVAL_RESET apart, which would
   70  * indicate a crash after startup or after every request */
   71 #define MONITOR_MAX_SVC_RESTARTS    2
   72 /* The services are restarted with a delay in case the restart was
   73  * hitting a race condition where the DP is not ready yet either.
   74  * The MONITOR_MAX_RESTART_DELAY defines the maximum delay between
   75  * restarts.
   76  */
   77 #define MONITOR_MAX_RESTART_DELAY   4
   78 
   79 /* Special value to leave the Kerberos Replay Cache set to use
   80  * the libkrb5 defaults
   81  */
   82 #define KRB5_RCACHE_DIR_DISABLE "__LIBKRB5_DEFAULTS__"
   83 
   84 /* Warning messages */
   85 #define CONF_FILE_PERM_ERROR_MSG "Cannot read config file %s. Please check "\
   86                                  "that the file is accessible only by the "\
   87                                  "owner and owned by root.root.\n"
   88 
   89 int cmdline_debug_level;
   90 int cmdline_debug_timestamps;
   91 int cmdline_debug_microseconds;
   92 
   93 struct svc_spy;
   94 
   95 struct mt_svc {
   96     struct mt_svc *prev;
   97     struct mt_svc *next;
   98     enum mt_svc_type type;
   99 
  100     struct sbus_connection *conn;
  101     struct svc_spy *conn_spy;
  102 
  103     struct mt_ctx *mt_ctx;
  104 
  105     char *provider;
  106     char *command;
  107     char *name;
  108     char *identity;
  109     const char *busname;
  110     pid_t pid;
  111 
  112     int kill_time;
  113 
  114     bool svc_started;
  115     bool socket_activated; /* also used for dbus-activated services */
  116 
  117     int restarts;
  118     time_t last_restart;
  119 
  120     int debug_level;
  121 
  122     struct sss_child_ctx *child_ctx;
  123 };
  124 
  125 typedef int (*monitor_reconf_fn)(struct config_file_ctx *file_ctx,
  126                                  const char *filename);
  127 
  128 struct config_file_callback {
  129     int wd;
  130     monitor_reconf_fn fn;
  131     char *filename;
  132     time_t modified;
  133     struct config_file_callback *next;
  134     struct config_file_callback *prev;
  135 };
  136 
  137 struct config_file_ctx {
  138     struct config_file_inotify_check {
  139         struct snotify_ctx *snctx;
  140     } inotify_check;
  141 
  142     struct config_file_poll_check {
  143         TALLOC_CTX *parent_ctx;
  144         struct tevent_timer *timer;
  145         struct config_file_callback *callbacks;
  146     } poll_check;
  147 
  148     monitor_reconf_fn fn;
  149     struct mt_ctx *mt_ctx;
  150 };
  151 
  152 struct mt_ctx {
  153     struct tevent_context *ev;
  154     struct confdb_ctx *cdb;
  155     struct sss_domain_info *domains;
  156     char **services;
  157     int num_services;
  158     int started_services;
  159     struct mt_svc *svc_list;
  160     struct config_file_ctx *file_ctx;
  161     int service_id_timeout;
  162     bool check_children;
  163     bool services_started;
  164     struct netlink_ctx *nlctx;
  165     const char *conf_path;
  166     struct sss_sigchild_ctx *sigchld_ctx;
  167     bool pid_file_created;
  168     bool is_daemon;
  169     pid_t parent_pid;
  170 
  171     struct sbus_server *sbus_server;
  172     struct sbus_connection *sbus_conn;
  173 
  174     /* For running unprivileged services */
  175     uid_t uid;
  176     gid_t gid;
  177 };
  178 
  179 static int start_service(struct mt_svc *mt_svc);
  180 
  181 static void monitor_service_shutdown(struct mt_svc *svc);
  182 
  183 static int service_signal_reset_offline(struct mt_svc *svc);
  184 
  185 static int get_service_config(struct mt_ctx *ctx, const char *name,
  186                               struct mt_svc **svc_cfg);
  187 static int get_provider_config(struct mt_ctx *ctx, const char *name,
  188                               struct mt_svc **svc_cfg);
  189 static int add_new_service(struct mt_ctx *ctx,
  190                            const char *name,
  191                            int restarts);
  192 static int add_new_provider(struct mt_ctx *ctx,
  193                             const char *name,
  194                             int restarts);
  195 
  196 static char *check_service(char *service);
  197 
  198 static int mark_service_as_started(struct mt_svc *svc);
  199 
  200 static int monitor_cleanup(void);
  201 
  202 static void network_status_change_cb(void *cb_data)
  203 {
  204     struct mt_svc *iter;
  205     struct mt_ctx *ctx = (struct mt_ctx *) cb_data;
  206 
  207     DEBUG(SSSDBG_TRACE_INTERNAL, "A networking status change detected "
  208           "signaling providers to reset offline status\n");
  209     for (iter = ctx->svc_list; iter; iter = iter->next) {
  210         /* Don't signal services, only providers */
  211         if (iter->provider) {
  212             service_signal_reset_offline(iter);
  213         }
  214     }
  215 }
  216 
  217 static int add_svc_conn_spy(struct mt_svc *svc);
  218 
  219 static int service_not_found(const char *svc_name,
  220                              struct mt_svc **_svc)
  221 {
  222     DEBUG(SSSDBG_FATAL_FAILURE,
  223           "Unable to find peer [%s] in list of services, "
  224           "killing connection!\n", svc_name);
  225 
  226     *_svc = NULL;
  227     return ENOENT;
  228 }
  229 
  230 #ifdef HAVE_SYSTEMD
  231 errno_t socket_activated_service_not_found(struct mt_ctx *mt_ctx,
  232                                            const char *svc_name,
  233                                            bool is_provider,
  234                                            struct mt_svc **_svc)
  235 {
  236     struct mt_svc *svc = NULL;
  237     int ret;
  238 
  239     if (is_provider) {
  240         return service_not_found(svc_name, _svc);
  241     }
  242 
  243     /* As the service is a responder and wasn't part of the services' list, it means
  244      * the service has been socket/dbus activated and has to be configured and added
  245      * to the services' list now */
  246 
  247     *_svc = NULL;
  248 
  249     if (check_service(discard_const(svc_name)) != NULL) {
  250         DEBUG(SSSDBG_FATAL_FAILURE, "Invalid service %s\n", svc_name);
  251         return EINVAL;
  252     }
  253 
  254     mt_ctx->num_services++;
  255 
  256     ret = get_service_config(mt_ctx, svc_name, &svc);
  257     if (ret != EOK) {
  258         DEBUG(SSSDBG_FATAL_FAILURE,
  259               "Unable to get the configuration for the service: %s\n",
  260               svc_name);
  261         return ret;
  262     }
  263     svc->restarts = 0;
  264     svc->socket_activated = true;
  265 
  266     DLIST_ADD(mt_ctx->svc_list, svc);
  267 
  268     *_svc = svc;
  269     return EOK;
  270 }
  271 #endif
  272 
  273 static errno_t
  274 get_service_in_the_list(struct mt_ctx *mt_ctx,
  275                         const char *svc_name,
  276                         bool is_provider,
  277                         struct mt_svc **_svc)
  278 {
  279     struct mt_svc *svc;
  280 
  281     for (svc = mt_ctx->svc_list; svc != NULL; svc = svc->next) {
  282         if (strcasecmp(svc->identity, svc_name) == 0) {
  283             svc->socket_activated = false;
  284             *_svc = svc;
  285             return EOK;
  286         }
  287     }
  288 
  289 #ifdef HAVE_SYSTEMD
  290     return socket_activated_service_not_found(mt_ctx, svc_name, is_provider,
  291                                               _svc);
  292 #else
  293     return service_not_found(svc_name, _svc);
  294 #endif
  295 }
  296 
  297 static errno_t
  298 monitor_sbus_RegisterService(TALLOC_CTX *mem_ctx,
  299                              struct sbus_request *sbus_req,
  300                              struct mt_ctx *mt_ctx,
  301                              const char *name,
  302                              uint16_t version,
  303                              uint16_t type,
  304                              uint16_t *_monitor_version)
  305 {
  306     struct mt_svc *svc;
  307     errno_t ret;
  308 
  309     DEBUG(SSSDBG_CONF_SETTINGS,
  310           "Received ID registration: (%s,%d)\n", name, version);
  311 
  312     /* search this service in the list */
  313     ret = get_service_in_the_list(mt_ctx, name, type == MT_SVC_PROVIDER, &svc);
  314     if (ret != EOK) {
  315         return ERR_SBUS_KILL_CONNECTION;
  316     }
  317 
  318     svc->busname = talloc_strdup(svc, sbus_req->sender->name);
  319     if (svc->busname == NULL) {
  320         return ERR_SBUS_KILL_CONNECTION;
  321     }
  322 
  323     /* Fill in svc structure with connection data */
  324     svc->conn = sbus_req->conn;
  325 
  326     /* For {dbus,socket}-activated services we will have to unregister then
  327      * when the sbus_connection is freed. That's the reason we have to
  328      * hook up on its destructor function, do the service unregistration
  329      * from there and set the destructor back to NULL just before freeing
  330      * the service itself. */
  331     if (svc->socket_activated) {
  332         sbus_connection_set_destructor(svc->conn, monitor_service_shutdown, svc);
  333     }
  334 
  335     ret = mark_service_as_started(svc);
  336     if (ret) {
  337         DEBUG(SSSDBG_CRIT_FAILURE, "Failed to mark service [%s]!\n", name);
  338         return ret;
  339     }
  340 
  341     *_monitor_version = MONITOR_VERSION;
  342 
  343     return EOK;
  344 }
  345 
  346 struct svc_spy {
  347     struct mt_svc *svc;
  348 };
  349 
  350 static int svc_destructor(void *mem)
  351 {
  352     struct mt_svc *svc = talloc_get_type(mem, struct mt_svc);
  353     if (!svc) {
  354         /* ?!?!? */
  355         return 0;
  356     }
  357 
  358     /* try to delist service */
  359     if (svc->mt_ctx) {
  360         DLIST_REMOVE(svc->mt_ctx->svc_list, svc);
  361     }
  362 
  363     /* svc is being freed, neutralize the spy */
  364     if (svc->conn_spy) {
  365         talloc_set_destructor((TALLOC_CTX *)svc->conn_spy, NULL);
  366         talloc_zfree(svc->conn_spy);
  367     }
  368 
  369     if (svc->type == MT_SVC_SERVICE && svc->svc_started
  370             && svc->mt_ctx != NULL && svc->mt_ctx->started_services > 0) {
  371         svc->mt_ctx->started_services--;
  372     }
  373 
  374     return 0;
  375 }
  376 
  377 static int svc_spy_destructor(void *mem)
  378 {
  379     struct svc_spy *spy = talloc_get_type(mem, struct svc_spy);
  380     if (!spy) {
  381         /* ?!?!? */
  382         return 0;
  383     }
  384 
  385     /* svc->conn has been freed, NULL the pointer in svc */
  386     spy->svc->conn_spy = NULL;
  387     spy->svc->conn = NULL;
  388     return 0;
  389 }
  390 
  391 static int add_svc_conn_spy(struct mt_svc *svc)
  392 {
  393     struct svc_spy *spy;
  394 
  395     spy = talloc(svc->conn, struct svc_spy);
  396     if (!spy) return ENOMEM;
  397 
  398     spy->svc = svc;
  399     talloc_set_destructor((TALLOC_CTX *)spy, svc_spy_destructor);
  400     svc->conn_spy = spy;
  401 
  402     return EOK;
  403 }
  404 
  405 
  406 static void svc_child_info(struct mt_svc *svc, int wait_status)
  407 {
  408     int exit_code = 0;
  409     int pid = svc->pid;
  410     const char *name = (svc->name ? svc->name : "");
  411     const char *identity = (svc->identity ? svc->identity : "");
  412 
  413     if (WIFEXITED(wait_status)) {
  414         exit_code = WEXITSTATUS(wait_status);
  415         if (exit_code == SSS_WATCHDOG_EXIT_CODE) {
  416             DEBUG(SSSDBG_CRIT_FAILURE,
  417                   "Child [%d] ('%s':'%s') was terminated by own WATCHDOG\n",
  418                   pid, name, identity);
  419             sss_log(SSS_LOG_CRIT,
  420                     "Child [%d] ('%s':'%s') was terminated by own WATCHDOG. "
  421                     "Consult corresponding logs to figure out the reason.",
  422                     pid, name, identity);
  423         } else {
  424             DEBUG(SSSDBG_OP_FAILURE,
  425                   "Child [%d] ('%s':'%s') exited with code [%d]\n",
  426                    pid, name, identity, exit_code);
  427         }
  428     } else if (WIFSIGNALED(wait_status)) {
  429         DEBUG(SSSDBG_OP_FAILURE,
  430               "Child [%d] ('%s':'%s') terminated with signal [%d]\n",
  431                pid, name, identity, WTERMSIG(wait_status));
  432     } else {
  433         DEBUG(SSSDBG_FATAL_FAILURE,
  434               "Child [%d] ('%s':'%s') did not exit cleanly\n",
  435               pid, name, identity);
  436         /* Forcibly kill this child, just in case */
  437         kill(svc->pid, SIGKILL);
  438 
  439         /* Let us get caught by another
  440          * call to the SIGCHLD handler
  441          */
  442     }
  443 }
  444 
  445 static int notify_startup(void)
  446 {
  447 #ifdef HAVE_SYSTEMD
  448     int ret;
  449 
  450     DEBUG(SSSDBG_TRACE_FUNC, "Sending startup notification to systemd\n");
  451     ret = sd_notify(0, "READY=1");
  452     if (ret < 0) {
  453         ret = -ret;
  454         DEBUG(SSSDBG_CRIT_FAILURE,
  455                 "Error sending notification to systemd %d: %s\n",
  456                 ret, sss_strerror(ret));
  457 
  458        return ret;
  459     }
  460 #endif
  461 
  462     return EOK;
  463 }
  464 
  465 static int mark_service_as_started(struct mt_svc *svc)
  466 {
  467     struct mt_ctx *ctx = svc->mt_ctx;
  468     struct mt_svc *iter;
  469     int ret;
  470     int i;
  471 
  472     DEBUG(SSSDBG_FUNC_DATA, "Marking %s as started.\n", svc->name);
  473     svc->svc_started = true;
  474 
  475     /* We need to attach a spy to the connection structure so that if some code
  476      * frees it we can zero it out in the service structure. Otherwise we may
  477      * try to access or even free, freed memory. */
  478     ret = add_svc_conn_spy(svc);
  479     if (ret) {
  480         DEBUG(SSSDBG_FATAL_FAILURE, "Failed to attach spy\n");
  481         goto done;
  482     }
  483 
  484     if (!ctx->services_started) {
  485 
  486         /* check if all providers are up */
  487         for (iter = ctx->svc_list; iter; iter = iter->next) {
  488             if (iter->provider && !iter->svc_started) {
  489                 DEBUG(SSSDBG_FUNC_DATA,
  490                       "Still waiting on %s provider.\n", iter->name);
  491                 break;
  492             }
  493         }
  494 
  495         if (iter) {
  496             /* there are still unstarted providers */
  497             goto done;
  498         }
  499 
  500         if (ctx->services != NULL) {
  501             ctx->services_started = true;
  502 
  503             DEBUG(SSSDBG_CONF_SETTINGS, "Now starting services!\n");
  504             /* then start all services */
  505             for (i = 0; ctx->services[i]; i++) {
  506                 add_new_service(ctx, ctx->services[i], 0);
  507             }
  508         }
  509     }
  510 
  511     if (svc->type == MT_SVC_SERVICE) {
  512         ctx->started_services++;
  513     }
  514 
  515     /* create the pid file if all services are alive */
  516     if (!ctx->pid_file_created && ctx->started_services == ctx->num_services) {
  517         if (svc->socket_activated) {
  518             /* There's no reason for trying to terminate the parent process
  519              * when the responder was socket-activated. */
  520             goto done;
  521         }
  522 
  523         DEBUG(SSSDBG_TRACE_FUNC,
  524               "All services have successfully started, creating pid file\n");
  525         ret = pidfile(SSSD_PIDFILE);
  526         if (ret != EOK) {
  527             DEBUG(SSSDBG_FATAL_FAILURE,
  528                   "Error creating pidfile: %s! (%d [%s])\n",
  529                   SSSD_PIDFILE, ret, strerror(ret));
  530             kill(getpid(), SIGTERM);
  531         }
  532 
  533         ctx->pid_file_created = true;
  534 
  535         notify_startup();
  536 
  537         /* Initialization is complete, terminate parent process if in daemon
  538          * mode. Make sure we send the signal to the right process */
  539         if (ctx->is_daemon) {
  540             if (ctx->parent_pid <= 1 || ctx->parent_pid != getppid()) {
  541                 /* the parent process was already terminated */
  542                 DEBUG(SSSDBG_MINOR_FAILURE, "Invalid parent pid: %d\n",
  543                       ctx->parent_pid);
  544                 goto done;
  545             }
  546 
  547             DEBUG(SSSDBG_TRACE_FUNC, "SSSD is initialized, "
  548                                       "terminating parent process\n");
  549 
  550             errno = 0;
  551             ret = kill(ctx->parent_pid, SIGTERM);
  552             if (ret != 0) {
  553                 ret = errno;
  554                 DEBUG(SSSDBG_FATAL_FAILURE, "Unable to terminate parent "
  555                       "process [%d]: %s\n", ret, strerror(ret));
  556             }
  557         }
  558     }
  559 
  560 done:
  561     return ret;
  562 }
  563 
  564 static void services_startup_timeout(struct tevent_context *ev,
  565                                      struct tevent_timer *te,
  566                                      struct timeval t, void *ptr)
  567 {
  568     struct mt_ctx *ctx = talloc_get_type(ptr, struct mt_ctx);
  569     int i;
  570 
  571     if (ctx->services == NULL) {
  572         return;
  573     }
  574 
  575     DEBUG(SSSDBG_TRACE_FUNC, "Handling timeout\n");
  576 
  577     if (!ctx->services_started) {
  578 
  579         DEBUG(SSSDBG_CRIT_FAILURE, "Providers did not start in time, "
  580                   "forcing services startup!\n");
  581 
  582         ctx->services_started = true;
  583 
  584         DEBUG(SSSDBG_CONF_SETTINGS, "Now starting services!\n");
  585         /* then start all services */
  586         for (i = 0; ctx->services[i]; i++) {
  587             add_new_service(ctx, ctx->services[i], 0);
  588         }
  589     }
  590 }
  591 
  592 static int add_services_startup_timeout(struct mt_ctx *ctx)
  593 {
  594     struct tevent_timer *to;
  595     struct timeval tv;
  596 
  597     /* 5 seconds should be plenty */
  598     tv = tevent_timeval_current_ofs(5, 0);
  599     to = tevent_add_timer(ctx->ev, ctx, tv, services_startup_timeout, ctx);
  600     if (!to) {
  601         DEBUG(SSSDBG_FATAL_FAILURE,"Out of memory?!\n");
  602         return ENOMEM;
  603     }
  604 
  605     return EOK;
  606 }
  607 
  608 static void monitor_restart_service(struct mt_svc *svc);
  609 
  610 static int service_signal_dns_reload(struct mt_svc *svc);
  611 static int monitor_update_resolv(struct config_file_ctx *file_ctx,
  612                                  const char *filename)
  613 {
  614     int ret;
  615     struct mt_svc *cur_svc;
  616     struct mt_ctx *mt_ctx;
  617 
  618     mt_ctx = file_ctx->mt_ctx;
  619 
  620     DEBUG(SSSDBG_TRACE_LIBS, "Resolv.conf has been updated. Reloading.\n");
  621 
  622     ret = res_init();
  623     if (ret != 0) {
  624         return EIO;
  625     }
  626 
  627     /* Signal all services to reload their DNS configuration */
  628     for (cur_svc = mt_ctx->svc_list; cur_svc; cur_svc = cur_svc->next) {
  629         service_signal_dns_reload(cur_svc);
  630     }
  631     return EOK;
  632 }
  633 
  634 typedef struct tevent_req *
  635 (*service_signal_send_fn)(TALLOC_CTX *mem_ctx,
  636                           struct sbus_connection *conn,
  637                           const char *busname,
  638                           const char *object_path);
  639 
  640 typedef errno_t
  641 (*service_signal_recv_fn)(struct tevent_req *req);
  642 
  643 static void service_signal_done(struct tevent_req *req);
  644 
  645 static int service_signal(struct mt_svc *svc,
  646                           service_signal_send_fn send_fn,
  647                           service_signal_recv_fn recv_fn)
  648 {
  649     struct sbus_connection *conn;
  650     struct tevent_req *req;
  651 
  652     if (svc->provider
  653             && (local_provider_is_built()
  654                 && strcasecmp(svc->provider, "local") == 0)) {
  655         /* The local provider requires no signaling */
  656         return EOK;
  657     }
  658 
  659     conn = svc->mt_ctx->sbus_conn;
  660 
  661     if (!svc->conn) {
  662         /* Avoid a race condition where we are trying to
  663          * order a service to reload that hasn't started
  664          * yet.
  665          */
  666         DEBUG(SSSDBG_CRIT_FAILURE,
  667               "Could not signal service [%s].\n", svc->name);
  668         return EIO;
  669     }
  670 
  671     req = send_fn(svc, conn, svc->busname, SSS_BUS_PATH);
  672     if (req == NULL) {
  673         return ENOMEM;
  674     }
  675 
  676     tevent_req_set_callback(req, service_signal_done, recv_fn);
  677 
  678     return EOK;
  679 }
  680 
  681 static void service_signal_done(struct tevent_req *req)
  682 {
  683     service_signal_recv_fn recv_fn;
  684     errno_t ret;
  685 
  686     recv_fn = tevent_req_callback_data_void(req);
  687 
  688     ret = recv_fn(req);
  689     talloc_zfree(req);
  690 
  691     if (ret == EOK) {
  692         return;
  693     }
  694 
  695     DEBUG(SSSDBG_FATAL_FAILURE, "Unable to signal service [%d]: %s\n",
  696           ret, sss_strerror(ret));
  697 }
  698 
  699 static int service_signal_dns_reload(struct mt_svc *svc)
  700 {
  701     return service_signal(svc, sbus_call_service_resInit_send,
  702                           sbus_call_service_resInit_recv);
  703 }
  704 static int service_signal_offline(struct mt_svc *svc)
  705 {
  706     return service_signal(svc, sbus_call_service_goOffline_send,
  707                           sbus_call_service_goOffline_recv);
  708 }
  709 static int service_signal_reset_offline(struct mt_svc *svc)
  710 {
  711     return service_signal(svc, sbus_call_service_resetOffline_send,
  712                           sbus_call_service_resetOffline_recv);
  713 }
  714 static int service_signal_rotate(struct mt_svc *svc)
  715 {
  716     return service_signal(svc, sbus_call_service_rotateLogs_send,
  717                           sbus_call_service_rotateLogs_recv);
  718 }
  719 static int service_signal_clear_memcache(struct mt_svc *svc)
  720 {
  721     return service_signal(svc, sbus_call_service_clearMemcache_send,
  722                           sbus_call_service_clearMemcache_recv);
  723 }
  724 static int service_signal_clear_enum_cache(struct mt_svc *svc)
  725 {
  726     return service_signal(svc, sbus_call_service_clearEnumCache_send,
  727                           sbus_call_service_clearEnumCache_recv);
  728 }
  729 static int service_signal_sysbus_reconnect(struct mt_svc *svc)
  730 {
  731     return service_signal(svc, sbus_call_service_sysbusReconnect_send,
  732                           sbus_call_service_sysbusReconnect_recv);
  733 }
  734 
  735 static int check_domain_ranges(struct sss_domain_info *domains)
  736 {
  737     struct sss_domain_info *dom = domains, *other = NULL;
  738     uint32_t id_min, id_max;
  739 
  740     while (dom) {
  741         other = get_next_domain(dom, 0);
  742         if (dom->id_max && dom->id_min > dom->id_max) {
  743             DEBUG(SSSDBG_CRIT_FAILURE,
  744                   "Domain '%s' does not have a valid ID range\n", dom->name);
  745             return EINVAL;
  746         }
  747 
  748         while (other) {
  749             id_min = MAX(dom->id_min, other->id_min);
  750             id_max = MIN((dom->id_max ? dom->id_max : UINT32_MAX),
  751                          (other->id_max ? other->id_max : UINT32_MAX));
  752             if (id_min <= id_max) {
  753                 DEBUG(SSSDBG_MINOR_FAILURE,
  754                       "Domains '%s' and '%s' overlap in range %u - %u\n",
  755                       dom->name, other->name, id_min, id_max);
  756             }
  757             other = get_next_domain(other, 0);
  758         }
  759         dom = get_next_domain(dom, 0);
  760     }
  761 
  762     return EOK;
  763 }
  764 
  765 static int check_local_domain_unique(struct sss_domain_info *domains)
  766 {
  767     uint8_t count = 0;
  768 
  769     struct sss_domain_info *dom = domains;
  770 
  771     while (dom) {
  772         if (local_provider_is_built()
  773                 && strcasecmp(dom->provider, "local") == 0) {
  774             count++;
  775         }
  776 
  777         if (count > 1) {
  778             break;
  779         }
  780 
  781         dom = get_next_domain(dom, 0);
  782     }
  783 
  784     if (count > 1) {
  785         return EINVAL;
  786     }
  787 
  788     return EOK;
  789 }
  790 
  791 static errno_t add_implicit_services(struct confdb_ctx *cdb, TALLOC_CTX *mem_ctx,
  792                                      char ***_services)
  793 {
  794     int ret;
  795     char **domain_names;
  796     TALLOC_CTX *tmp_ctx;
  797     size_t c;
  798     char *conf_path;
  799     char *id_provider;
  800     bool add_pac = false;
  801 
  802     tmp_ctx = talloc_new(NULL);
  803     if (tmp_ctx == NULL) {
  804         DEBUG(SSSDBG_OP_FAILURE, "talloc_new failed.\n");
  805         return ENOMEM;
  806     }
  807 
  808     ret = confdb_get_string_as_list(cdb, tmp_ctx,
  809                                     CONFDB_MONITOR_CONF_ENTRY,
  810                                     CONFDB_MONITOR_ACTIVE_DOMAINS,
  811                                     &domain_names);
  812     if (ret == ENOENT) {
  813         DEBUG(SSSDBG_OP_FAILURE, "No domains configured!\n");
  814         goto done;
  815     }
  816 
  817     for (c = 0; domain_names[c] != NULL; c++) {
  818         if (!is_valid_domain_name(domain_names[c])) {
  819             DEBUG(SSSDBG_CRIT_FAILURE,
  820                   "Skipping invalid domain name '%s'\n", domain_names[c]);
  821             continue;
  822         }
  823         conf_path = talloc_asprintf(tmp_ctx, CONFDB_DOMAIN_PATH_TMPL,
  824                                     domain_names[c]);
  825         if (conf_path == NULL) {
  826             DEBUG(SSSDBG_OP_FAILURE, "talloc_asprintf failed.\n");
  827             ret = ENOMEM;
  828             goto done;
  829         }
  830 
  831         ret = confdb_get_string(cdb, tmp_ctx, conf_path,
  832                                 CONFDB_DOMAIN_ID_PROVIDER, NULL, &id_provider);
  833         if (ret == EOK) {
  834             if (id_provider == NULL) {
  835                 DEBUG(SSSDBG_OP_FAILURE, "id_provider is not set for "
  836                       "domain [%s], trying next domain.\n", domain_names[c]);
  837                 continue;
  838             }
  839 
  840             if (strcasecmp(id_provider, "IPA") == 0) {
  841                 add_pac = true;
  842             }
  843         } else {
  844             DEBUG(SSSDBG_OP_FAILURE, "Failed to get id_provider for " \
  845                                       "domain [%s], trying next domain.\n",
  846                                       domain_names[c]);
  847         }
  848     }
  849 
  850     if (BUILD_WITH_PAC_RESPONDER && add_pac &&
  851         !string_in_list("pac", *_services, false)) {
  852         ret = add_string_to_list(mem_ctx, "pac", _services);
  853         if (ret != EOK) {
  854             DEBUG(SSSDBG_OP_FAILURE, "add_string_to_list failed.\n");
  855             goto done;
  856         }
  857     }
  858 
  859     ret = EOK;
  860 
  861 done:
  862     talloc_free(tmp_ctx);
  863 
  864     return ret;
  865 }
  866 
  867 static char *check_service(char *service)
  868 {
  869     const char * const *known_services = get_known_services();
  870     int i;
  871 
  872     for (i = 0; known_services[i] != NULL; i++) {
  873         if (strcasecmp(service, known_services[i]) == 0) {
  874             break;
  875         }
  876     }
  877 
  878     if (known_services[i] == NULL) {
  879         return service;
  880     }
  881 
  882     return NULL;
  883 }
  884 
  885 static char *check_services(char **services)
  886 {
  887     if (services == NULL) {
  888         return NULL;
  889     }
  890 
  891     /* Check if services we are about to start are in the list if known */
  892     for (int i = 0; services[i]; i++) {
  893         if (check_service(services[i]) != NULL) {
  894             return services[i];
  895         }
  896     }
  897 
  898     return NULL;
  899 }
  900 
  901 static int get_service_user(struct mt_ctx *ctx)
  902 {
  903     errno_t ret;
  904     char *user_str;
  905 
  906     ret = confdb_get_string(ctx->cdb, ctx, CONFDB_MONITOR_CONF_ENTRY,
  907                             CONFDB_MONITOR_USER_RUNAS,
  908                             "root", &user_str);
  909     if (ret != EOK) {
  910         DEBUG(SSSDBG_FATAL_FAILURE, "Failed to get the user to run as\n");
  911         return ret;
  912     }
  913 
  914     ret = sss_user_by_name_or_uid(user_str, &ctx->uid, &ctx->gid);
  915     talloc_free(user_str);
  916     if (ret != EOK) {
  917         DEBUG(SSSDBG_FATAL_FAILURE, "Failed to set allowed UIDs.\n");
  918         return ret;
  919     }
  920 
  921     return EOK;
  922 }
  923 
  924 static int get_monitor_config(struct mt_ctx *ctx)
  925 {
  926     int ret;
  927     int timeout_seconds;
  928     char *badsrv = NULL;
  929     int i;
  930 
  931     ret = confdb_get_int(ctx->cdb,
  932                          CONFDB_MONITOR_CONF_ENTRY,
  933                          CONFDB_MONITOR_SBUS_TIMEOUT,
  934                          10, &timeout_seconds);
  935     if (ret != EOK) {
  936         return ret;
  937     }
  938 
  939     ctx->service_id_timeout = timeout_seconds * 1000; /* service_id_timeout is in ms */
  940 
  941     ret = confdb_get_string_as_list(ctx->cdb, ctx,
  942                                     CONFDB_MONITOR_CONF_ENTRY,
  943                                     CONFDB_MONITOR_ACTIVE_SERVICES,
  944                                     &ctx->services);
  945 
  946 #ifdef HAVE_SYSTEMD
  947     if (ret != EOK && ret != ENOENT) {
  948         DEBUG(SSSDBG_FATAL_FAILURE,
  949               "Failed to get the explicitly configured services!\n");
  950         return EINVAL;
  951     }
  952 #else
  953     if (ret != EOK) {
  954         DEBUG(SSSDBG_FATAL_FAILURE, "No services configured!\n");
  955         return EINVAL;
  956     }
  957 #endif
  958 
  959     ret = add_implicit_services(ctx->cdb, ctx, &ctx->services);
  960     if (ret != EOK) {
  961         DEBUG(SSSDBG_OP_FAILURE, "Failed to add implicit configured "
  962                                  "services. Some functionality might "
  963                                  "be missing\n");
  964     }
  965 
  966     badsrv = check_services(ctx->services);
  967     if (badsrv != NULL) {
  968         DEBUG(SSSDBG_FATAL_FAILURE, "Invalid service %s\n", badsrv);
  969         return EINVAL;
  970     }
  971 
  972     ctx->started_services = 0;
  973     ctx->num_services = 0;
  974 
  975     if (ctx->services != NULL) {
  976         for (i = 0; ctx->services[i] != NULL; i++) {
  977             ctx->num_services++;
  978         }
  979     }
  980 
  981     ret = get_service_user(ctx);
  982     if (ret != EOK) {
  983         DEBUG(SSSDBG_CRIT_FAILURE, "Failed to get the unprivileged user\n");
  984         return ret;
  985     }
  986 
  987     ret = confdb_expand_app_domains(ctx->cdb);
  988     if (ret != EOK) {
  989         DEBUG(SSSDBG_FATAL_FAILURE, "Failed to expand application domains\n");
  990         /* This must not be fatal so that SSSD keeps running and lets
  991          * admin correct the error.
  992          */
  993     }
  994 
  995     ret = confdb_get_domains(ctx->cdb, &ctx->domains);
  996     if (ret != EOK) {
  997         DEBUG(SSSDBG_FATAL_FAILURE, "No domains configured.\n");
  998         return ret;
  999     }
 1000 
 1001     ret = check_local_domain_unique(ctx->domains);
 1002     if (ret != EOK) {
 1003         DEBUG(SSSDBG_FATAL_FAILURE, "More than one local domain configured.\n");
 1004         return ret;
 1005     }
 1006 
 1007     /* Check UID/GID overlaps */
 1008     ret = check_domain_ranges(ctx->domains);
 1009     if (ret != EOK) {
 1010         return ret;
 1011     }
 1012 
 1013     return EOK;
 1014 }
 1015 
 1016 /* This is a temporary function that returns false if the service
 1017  * being started was only tested when running as root.
 1018  */
 1019 static bool svc_supported_as_nonroot(const char *svc_name)
 1020 {
 1021     if ((strcmp(svc_name, "nss") == 0)
 1022         || (strcmp(svc_name, "pam") == 0)
 1023         || (strcmp(svc_name, "autofs") == 0)
 1024         || (strcmp(svc_name, "pac") == 0)
 1025         || (strcmp(svc_name, "sudo") == 0)
 1026         || (strcmp(svc_name, "ssh") == 0)) {
 1027         return true;
 1028     }
 1029     return false;
 1030 }
 1031 
 1032 static int get_service_config(struct mt_ctx *ctx, const char *name,
 1033                               struct mt_svc **svc_cfg)
 1034 {
 1035     int ret;
 1036     char *path;
 1037     struct mt_svc *svc;
 1038     time_t now = time(NULL);
 1039     uid_t uid = 0;
 1040     gid_t gid = 0;
 1041 
 1042     *svc_cfg = NULL;
 1043 
 1044     svc = talloc_zero(ctx, struct mt_svc);
 1045     if (!svc) {
 1046         return ENOMEM;
 1047     }
 1048     svc->mt_ctx = ctx;
 1049     svc->type = MT_SVC_SERVICE;
 1050 
 1051     talloc_set_destructor((TALLOC_CTX *)svc, svc_destructor);
 1052 
 1053     svc->name = talloc_strdup(svc, name);
 1054     if (!svc->name) {
 1055         talloc_free(svc);
 1056         return ENOMEM;
 1057     }
 1058 
 1059     svc->identity = talloc_strdup(svc, name);
 1060     if (!svc->identity) {
 1061         talloc_free(svc);
 1062         return ENOMEM;
 1063     }
 1064 
 1065     path = talloc_asprintf(svc, CONFDB_SERVICE_PATH_TMPL, svc->name);
 1066     if (!path) {
 1067         talloc_free(svc);
 1068         return ENOMEM;
 1069     }
 1070 
 1071     ret = confdb_get_string(ctx->cdb, svc, path,
 1072                             CONFDB_SERVICE_COMMAND,
 1073                             NULL, &svc->command);
 1074     if (ret != EOK) {
 1075         DEBUG(SSSDBG_FATAL_FAILURE,"Failed to start service '%s'\n", svc->name);
 1076         talloc_free(svc);
 1077         return ret;
 1078     }
 1079 
 1080     if (svc_supported_as_nonroot(svc->name)) {
 1081         uid = ctx->uid;
 1082         gid = ctx->gid;
 1083     }
 1084 
 1085     if (!svc->command) {
 1086         svc->command = talloc_asprintf(
 1087             svc, "%s/sssd_%s", SSSD_LIBEXEC_PATH, svc->name
 1088         );
 1089         if (!svc->command) {
 1090             talloc_free(svc);
 1091             return ENOMEM;
 1092         }
 1093 
 1094         svc->command = talloc_asprintf_append(svc->command,
 1095                 " --uid %"SPRIuid" --gid %"SPRIgid,
 1096                 uid, gid);
 1097         if (!svc->command) {
 1098             talloc_free(svc);
 1099             return ENOMEM;
 1100         }
 1101 
 1102         if (cmdline_debug_level != SSSDBG_UNRESOLVED) {
 1103             svc->command = talloc_asprintf_append(
 1104                 svc->command, " -d %#.4x", cmdline_debug_level
 1105             );
 1106             if (!svc->command) {
 1107                 talloc_free(svc);
 1108                 return ENOMEM;
 1109             }
 1110         }
 1111 
 1112         if (cmdline_debug_timestamps != SSSDBG_TIMESTAMP_UNRESOLVED) {
 1113             svc->command = talloc_asprintf_append(
 1114                 svc->command, " --debug-timestamps=%d", cmdline_debug_timestamps
 1115             );
 1116             if (!svc->command) {
 1117                 talloc_free(svc);
 1118                 return ENOMEM;
 1119             }
 1120         }
 1121 
 1122         if (cmdline_debug_microseconds != SSSDBG_MICROSECONDS_UNRESOLVED) {
 1123             svc->command = talloc_asprintf_append(
 1124                 svc->command, " --debug-microseconds=%d",
 1125                 cmdline_debug_microseconds
 1126             );
 1127             if (!svc->command) {
 1128                 talloc_free(svc);
 1129                 return ENOMEM;
 1130             }
 1131         }
 1132 
 1133         svc->command = talloc_asprintf_append(
 1134             svc->command, " --logger=%s", sss_logger_str[sss_logger]);
 1135         if (!svc->command) {
 1136             talloc_free(svc);
 1137             return ENOMEM;
 1138         }
 1139     }
 1140 
 1141     svc->last_restart = now;
 1142 
 1143     *svc_cfg = svc;
 1144     talloc_free(path);
 1145 
 1146     return EOK;
 1147 }
 1148 
 1149 static int add_new_service(struct mt_ctx *ctx,
 1150                            const char *name,
 1151                            int restarts)
 1152 {
 1153     int ret;
 1154     struct mt_svc *svc;
 1155 
 1156     ret = get_service_config(ctx, name, &svc);
 1157     if (ret != EOK) {
 1158         return ret;
 1159     }
 1160     svc->restarts = restarts;
 1161 
 1162     ret = start_service(svc);
 1163     if (ret != EOK) {
 1164         DEBUG(SSSDBG_FATAL_FAILURE,"Failed to start service '%s'\n", svc->name);
 1165         talloc_free(svc);
 1166     }
 1167 
 1168     return ret;
 1169 }
 1170 
 1171 static int get_provider_config(struct mt_ctx *ctx, const char *name,
 1172                               struct mt_svc **svc_cfg)
 1173 {
 1174     int ret;
 1175     char *path;
 1176     struct mt_svc *svc;
 1177     time_t now = time(NULL);
 1178 
 1179     *svc_cfg = NULL;
 1180 
 1181     svc = talloc_zero(ctx, struct mt_svc);
 1182     if (!svc) {
 1183         return ENOMEM;
 1184     }
 1185     svc->mt_ctx = ctx;
 1186     svc->type = MT_SVC_PROVIDER;
 1187 
 1188     talloc_set_destructor((TALLOC_CTX *)svc, svc_destructor);
 1189 
 1190     svc->name = talloc_strdup(svc, name);
 1191     if (!svc->name) {
 1192         talloc_free(svc);
 1193         return ENOMEM;
 1194     }
 1195 
 1196     svc->identity = talloc_asprintf(svc, "%%BE_%s", svc->name);
 1197     if (!svc->identity) {
 1198         talloc_free(svc);
 1199         return ENOMEM;
 1200     }
 1201 
 1202     path = talloc_asprintf(svc, CONFDB_DOMAIN_PATH_TMPL, name);
 1203     if (!path) {
 1204         talloc_free(svc);
 1205         return ENOMEM;
 1206     }
 1207 
 1208     ret = confdb_get_string(ctx->cdb, svc, path,
 1209                             CONFDB_DOMAIN_ID_PROVIDER,
 1210                             NULL, &svc->provider);
 1211     if (ret != EOK) {
 1212         DEBUG(SSSDBG_FATAL_FAILURE,
 1213               "Failed to find ID provider from [%s] configuration\n", name);
 1214         talloc_free(svc);
 1215         return ret;
 1216     }
 1217 
 1218     ret = confdb_get_string(ctx->cdb, svc, path,
 1219                             CONFDB_DOMAIN_COMMAND,
 1220                             NULL, &svc->command);
 1221     if (ret != EOK) {
 1222         DEBUG(SSSDBG_FATAL_FAILURE,
 1223               "Failed to find command from [%s] configuration\n", name);
 1224         talloc_free(svc);
 1225         return ret;
 1226     }
 1227 
 1228     talloc_free(path);
 1229 
 1230     /* if no provider is present do not run the domain */
 1231     if (!svc->provider) {
 1232         talloc_free(svc);
 1233         return EIO;
 1234     }
 1235 
 1236     /* if there are no custom commands, build a default one */
 1237     if (!svc->command) {
 1238         svc->command = talloc_asprintf(
 1239             svc, "%s/sssd_be --domain %s", SSSD_LIBEXEC_PATH, svc->name
 1240         );
 1241         if (!svc->command) {
 1242             talloc_free(svc);
 1243             return ENOMEM;
 1244         }
 1245 
 1246         svc->command = talloc_asprintf_append(svc->command,
 1247                 " --uid %"SPRIuid" --gid %"SPRIgid,
 1248                 ctx->uid, ctx->gid);
 1249         if (!svc->command) {
 1250             talloc_free(svc);
 1251             return ENOMEM;
 1252         }
 1253 
 1254         if (cmdline_debug_level != SSSDBG_UNRESOLVED) {
 1255             svc->command = talloc_asprintf_append(
 1256                 svc->command, " -d %#.4x", cmdline_debug_level
 1257             );
 1258             if (!svc->command) {
 1259                 talloc_free(svc);
 1260                 return ENOMEM;
 1261             }
 1262         }
 1263 
 1264         if (cmdline_debug_timestamps != SSSDBG_TIMESTAMP_UNRESOLVED) {
 1265             svc->command = talloc_asprintf_append(
 1266                 svc->command, " --debug-timestamps=%d", cmdline_debug_timestamps
 1267             );
 1268             if (!svc->command) {
 1269                 talloc_free(svc);
 1270                 return ENOMEM;
 1271             }
 1272         }
 1273 
 1274         if (cmdline_debug_microseconds != SSSDBG_MICROSECONDS_UNRESOLVED) {
 1275             svc->command = talloc_asprintf_append(
 1276                 svc->command, " --debug-microseconds=%d",
 1277                 cmdline_debug_microseconds
 1278             );
 1279             if (!svc->command) {
 1280                 talloc_free(svc);
 1281                 return ENOMEM;
 1282             }
 1283         }
 1284 
 1285         svc->command = talloc_asprintf_append(
 1286             svc->command, " --logger=%s", sss_logger_str[sss_logger]);
 1287         if (!svc->command) {
 1288             talloc_free(svc);
 1289             return ENOMEM;
 1290         }
 1291     }
 1292 
 1293     svc->last_restart = now;
 1294 
 1295     *svc_cfg = svc;
 1296     return EOK;
 1297 }
 1298 
 1299 static int add_new_provider(struct mt_ctx *ctx,
 1300                             const char *name,
 1301                             int restarts)
 1302 {
 1303     int ret;
 1304     struct mt_svc *svc;
 1305 
 1306     ret = get_provider_config(ctx, name, &svc);
 1307     if (ret != EOK) {
 1308         DEBUG(SSSDBG_FATAL_FAILURE,
 1309               "Could not get provider configuration for [%s]\n",
 1310                   name);
 1311         return ret;
 1312     }
 1313     svc->restarts = restarts;
 1314 
 1315     if (local_provider_is_built()
 1316             && strcasecmp(svc->provider, "local") == 0) {
 1317         /* The LOCAL provider requires no back-end currently
 1318          * We'll add it to the service list, but we don't need
 1319          * to poll it.
 1320          */
 1321         svc->svc_started = true;
 1322         DLIST_ADD(ctx->svc_list, svc);
 1323         return ENOENT;
 1324     }
 1325 
 1326     ret = start_service(svc);
 1327     if (ret != EOK) {
 1328         DEBUG(SSSDBG_FATAL_FAILURE,"Failed to start service '%s'\n", svc->name);
 1329         talloc_free(svc);
 1330     }
 1331 
 1332     return ret;
 1333 }
 1334 
 1335 static void monitor_hup(struct tevent_context *ev,
 1336                         struct tevent_signal *se,
 1337                         int signum,
 1338                         int count,
 1339                         void *siginfo,
 1340                         void *private_data)
 1341 {
 1342     struct mt_ctx *ctx = talloc_get_type(private_data, struct mt_ctx);
 1343     struct mt_svc *cur_svc;
 1344 
 1345     DEBUG(SSSDBG_CRIT_FAILURE, "Received SIGHUP.\n");
 1346 
 1347     /* Send D-Bus message to other services to rotate their logs.
 1348      * NSS service receives also message to clear memory caches. */
 1349     for(cur_svc = ctx->svc_list; cur_svc; cur_svc = cur_svc->next) {
 1350         service_signal_rotate(cur_svc);
 1351         if (!strcmp(NSS_SBUS_SERVICE_NAME, cur_svc->name)) {
 1352             service_signal_clear_memcache(cur_svc);
 1353             service_signal_clear_enum_cache(cur_svc);
 1354         }
 1355 
 1356         if (!strcmp(SSS_AUTOFS_SBUS_SERVICE_NAME, cur_svc->name)) {
 1357             service_signal_clear_enum_cache(cur_svc);
 1358         }
 1359 
 1360     }
 1361 
 1362 }
 1363 
 1364 static int monitor_cleanup(void)
 1365 {
 1366     int ret;
 1367 
 1368     errno = 0;
 1369     ret = unlink(SSSD_PIDFILE);
 1370     if (ret == -1) {
 1371         ret = errno;
 1372         DEBUG(SSSDBG_FATAL_FAILURE,
 1373               "Error removing pidfile! (%d [%s])\n", ret, strerror(ret));
 1374         return ret;
 1375     }
 1376 
 1377     return EOK;
 1378 }
 1379 
 1380 static void monitor_quit(struct mt_ctx *mt_ctx, int ret)
 1381 {
 1382     struct mt_svc *svc;
 1383     pid_t pid;
 1384     int status;
 1385     errno_t error;
 1386     int kret;
 1387     bool killed;
 1388 
 1389     DEBUG(SSSDBG_IMPORTANT_INFO, "Returned with: %d\n", ret);
 1390 
 1391     /* Kill all of our known children manually */
 1392     DLIST_FOR_EACH(svc, mt_ctx->svc_list) {
 1393         if (svc->socket_activated && svc->conn != NULL) {
 1394             /* Unset the sbus_connection destructor used to
 1395              * unregister the service from the monitor as
 1396              * it may lead to a double-free here. */
 1397             talloc_set_destructor(svc->conn, NULL);
 1398         }
 1399 
 1400         if (svc->pid == 0) {
 1401             /* The local provider has no PID */
 1402             continue;
 1403         }
 1404 
 1405         killed = false;
 1406         DEBUG(SSSDBG_CRIT_FAILURE,
 1407               "Terminating [%s][%d]\n", svc->name, svc->pid);
 1408         do {
 1409             errno = 0;
 1410             kret = kill(-svc->pid, SIGTERM);
 1411             if (kret < 0) {
 1412                 error = errno;
 1413                 DEBUG(SSSDBG_CRIT_FAILURE, "Couldn't kill [%s][%d]: [%s]\n",
 1414                           svc->name, svc->pid, strerror(error));
 1415             }
 1416 
 1417             error = 0;
 1418             do {
 1419                 errno = 0;
 1420                 pid = waitpid(svc->pid, &status, WNOHANG);
 1421                 if (pid == -1) {
 1422                     /* An error occurred while waiting */
 1423                     error = errno;
 1424                     if (error == ECHILD) {
 1425                         killed = true;
 1426                     } else if (error != EINTR) {
 1427                         DEBUG(SSSDBG_FATAL_FAILURE,
 1428                               "[%d][%s] while waiting for [%s]\n",
 1429                                   error, strerror(error), svc->name);
 1430                         /* Forcibly kill this child */
 1431                         kill(-svc->pid, SIGKILL);
 1432                         break;
 1433                     }
 1434                 } else if (pid != 0) {
 1435                     error = 0;
 1436                     if (WIFEXITED(status)) {
 1437                         DEBUG(SSSDBG_CRIT_FAILURE,
 1438                               "Child [%s] exited gracefully\n", svc->name);
 1439                     } else if (WIFSIGNALED(status)) {
 1440                         DEBUG(SSSDBG_CRIT_FAILURE,
 1441                               "Child [%s] terminated with a signal\n", svc->name);
 1442                     } else {
 1443                         DEBUG(SSSDBG_CRIT_FAILURE,
 1444                               "Child [%s] did not exit cleanly\n", svc->name);
 1445                         /* Forcibly kill this child */
 1446                         kill(-svc->pid, SIGKILL);
 1447                     }
 1448                     killed = true;
 1449                 }
 1450             } while (error == EINTR);
 1451             if (!killed) {
 1452                 /* Sleep 10ms and try again */
 1453                 usleep(10000);
 1454             }
 1455         } while (!killed);
 1456     }
 1457 
 1458 #if HAVE_GETPGRP
 1459     /* Kill any remaining children in our process group, just in case
 1460      * we have any leftover children we don't expect. For example, if
 1461      * a krb5_child or ldap_child is running at the same moment.
 1462      */
 1463     error = 0;
 1464     if (getpgrp() == getpid()) {
 1465         kill(-getpgrp(), SIGTERM);
 1466         do {
 1467             errno = 0;
 1468             pid = waitpid(0, &status, 0);
 1469             if (pid == -1) {
 1470                 error = errno;
 1471             }
 1472         } while (error == EINTR || pid > 0);
 1473     }
 1474 #endif
 1475 
 1476     monitor_cleanup();
 1477 
 1478     exit(ret);
 1479 }
 1480 
 1481 static void monitor_quit_signal(struct tevent_context *ev,
 1482                                 struct tevent_signal *se,
 1483                                 int signum,
 1484                                 int count,
 1485                                 void *siginfo,
 1486                                 void *private_data)
 1487 {
 1488     struct mt_ctx *mt_ctx = talloc_get_type(private_data, struct mt_ctx);
 1489 
 1490     DEBUG(SSSDBG_TRACE_INTERNAL, "Received shutdown command\n");
 1491 
 1492     DEBUG(SSSDBG_IMPORTANT_INFO, "Monitor received %s: terminating "
 1493                                   "children\n", strsignal(signum));
 1494 
 1495     monitor_quit(mt_ctx, 0);
 1496 }
 1497 
 1498 static void signal_res_init(struct mt_ctx *monitor)
 1499 {
 1500     struct mt_svc *cur_svc;
 1501     int ret;
 1502     DEBUG(SSSDBG_OP_FAILURE, "Reloading Resolv.conf.\n");
 1503 
 1504     ret = res_init();
 1505     if (ret == 0) {
 1506         for(cur_svc = monitor->svc_list; cur_svc; cur_svc = cur_svc->next) {
 1507             service_signal_dns_reload(cur_svc);
 1508         }
 1509     }
 1510 }
 1511 
 1512 static void signal_offline(struct tevent_context *ev,
 1513                            struct tevent_signal *se,
 1514                            int signum,
 1515                            int count,
 1516                            void *siginfo,
 1517                            void *private_data)
 1518 {
 1519     struct mt_ctx *monitor;
 1520     struct mt_svc *cur_svc;
 1521 
 1522     monitor = talloc_get_type(private_data, struct mt_ctx);
 1523 
 1524     DEBUG(SSSDBG_TRACE_INTERNAL,
 1525          "Signaling providers to go offline immediately.\n");
 1526 
 1527     /* Signal all providers to immediately go offline */
 1528     for(cur_svc = monitor->svc_list; cur_svc; cur_svc = cur_svc->next) {
 1529         /* Don't signal services, only providers */
 1530         if (cur_svc->provider) {
 1531             service_signal_offline(cur_svc);
 1532         }
 1533     }
 1534 }
 1535 
 1536 static void signal_offline_reset(struct tevent_context *ev,
 1537                                  struct tevent_signal *se,
 1538                                  int signum,
 1539                                  int count,
 1540                                  void *siginfo,
 1541                                  void *private_data)
 1542 {
 1543     struct mt_ctx *monitor;
 1544     struct mt_svc *cur_svc;
 1545 
 1546     monitor = talloc_get_type(private_data, struct mt_ctx);
 1547 
 1548     DEBUG(SSSDBG_TRACE_INTERNAL,
 1549          "Signaling providers to reset offline immediately.\n");
 1550 
 1551     for(cur_svc = monitor->svc_list; cur_svc; cur_svc = cur_svc->next) {
 1552         if (cur_svc->provider) {
 1553             service_signal_reset_offline(cur_svc);
 1554         }
 1555 
 1556         if (strcmp(SSS_IFP_SBUS_SERVICE_NAME, cur_svc->name) == 0) {
 1557             service_signal_sysbus_reconnect(cur_svc);
 1558         }
 1559     }
 1560     signal_res_init(monitor);
 1561 }
 1562 
 1563 static int monitor_ctx_destructor(void *mem)
 1564 {
 1565     struct mt_ctx *mon = talloc_get_type(mem, struct mt_ctx);
 1566     struct mt_svc *svc;
 1567 
 1568     /* zero out references in SVCs so that they don't try
 1569      * to access the monitor context on process shutdown */
 1570 
 1571     for (svc = mon->svc_list; svc; svc = svc->next) {
 1572         svc->mt_ctx = NULL;
 1573     }
 1574     return 0;
 1575 }
 1576 
 1577 /*
 1578  * This function should not be static otherwise gcc does some special kind of
 1579  * optimisations which should not happen according to code: chown (unlink)
 1580  * failed (return -1) but errno was zero.
 1581  * As a result of this * warning is printed ‘monitor’ may be used
 1582  * uninitialized in this function. Instead of checking errno for 0
 1583  * it's better to disable optimisation (in-lining) of this function.
 1584  */
 1585 errno_t load_configuration(TALLOC_CTX *mem_ctx,
 1586                            const char *config_file,
 1587                            const char *config_dir,
 1588                            const char *only_section,
 1589                            struct mt_ctx **monitor)
 1590 {
 1591     errno_t ret;
 1592     struct mt_ctx *ctx;
 1593     char *cdb_file = NULL;
 1594 
 1595     ctx = talloc_zero(mem_ctx, struct mt_ctx);
 1596     if(!ctx) {
 1597         return ENOMEM;
 1598     }
 1599 
 1600     ctx->pid_file_created = false;
 1601     talloc_set_destructor((TALLOC_CTX *)ctx, monitor_ctx_destructor);
 1602 
 1603     cdb_file = talloc_asprintf(ctx, "%s/%s", DB_PATH, CONFDB_FILE);
 1604     if (cdb_file == NULL) {
 1605         DEBUG(SSSDBG_FATAL_FAILURE,"Out of memory, aborting!\n");
 1606         ret = ENOMEM;
 1607         goto done;
 1608     }
 1609 
 1610     ret = confdb_setup(ctx, cdb_file, config_file, config_dir, only_section,
 1611                        &ctx->cdb);
 1612     if (ret != EOK) {
 1613         DEBUG(SSSDBG_FATAL_FAILURE, "Unable to setup ConfDB [%d]: %s\n",
 1614              ret, sss_strerror(ret));
 1615         goto done;
 1616     }
 1617 
 1618     /* Validate the configuration in the database */
 1619     /* Read in the monitor's configuration */
 1620     ret = get_monitor_config(ctx);
 1621     if (ret != EOK) {
 1622         goto done;
 1623     }
 1624 
 1625     /* Allow configuration database to be accessible
 1626      * when SSSD runs as nonroot */
 1627     ret = chown(cdb_file, ctx->uid, ctx->gid);
 1628     if (ret != 0) {
 1629         ret = errno;
 1630         DEBUG(SSSDBG_FATAL_FAILURE,
 1631               "chown failed for [%s]: [%d][%s].\n",
 1632               cdb_file, ret, sss_strerror(ret));
 1633         goto done;
 1634     }
 1635 
 1636     *monitor = ctx;
 1637 
 1638     ret = EOK;
 1639 
 1640 done:
 1641     talloc_free(cdb_file);
 1642     if (ret != EOK) {
 1643         talloc_free(ctx);
 1644     }
 1645     return ret;
 1646 }
 1647 
 1648 static void poll_config_file(struct tevent_context *ev,
 1649                              struct tevent_timer *te,
 1650                              struct timeval t, void *ptr);
 1651 static errno_t monitor_config_file_fallback(TALLOC_CTX *parent_ctx,
 1652                                             struct config_file_ctx *file_ctx,
 1653                                             const char *file);
 1654 
 1655 static errno_t create_poll_timer(struct config_file_ctx *file_ctx)
 1656 {
 1657     struct timeval tv;
 1658 
 1659     gettimeofday(&tv, NULL);
 1660     tv.tv_sec += CONFIG_FILE_POLL_INTERVAL;
 1661     tv.tv_usec = 0;
 1662 
 1663     file_ctx->poll_check.timer = tevent_add_timer(file_ctx->mt_ctx->ev,
 1664                                                   file_ctx->poll_check.parent_ctx,
 1665                                                   tv,
 1666                                                   poll_config_file,
 1667                                                   file_ctx);
 1668     if (!file_ctx->poll_check.timer) {
 1669         talloc_free(file_ctx);
 1670         return EIO;
 1671     }
 1672 
 1673     return EOK;
 1674 }
 1675 
 1676 static void poll_config_file(struct tevent_context *ev,
 1677                              struct tevent_timer *te,
 1678                              struct timeval t, void *ptr)
 1679 {
 1680     int ret, err;
 1681     struct stat file_stat;
 1682     struct config_file_ctx *file_ctx;
 1683     struct config_file_callback *cb;
 1684 
 1685     file_ctx = talloc_get_type(ptr, struct config_file_ctx);
 1686 
 1687     for (cb = file_ctx->poll_check.callbacks; cb; cb = cb->next) {
 1688         ret = stat(cb->filename, &file_stat);
 1689         if (ret < 0) {
 1690             err = errno;
 1691             DEBUG(SSSDBG_FATAL_FAILURE,
 1692                   "Could not stat file [%s]. Error [%d:%s]\n",
 1693                   cb->filename, err, strerror(err));
 1694             return;
 1695         }
 1696 
 1697         if (file_stat.st_mtime != cb->modified) {
 1698             /* Parse the configuration file and signal the children */
 1699             /* Note: this will fire if the modification time changes into the past
 1700              * as well as the future.
 1701              */
 1702             DEBUG(SSSDBG_CRIT_FAILURE, "Config file changed\n");
 1703             cb->modified = file_stat.st_mtime;
 1704 
 1705             /* Tell the monitor to signal the children */
 1706             cb->fn(file_ctx, cb->filename);
 1707         }
 1708     }
 1709 
 1710     ret = create_poll_timer(file_ctx);
 1711     if (ret != EOK) {
 1712         DEBUG(SSSDBG_FATAL_FAILURE,
 1713               "Error: Config file no longer monitored for changes!\n");
 1714     }
 1715 }
 1716 
 1717 static int resolv_conf_inotify_cb(const char *filename,
 1718                                   uint32_t flags,
 1719                                   void *pvt)
 1720 {
 1721     struct config_file_ctx *file_ctx;
 1722 
 1723     DEBUG(SSSDBG_TRACE_INTERNAL,
 1724           "Received inotify notification for %s\n", filename);
 1725 
 1726     file_ctx = talloc_get_type(pvt, struct config_file_ctx);
 1727     if (file_ctx == NULL) {
 1728         return EINVAL;
 1729     }
 1730 
 1731     return file_ctx->fn(file_ctx, filename);
 1732 }
 1733 
 1734 static int try_inotify(struct config_file_ctx *file_ctx,
 1735                        const char *filename)
 1736 {
 1737 #ifdef HAVE_INOTIFY
 1738     struct snotify_ctx *snctx;
 1739     /* We will queue the file for update in one second.
 1740      * This way, if there is a script writing to the file
 1741      * repeatedly, we won't be attempting to update multiple
 1742      * times.
 1743      */
 1744     struct timeval delay = { .tv_sec = 1, .tv_usec = 0 };
 1745 
 1746     snctx = snotify_create(file_ctx, file_ctx->mt_ctx->ev, SNOTIFY_WATCH_DIR,
 1747                            filename, &delay,
 1748                            IN_DELETE_SELF | IN_CLOSE_WRITE | IN_MOVE_SELF | \
 1749                            IN_CREATE | IN_MOVED_TO | IN_IGNORED,
 1750                            resolv_conf_inotify_cb, file_ctx);
 1751     if (snctx == NULL) {
 1752         return EIO;
 1753     }
 1754 
 1755     return EOK;
 1756 #else
 1757     return EINVAL;
 1758 #endif /* HAVE_INOTIFY */
 1759 }
 1760 
 1761 static int monitor_config_file(TALLOC_CTX *mem_ctx,
 1762                                struct mt_ctx *ctx,
 1763                                monitor_reconf_fn fn,
 1764                                const char *file)
 1765 {
 1766     int ret;
 1767     bool use_inotify;
 1768 
 1769     if (!ctx->file_ctx) {
 1770         ctx->file_ctx = talloc_zero(mem_ctx, struct config_file_ctx);
 1771         if (!ctx->file_ctx) return ENOMEM;
 1772 
 1773         ctx->file_ctx->mt_ctx = ctx;
 1774         ctx->file_ctx->fn = fn;
 1775     }
 1776 
 1777     ret = confdb_get_bool(ctx->cdb,
 1778                           CONFDB_MONITOR_CONF_ENTRY,
 1779                           CONFDB_MONITOR_TRY_INOTIFY,
 1780                           true, &use_inotify);
 1781     if (ret != EOK) {
 1782         talloc_free(ctx->file_ctx);
 1783         return ret;
 1784     }
 1785 
 1786     if (use_inotify) {
 1787         ret = try_inotify(ctx->file_ctx, file);
 1788         if (ret != EOK) {
 1789             DEBUG(SSSDBG_MINOR_FAILURE, "Falling back to polling\n");
 1790             use_inotify = false;
 1791         }
 1792     }
 1793 
 1794     if (use_inotify == false) {
 1795         ret = monitor_config_file_fallback(mem_ctx, ctx->file_ctx, file);
 1796     }
 1797 
 1798     return ret;
 1799 }
 1800 
 1801 static errno_t monitor_config_file_fallback(TALLOC_CTX *parent_ctx,
 1802                                             struct config_file_ctx *file_ctx,
 1803                                             const char *file)
 1804 {
 1805     struct config_file_callback *cb = NULL;
 1806     struct stat file_stat;
 1807     int ret, err;
 1808 
 1809     ret = stat(file, &file_stat);
 1810     if (ret < 0) {
 1811         err = errno;
 1812         if (err == ENOENT) {
 1813             DEBUG(SSSDBG_CRIT_FAILURE,
 1814                   "file [%s] is missing. Will try again later.\n", file);
 1815         } else {
 1816             DEBUG(SSSDBG_FATAL_FAILURE,
 1817                   "Could not stat file [%s]. Error [%d:%s]\n",
 1818                   file, err, strerror(err));
 1819         }
 1820         return err;
 1821     }
 1822 
 1823     file_ctx->poll_check.parent_ctx = parent_ctx;
 1824 
 1825     cb = talloc_zero(file_ctx, struct config_file_callback);
 1826     if (!cb) {
 1827         talloc_free(file_ctx);
 1828         return ENOMEM;
 1829     }
 1830     cb->filename = talloc_strdup(cb, file);
 1831     if (!cb->filename) {
 1832         talloc_free(file_ctx);
 1833         return ENOMEM;
 1834     }
 1835     cb->fn = file_ctx->fn;
 1836     cb->modified = file_stat.st_mtime;
 1837 
 1838     DLIST_ADD(file_ctx->poll_check.callbacks, cb);
 1839 
 1840     if(!file_ctx->poll_check.timer) {
 1841         ret = create_poll_timer(file_ctx);
 1842         if (ret != EOK) {
 1843             DEBUG(SSSDBG_OP_FAILURE, "Cannot create poll timer\n");
 1844             return ret;
 1845         }
 1846     }
 1847 
 1848     return EOK;
 1849 }
 1850 
 1851 #define MISSING_RESOLV_CONF_POLL_TIME 10
 1852 
 1853 static void missing_resolv_conf(struct tevent_context *ev,
 1854                                 struct tevent_timer *te,
 1855                                 struct timeval tv, void *data)
 1856 {
 1857     int ret;
 1858     struct mt_ctx *ctx = talloc_get_type(data, struct mt_ctx);
 1859 
 1860     ret = monitor_config_file(ctx, ctx, monitor_update_resolv, RESOLV_CONF_PATH);
 1861     if (ret == EOK) {
 1862         signal_res_init(ctx);
 1863     } else if (ret == ENOENT) {
 1864         tv = tevent_timeval_current_ofs(MISSING_RESOLV_CONF_POLL_TIME, 0);
 1865         te = tevent_add_timer(ctx->ev, ctx, tv, missing_resolv_conf, ctx);
 1866         if (te == NULL) {
 1867             DEBUG(SSSDBG_FATAL_FAILURE,
 1868                   "tevent_add_timer failed. resolv.conf will be ignored.\n");
 1869         }
 1870     } else {
 1871         DEBUG(SSSDBG_FATAL_FAILURE,
 1872               "Monitor_config_file failed. resolv.conf will be ignored.\n");
 1873     }
 1874 }
 1875 
 1876 static int monitor_config_files(struct mt_ctx *ctx)
 1877 {
 1878     int ret;
 1879     bool monitor_resolv_conf;
 1880     struct timeval tv;
 1881     struct tevent_timer *te;
 1882 
 1883     /* Watch for changes to the DNS resolv.conf */
 1884     ret = confdb_get_bool(ctx->cdb,
 1885                           CONFDB_MONITOR_CONF_ENTRY,
 1886                           CONFDB_MONITOR_RESOLV_CONF,
 1887                           true, &monitor_resolv_conf);
 1888     if (ret != EOK) {
 1889         return ret;
 1890     }
 1891 
 1892     if (monitor_resolv_conf) {
 1893         ret = monitor_config_file(ctx, ctx, monitor_update_resolv,
 1894                                   RESOLV_CONF_PATH);
 1895         if (ret == ENOENT) {
 1896             tv = tevent_timeval_current_ofs(MISSING_RESOLV_CONF_POLL_TIME, 0);
 1897             te = tevent_add_timer(ctx->ev, ctx, tv, missing_resolv_conf, ctx);
 1898             if (te == NULL) {
 1899                 DEBUG(SSSDBG_FATAL_FAILURE, "resolv.conf will be ignored\n");
 1900             }
 1901         } else if (ret != EOK) {
 1902             return ret;
 1903         }
 1904     } else {
 1905         DEBUG(SSS_LOG_NOTICE, "%s monitoring is disabled\n", RESOLV_CONF_PATH);
 1906     }
 1907 
 1908     return EOK;
 1909 }
 1910 
 1911 static void monitor_sbus_connected(struct tevent_req *req);
 1912 
 1913 static int monitor_process_init(struct mt_ctx *ctx,
 1914                                 const char *config_file)
 1915 {
 1916     TALLOC_CTX *tmp_ctx;
 1917     struct tevent_signal *tes;
 1918     struct tevent_req *req;
 1919     char *rcachedir;
 1920     int ret;
 1921     int error;
 1922     struct sysdb_upgrade_ctx db_up_ctx;
 1923 
 1924     /* Set up the environment variable for the Kerberos Replay Cache */
 1925     ret = confdb_get_string(ctx->cdb, ctx,
 1926                             CONFDB_MONITOR_CONF_ENTRY,
 1927                             CONFDB_MONITOR_KRB5_RCACHEDIR,
 1928                             KRB5_RCACHE_DIR,
 1929                             &rcachedir);
 1930     if (ret != EOK) {
 1931         return ret;
 1932     }
 1933 
 1934     if (strcmp(rcachedir, KRB5_RCACHE_DIR_DISABLE) != 0)
 1935     {
 1936         errno = 0;
 1937         ret = setenv("KRB5RCACHEDIR", rcachedir, 1);
 1938         if (ret < 0) {
 1939             error = errno;
 1940             DEBUG(SSSDBG_CRIT_FAILURE,
 1941                   "Unable to set KRB5RCACHEDIR: %s."
 1942                    "Will attempt to use libkrb5 defaults\n",
 1943                    strerror(error));
 1944         }
 1945         talloc_zfree(rcachedir);
 1946     }
 1947 
 1948     /* Set up an event handler for a SIGHUP */
 1949     tes = tevent_add_signal(ctx->ev, ctx, SIGHUP, 0,
 1950                             monitor_hup, ctx);
 1951     if (tes == NULL) {
 1952         return EIO;
 1953     }
 1954 
 1955     /* Set up an event handler for a SIGINT */
 1956     BlockSignals(false, SIGINT);
 1957     tes = tevent_add_signal(ctx->ev, ctx, SIGINT, 0,
 1958                             monitor_quit_signal, ctx);
 1959     if (tes == NULL) {
 1960         return EIO;
 1961     }
 1962 
 1963     /* Set up an event handler for a SIGTERM */
 1964     tes = tevent_add_signal(ctx->ev, ctx, SIGTERM, 0,
 1965                             monitor_quit_signal, ctx);
 1966     if (tes == NULL) {
 1967         return EIO;
 1968     }
 1969 
 1970     /* Handle SIGUSR1 (tell all providers to go offline) */
 1971     BlockSignals(false, SIGUSR1);
 1972     tes = tevent_add_signal(ctx->ev, ctx, SIGUSR1, 0,
 1973                             signal_offline, ctx);
 1974     if (tes == NULL) {
 1975         return EIO;
 1976     }
 1977 
 1978     /* Handle SIGUSR2 (tell all providers to go reset offline) */
 1979     BlockSignals(false, SIGUSR2);
 1980     tes = tevent_add_signal(ctx->ev, ctx, SIGUSR2, 0,
 1981                             signal_offline_reset, ctx);
 1982     if (tes == NULL) {
 1983         return EIO;
 1984     }
 1985 
 1986     /* Set up the SIGCHLD handler */
 1987     ret = sss_sigchld_init(ctx, ctx->ev, &ctx->sigchld_ctx);
 1988     if (ret != EOK) return ret;
 1989 
 1990     /* Set up watchers for system config files */
 1991     ret = monitor_config_files(ctx);
 1992     if (ret != EOK) {
 1993         return ret;
 1994     }
 1995 
 1996     /* Avoid a startup race condition between process.
 1997      * We need to handle DB upgrades or DB creation only
 1998      * in one process before all other start.
 1999      */
 2000     tmp_ctx = talloc_new(NULL);
 2001     if (!tmp_ctx) {
 2002         return ENOMEM;
 2003     }
 2004 
 2005     db_up_ctx.cdb = ctx->cdb;
 2006     ret = sysdb_init_ext(tmp_ctx, ctx->domains, &db_up_ctx,
 2007                          true, ctx->uid, ctx->gid);
 2008     if (ret != EOK) {
 2009         SYSDB_VERSION_ERROR_DAEMON(ret);
 2010         goto done;
 2011     }
 2012     talloc_zfree(tmp_ctx);
 2013 
 2014     req = sbus_server_create_and_connect_send(ctx, ctx->ev, SSS_BUS_MONITOR,
 2015                                               NULL, SSS_MONITOR_ADDRESS,
 2016                                               false, 100, ctx->uid, ctx->gid,
 2017                                               NULL, NULL);
 2018     if (req == NULL) {
 2019         ret = ENOMEM;
 2020         goto done;
 2021     }
 2022 
 2023     tevent_req_set_callback(req, monitor_sbus_connected, ctx);
 2024 
 2025     ret = EOK;
 2026 
 2027 done:
 2028     talloc_free(tmp_ctx);
 2029 
 2030     return ret;
 2031 }
 2032 
 2033 static void monitor_sbus_connected(struct tevent_req *req)
 2034 {
 2035     struct mt_ctx *ctx;
 2036     struct sss_domain_info *dom;
 2037     bool disable_netlink;
 2038     int num_providers;
 2039     errno_t ret;
 2040 
 2041     ctx = tevent_req_callback_data(req, struct mt_ctx);
 2042 
 2043     ret = sbus_server_create_and_connect_recv(ctx, req,
 2044                                               &ctx->sbus_server,
 2045                                               &ctx->sbus_conn);
 2046     talloc_zfree(req);
 2047     if (ret !=  EOK) {
 2048         goto done;
 2049     }
 2050 
 2051     SBUS_INTERFACE(iface,
 2052         sssd_monitor,
 2053         SBUS_METHODS(
 2054             SBUS_SYNC(METHOD, sssd_monitor, RegisterService, monitor_sbus_RegisterService, ctx)
 2055         ),
 2056         SBUS_SIGNALS(SBUS_NO_SIGNALS),
 2057         SBUS_PROPERTIES(SBUS_NO_PROPERTIES)
 2058     );
 2059 
 2060     struct sbus_path paths[] = {
 2061         {SSS_BUS_PATH, &iface},
 2062         {NULL, NULL}
 2063     };
 2064 
 2065     ret = sbus_connection_add_path_map(ctx->sbus_conn, paths);
 2066     if (ret != EOK) {
 2067         DEBUG(SSSDBG_FATAL_FAILURE, "Unable to add paths [%d]: %s\n",
 2068               ret, sss_strerror(ret));
 2069         goto done;
 2070     }
 2071 
 2072     ret = confdb_get_bool(ctx->cdb,
 2073                           CONFDB_MONITOR_CONF_ENTRY,
 2074                           CONFDB_MONITOR_DISABLE_NETLINK,
 2075                           false, &disable_netlink);
 2076 
 2077     if (ret != EOK) {
 2078         DEBUG(SSSDBG_OP_FAILURE,
 2079               "Failed to read disable_netlink from confdb: [%d] %s\n",
 2080               ret, sss_strerror(ret));
 2081         goto done;
 2082     }
 2083 
 2084     if (disable_netlink == false) {
 2085         ret = setup_netlink(ctx, ctx->ev, network_status_change_cb,
 2086                             ctx, &ctx->nlctx);
 2087         if (ret != EOK) {
 2088             DEBUG(SSSDBG_OP_FAILURE,
 2089                   "Cannot set up listening for network notifications\n");
 2090             goto done;
 2091         }
 2092     }
 2093 
 2094     /* start providers */
 2095     num_providers = 0;
 2096     for (dom = ctx->domains; dom; dom = get_next_domain(dom, 0)) {
 2097         ret = add_new_provider(ctx, dom->name, 0);
 2098         if (ret != EOK && ret != ENOENT) {
 2099             goto done;
 2100         }
 2101         if (ret != ENOENT) {
 2102             num_providers++;
 2103         }
 2104     }
 2105 
 2106     if (num_providers > 0) {
 2107         /* now set the services startup timeout *
 2108          * (responders will be started automatically when all
 2109          *  providers are up and running or when the timeout
 2110          *  expires) */
 2111         ret = add_services_startup_timeout(ctx);
 2112         if (ret != EOK) {
 2113             goto done;
 2114         }
 2115     } else if (ctx->services != NULL) {
 2116         int i;
 2117 
 2118         ctx->services_started = true;
 2119 
 2120         /* No providers start services immediately
 2121          * Normally this means only LOCAL is configured */
 2122         for (i = 0; ctx->services[i]; i++) {
 2123             ret = add_new_service(ctx, ctx->services[i], 0);
 2124             if (ret != EOK) {
 2125                 goto done;
 2126             }
 2127         }
 2128     }
 2129 
 2130     /* When the only provider set up is the local one (num_providers == 0) and
 2131      * there's no responder explicitly set up it means that we should notify
 2132      * systemd that SSSD is ready right now as any other provider/responder
 2133      * would be able to do so and the SSSD would end up hitting a systemd
 2134      * timeout! */
 2135     if (num_providers == 0 && ctx->services == NULL) {
 2136         ret = notify_startup();
 2137     }
 2138 
 2139 done:
 2140     if (ret != EOK) {
 2141         monitor_quit(ctx, 3);
 2142     }
 2143 }
 2144 
 2145 /*
 2146  * monitor_service_shutdown
 2147  * Unregister the client when it's connection is finished.
 2148  * Shuts down, from the monitor point of view, the service that just finished.
 2149  */
 2150 static void monitor_service_shutdown(struct mt_svc *svc)
 2151 {
 2152     struct mt_ctx *ctx = svc->mt_ctx;
 2153 
 2154     /* We must decrease the number of services when shutting down
 2155      * a {socket,dbus}-activated service. */
 2156     ctx->num_services--;
 2157 
 2158     DEBUG(SSSDBG_TRACE_FUNC,
 2159           "Unregistering service %s (%p)\n", svc->identity, svc);
 2160 
 2161     talloc_zfree(svc);
 2162 }
 2163 
 2164 static void service_startup_handler(struct tevent_context *ev,
 2165                                     struct tevent_timer *te,
 2166                                     struct timeval t, void *ptr);
 2167 
 2168 static int start_service(struct mt_svc *svc)
 2169 {
 2170     struct tevent_timer *te;
 2171     struct timeval tv;
 2172 
 2173     DEBUG(SSSDBG_CONF_SETTINGS,"Queueing service %s for startup\n", svc->name);
 2174 
 2175     tv = tevent_timeval_current();
 2176 
 2177     /* Add a timed event to start up the service.
 2178      * We have to do this in order to avoid a race
 2179      * condition where the service being started forks
 2180      * and attempts to connect to the SBUS before
 2181      * the monitor is serving it.
 2182      */
 2183     te = tevent_add_timer(svc->mt_ctx->ev, svc, tv,
 2184                           service_startup_handler, svc);
 2185     if (te == NULL) {
 2186         DEBUG(SSSDBG_FATAL_FAILURE,
 2187               "Unable to queue service %s for startup\n", svc->name);
 2188         return ENOMEM;
 2189     }
 2190     return EOK;
 2191 }
 2192 
 2193 static void mt_svc_exit_handler(int pid, int wait_status, void *pvt);
 2194 static void service_startup_handler(struct tevent_context *ev,
 2195                                     struct tevent_timer *te,
 2196                                     struct timeval t, void *ptr)
 2197 {
 2198     errno_t ret;
 2199     struct mt_svc *mt_svc;
 2200     char **args;
 2201 
 2202     mt_svc = talloc_get_type(ptr, struct mt_svc);
 2203     if (mt_svc == NULL) {
 2204         return;
 2205     }
 2206 
 2207     mt_svc->pid = fork();
 2208     if (mt_svc->pid != 0) {
 2209         if (mt_svc->pid == -1) {
 2210             DEBUG(SSSDBG_FATAL_FAILURE,
 2211                   "Could not fork child to start service [%s]. "
 2212                       "Continuing.\n", mt_svc->name);
 2213             return;
 2214         }
 2215 
 2216         /* Parent */
 2217         mt_svc->mt_ctx->check_children = true;
 2218 
 2219         /* Handle process exit */
 2220         ret = sss_child_register(mt_svc,
 2221                                  mt_svc->mt_ctx->sigchld_ctx,
 2222                                  mt_svc->pid,
 2223                                  mt_svc_exit_handler,
 2224                                  mt_svc,
 2225                                  &mt_svc->child_ctx);
 2226         if (ret != EOK) {
 2227             DEBUG(SSSDBG_FATAL_FAILURE,
 2228                   "Could not register sigchld handler.\n");
 2229             /* Should we exit here? For now, we'll hope this
 2230              * child never dies, because we can't restart it.
 2231              */
 2232         }
 2233 
 2234         DLIST_ADD(mt_svc->mt_ctx->svc_list, mt_svc);
 2235 
 2236         return;
 2237     }
 2238 
 2239     /* child */
 2240 
 2241     args = parse_args(mt_svc->command);
 2242     execvp(args[0], args);
 2243 
 2244     /* If we are here, exec() has failed
 2245      * Print errno and abort quickly */
 2246     DEBUG(SSSDBG_FATAL_FAILURE,
 2247           "Could not exec %s, reason: %s\n", mt_svc->command, strerror(errno));
 2248 
 2249     /* Also log to syslog since SSSD failed to start. */
 2250     sss_log(SSS_LOG_ERR, "Could not exec %s, reason: %s",
 2251             mt_svc->command, strerror(errno));
 2252 
 2253     /* We have to call _exit() instead of exit() here
 2254      * because a bug in D-BUS will cause the server to
 2255      * close its socket at exit() */
 2256     _exit(1);
 2257 }
 2258 
 2259 static void mt_svc_restart(struct tevent_context *ev,
 2260                            struct tevent_timer *te,
 2261                            struct timeval t, void *ptr)
 2262 {
 2263     struct mt_svc *svc;
 2264 
 2265     svc = talloc_get_type(ptr, struct mt_svc);
 2266     if (svc == NULL) {
 2267         return;
 2268     }
 2269 
 2270     DEBUG(SSSDBG_TRACE_FUNC, "Scheduling service %s for restart %d\n",
 2271                               svc->name, svc->restarts+1);
 2272 
 2273     if (svc->type == MT_SVC_SERVICE) {
 2274         add_new_service(svc->mt_ctx, svc->name, svc->restarts + 1);
 2275     } else if (svc->type == MT_SVC_PROVIDER) {
 2276         add_new_provider(svc->mt_ctx, svc->name, svc->restarts + 1);
 2277     } else {
 2278         /* Invalid type? */
 2279         DEBUG(SSSDBG_FATAL_FAILURE,
 2280               "BUG: Invalid child process type [%d]\n", svc->type);
 2281     }
 2282 
 2283     /* Free the old service (which will also remove it
 2284      * from the child list)
 2285      */
 2286     talloc_free(svc);
 2287 }
 2288 
 2289 static void mt_svc_exit_handler(int pid, int wait_status, void *pvt)
 2290 {
 2291     struct mt_svc *svc = talloc_get_type(pvt, struct mt_svc);
 2292 
 2293     DEBUG(SSSDBG_TRACE_LIBS,
 2294           "SIGCHLD handler of service %s called\n", svc->name);
 2295     svc_child_info(svc, wait_status);
 2296 
 2297     /* Check the number of restart tries and relaunch the service */
 2298     monitor_restart_service(svc);
 2299 
 2300     return;
 2301 }
 2302 
 2303 static void monitor_restart_service(struct mt_svc *svc)
 2304 {
 2305     struct mt_ctx *mt_ctx = svc->mt_ctx;
 2306     int restart_delay;
 2307     time_t now = time(NULL);
 2308     struct tevent_timer *te;
 2309     struct timeval tv;
 2310 
 2311     /* Handle the actual checks for how many times to restart this
 2312      * service before giving up.
 2313      */
 2314     if ((now - svc->last_restart) > MONITOR_RESTART_CNT_INTERVAL_RESET) {
 2315         svc->restarts = 0;
 2316     }
 2317 
 2318     /* Restart the service */
 2319     if (svc->restarts > MONITOR_MAX_SVC_RESTARTS) {
 2320         DEBUG(SSSDBG_FATAL_FAILURE,
 2321               "Process [%s], definitely stopped!\n", svc->name);
 2322 
 2323         sss_log(SSS_LOG_ERR,
 2324                 "Exiting the SSSD. Could not restart critical service [%s].",
 2325                 svc->name);
 2326 
 2327         talloc_free(svc);
 2328 
 2329         /* exit the SSSD with an error, shutting down all
 2330          * services and domains.
 2331          * We do this because if one of the responders is down
 2332          * and can't come back up, this is the only way to
 2333          * guarantee admin intervention.
 2334          */
 2335         monitor_quit(mt_ctx, 1);
 2336         return;
 2337     }
 2338 
 2339     /* restarts are schedule after 0, 2, 4 seconds */
 2340     restart_delay = svc->restarts << 1;
 2341     if (restart_delay > MONITOR_MAX_RESTART_DELAY) {
 2342         restart_delay = MONITOR_MAX_RESTART_DELAY;
 2343     }
 2344 
 2345     tv = tevent_timeval_current_ofs(restart_delay, 0);
 2346     te = tevent_add_timer(svc->mt_ctx->ev, svc, tv, mt_svc_restart, svc);
 2347     if (te == NULL) {
 2348         /* Nothing much we can do */
 2349         DEBUG(SSSDBG_CRIT_FAILURE,
 2350               "Failed to allocate timed event: mt_svc_restart.\n");
 2351         talloc_free(svc);
 2352         return;
 2353     }
 2354 }
 2355 
 2356 int main(int argc, const char *argv[])
 2357 {
 2358     int opt;
 2359     poptContext pc;
 2360     int opt_daemon = 0;
 2361     int opt_interactive = 0;
 2362     int opt_genconf = 0;
 2363     int opt_version = 0;
 2364     int opt_netlinkoff = 0;
 2365     char *opt_config_file = NULL;
 2366     char *opt_logger = NULL;
 2367     char *config_file = NULL;
 2368     char *opt_genconf_section = NULL;
 2369     int flags = 0;
 2370     struct main_context *main_ctx;
 2371     TALLOC_CTX *tmp_ctx;
 2372     struct mt_ctx *monitor;
 2373     int ret;
 2374     uid_t uid;
 2375 
 2376     struct poptOption long_options[] = {
 2377         POPT_AUTOHELP
 2378         SSSD_MAIN_OPTS
 2379         SSSD_LOGGER_OPTS
 2380         {"daemon", 'D', POPT_ARG_NONE, &opt_daemon, 0, \
 2381          _("Become a daemon (default)"), NULL }, \
 2382         {"interactive", 'i', POPT_ARG_NONE, &opt_interactive, 0, \
 2383          _("Run interactive (not a daemon)"), NULL}, \
 2384         {"disable-netlink", '\0', POPT_ARG_NONE | POPT_ARGFLAG_DOC_HIDDEN,
 2385             &opt_netlinkoff, 0, \
 2386          _("Disable netlink interface"), NULL}, \
 2387         {"config", 'c', POPT_ARG_STRING, &opt_config_file, 0, \
 2388          _("Specify a non-default config file"), NULL}, \
 2389         {"genconf", 'g', POPT_ARG_NONE, &opt_genconf, 0, \
 2390          _("Refresh the configuration database, then exit"), \
 2391          NULL}, \
 2392         {"genconf-section", 's', POPT_ARG_STRING, &opt_genconf_section, 0, \
 2393          _("Similar to --genconf, but only refreshes the given section"), \
 2394          NULL}, \
 2395         {"version", '\0', POPT_ARG_NONE, &opt_version, 0, \
 2396          _("Print version number and exit"), NULL }, \
 2397         POPT_TABLEEND
 2398     };
 2399 
 2400     /* Set debug level to invalid value so we can decide if -d 0 was used. */
 2401     debug_level = SSSDBG_INVALID;
 2402 
 2403     pc = poptGetContext(argv[0], argc, argv, long_options, 0);
 2404     while((opt = poptGetNextOpt(pc)) != -1) {
 2405         switch(opt) {
 2406         default:
 2407             fprintf(stderr, "\nInvalid option %s: %s\n\n",
 2408                     poptBadOption(pc, 0), poptStrerror(opt));
 2409             poptPrintUsage(pc, stderr, 0);
 2410             return 1;
 2411         }
 2412     }
 2413 
 2414     DEBUG_INIT(debug_level);
 2415 
 2416     if (opt_version) {
 2417         puts(VERSION""PRERELEASE_VERSION);
 2418         return EXIT_SUCCESS;
 2419     }
 2420 
 2421     if (opt_genconf_section) {
 2422         /* --genconf-section implies genconf, just restricted to a single
 2423          * section
 2424          */
 2425         opt_genconf = 1;
 2426     }
 2427 
 2428     /* If the level or timestamps was passed at the command-line, we want
 2429      * to save it and pass it to the children later.
 2430      */
 2431     cmdline_debug_level = debug_level;
 2432     cmdline_debug_timestamps = debug_timestamps;
 2433     cmdline_debug_microseconds = debug_microseconds;
 2434 
 2435     if (opt_daemon && opt_interactive) {
 2436         fprintf(stderr, "Option -i|--interactive is not allowed together with -D|--daemon\n");
 2437         poptPrintUsage(pc, stderr, 0);
 2438         return 1;
 2439     }
 2440 
 2441     if (opt_genconf && (opt_daemon || opt_interactive)) {
 2442         fprintf(stderr, "Option -g is incompatible with -D or -i\n");
 2443         poptPrintUsage(pc, stderr, 0);
 2444         return 1;
 2445     }
 2446 
 2447     if (!opt_daemon && !opt_interactive && !opt_genconf) {
 2448         opt_daemon = 1;
 2449     }
 2450 
 2451     poptFreeContext(pc);
 2452 
 2453     uid = getuid();
 2454     if (uid != 0) {
 2455         DEBUG(SSSDBG_FATAL_FAILURE,
 2456               "Running under %"SPRIuid", must be root\n", uid);
 2457         sss_log(SSS_LOG_ALERT, "sssd must be run as root");
 2458         return 8;
 2459     }
 2460 
 2461     tmp_ctx = talloc_new(NULL);
 2462     if (!tmp_ctx) {
 2463         return 7;
 2464     }
 2465 
 2466     if (opt_daemon) flags |= FLAGS_DAEMON;
 2467     if (opt_interactive) {
 2468         flags |= FLAGS_INTERACTIVE;
 2469         debug_to_stderr = 1;
 2470     }
 2471     if (opt_genconf) {
 2472         flags |= FLAGS_GEN_CONF;
 2473         debug_to_stderr = 1;
 2474     }
 2475 
 2476     sss_set_logger(opt_logger);
 2477 
 2478     if (opt_config_file) {
 2479         config_file = talloc_strdup(tmp_ctx, opt_config_file);
 2480     } else {
 2481         config_file = talloc_strdup(tmp_ctx, SSSD_CONFIG_FILE);
 2482     }
 2483 
 2484     if (opt_netlinkoff) {
 2485         DEBUG(SSSDBG_MINOR_FAILURE,
 2486               "Option --disable-netlink has been removed and "
 2487               "replaced as a monitor option in sssd.conf\n");
 2488         sss_log(SSS_LOG_ALERT,
 2489                 "--disable-netlink has been deprecated, tunable option "
 2490                 "disable_netlink available as replacement(man sssd.conf)");
 2491     }
 2492 
 2493     if (!config_file) {
 2494         return 6;
 2495     }
 2496 
 2497     /* the monitor should not run a watchdog on itself */
 2498     flags |= FLAGS_NO_WATCHDOG;
 2499 
 2500     /* Open before server_setup() does to have logging
 2501      * during configuration checking */
 2502     if (sss_logger == FILES_LOGGER) {
 2503         ret = open_debug_file();
 2504         if (ret) {
 2505             return 7;
 2506         }
 2507     }
 2508 
 2509 #ifdef USE_KEYRING
 2510     /* Do this before all the forks, it sets the session key ring so all
 2511      * keys are private to the daemon and cannot be read by any other process
 2512      * tree */
 2513 
 2514     /* make a new session */
 2515     ret = keyctl_join_session_keyring(NULL);
 2516     if (ret == -1) {
 2517         sss_log(SSS_LOG_ALERT,
 2518                 "Could not create private keyring session. "
 2519                 "If you store password there they may be easily accessible "
 2520                 "to the root user. (%d, %s)", errno, strerror(errno));
 2521     }
 2522 
 2523     ret = keyctl_setperm(KEY_SPEC_SESSION_KEYRING, KEY_POS_ALL);
 2524     if (ret == -1) {
 2525         sss_log(SSS_LOG_ALERT,
 2526                 "Could not set permissions on private keyring. "
 2527                 "If you store password there they may be easily accessible "
 2528                 "to the root user. (%d, %s)", errno, strerror(errno));
 2529     }
 2530 #endif
 2531 
 2532     /* Check if the SSSD is already running and for nscd conflicts unless we're
 2533      * only interested in re-reading the configuration
 2534      */
 2535     if (opt_genconf == 0) {
 2536         ret = check_file(SSSD_PIDFILE, 0, 0, S_IFREG|0600, 0, NULL, false);
 2537         if (ret == EOK) {
 2538             ret = check_pidfile(SSSD_PIDFILE);
 2539             if (ret != EOK) {
 2540                 DEBUG(SSSDBG_FATAL_FAILURE,
 2541                     "pidfile exists at %s\n", SSSD_PIDFILE);
 2542                 ERROR("SSSD is already running\n");
 2543                 return 2;
 2544             }
 2545         }
 2546 
 2547         /* Warn if nscd seems to be running */
 2548         ret = check_file(NSCD_SOCKET_PATH,
 2549                          -1, -1, S_IFSOCK, S_IFMT, NULL, false);
 2550         if (ret == EOK) {
 2551             ret = sss_nscd_parse_conf(NSCD_CONF_PATH);
 2552 
 2553             switch (ret) {
 2554                 case ENOENT:
 2555                     sss_log(SSS_LOG_NOTICE,
 2556                             "NSCD socket was detected. NSCD caching capabilities "
 2557                             "may conflict with SSSD for users and groups. It is "
 2558                             "recommended not to run NSCD in parallel with SSSD, "
 2559                             "unless NSCD is configured not to cache the passwd, "
 2560                             "group, netgroup and services nsswitch maps.");
 2561                     break;
 2562 
 2563                 case EEXIST:
 2564                     sss_log(SSS_LOG_NOTICE,
 2565                             "NSCD socket was detected and seems to be configured "
 2566                             "to cache some of the databases controlled by "
 2567                             "SSSD [passwd,group,netgroup,services]. It is "
 2568                             "recommended not to run NSCD in parallel with SSSD, "
 2569                             "unless NSCD is configured not to cache these.");
 2570                     break;
 2571 
 2572                 case EOK:
 2573                     DEBUG(SSSDBG_TRACE_FUNC, "NSCD socket was detected and it "
 2574                                 "seems to be configured not to interfere with "
 2575                                 "SSSD's caching capabilities\n");
 2576             }
 2577         }
 2578 
 2579     }
 2580 
 2581     /* Parse config file, fail if cannot be done */
 2582     ret = load_configuration(tmp_ctx, config_file, CONFDB_DEFAULT_CONFIG_DIR,
 2583                              opt_genconf_section, &monitor);
 2584     if (ret != EOK) {
 2585         switch (ret) {
 2586         case EPERM:
 2587         case EACCES:
 2588             DEBUG(SSSDBG_FATAL_FAILURE,
 2589                   CONF_FILE_PERM_ERROR_MSG, config_file);
 2590             sss_log(SSS_LOG_CRIT, CONF_FILE_PERM_ERROR_MSG, config_file);
 2591             break;
 2592         default:
 2593             DEBUG(SSSDBG_FATAL_FAILURE,
 2594                  "SSSD couldn't load the configuration database.\n");
 2595             sss_log(SSS_LOG_CRIT,
 2596                    "SSSD couldn't load the configuration database [%d]: %s.\n",
 2597                     ret, strerror(ret));
 2598             break;
 2599         }
 2600         return 4;
 2601     }
 2602 
 2603     /* at this point we are done generating the config file, we may exit
 2604      * if that's all we were asked to do */
 2605     if (opt_genconf) return 0;
 2606 
 2607     /* set up things like debug, signals, daemonization, etc. */
 2608     monitor->conf_path = CONFDB_MONITOR_CONF_ENTRY;
 2609     ret = close(STDIN_FILENO);
 2610     if (ret != EOK) return 6;
 2611 
 2612     ret = server_setup(SSSD_MONITOR_NAME, flags, 0, 0,
 2613                        monitor->conf_path, &main_ctx);
 2614     if (ret != EOK) return 2;
 2615 
 2616     /* Use confd initialized in server_setup. ldb_tdb module (1.4.0) check PID
 2617      * of process which initialized db for locking purposes.
 2618      * Failed to unlock db: ../ldb_tdb/ldb_tdb.c:147:
 2619      *    Reusing ldb opened by pid 28889 in process 28893
 2620      */
 2621     talloc_zfree(monitor->cdb);
 2622     monitor->cdb = main_ctx->confdb_ctx;
 2623 
 2624     ret = confdb_get_domains(monitor->cdb, &monitor->domains);
 2625     if (ret != EOK) {
 2626         DEBUG(SSSDBG_FATAL_FAILURE, "No domains configured.\n");
 2627         return 4;
 2628     }
 2629 
 2630     monitor->is_daemon = !opt_interactive;
 2631     monitor->parent_pid = main_ctx->parent_pid;
 2632     monitor->ev = main_ctx->event_ctx;
 2633     talloc_steal(main_ctx, monitor);
 2634 
 2635     ret = monitor_process_init(monitor, config_file);
 2636 
 2637     if (ret != EOK) return 3;
 2638     talloc_free(tmp_ctx);
 2639 
 2640     /* loop on main */
 2641     server_loop(main_ctx);
 2642 
 2643     ret = monitor_cleanup();
 2644     if (ret != EOK) return 5;
 2645 
 2646     return 0;
 2647 }