lock_daemon.c 41.7 KB
Newer Older
1 2 3
/*
 * lock_daemon.c: lock management daemon
 *
4
 * Copyright (C) 2006-2015 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library;  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <getopt.h>
#include <stdlib.h>
#include <locale.h>


#include "lock_daemon.h"
#include "lock_daemon_config.h"
36
#include "virutil.h"
37 38
#include "virfile.h"
#include "virpidfile.h"
39
#include "virprocess.h"
40
#include "virerror.h"
41
#include "virlog.h"
42
#include "viralloc.h"
43
#include "virconf.h"
44
#include "rpc/virnetdaemon.h"
45 46 47
#include "rpc/virnetserver.h"
#include "virrandom.h"
#include "virhash.h"
48
#include "viruuid.h"
49
#include "virstring.h"
50

51 52 53
#include "locking/lock_daemon_dispatch.h"
#include "locking/lock_protocol.h"

54 55 56 57
#include "configmake.h"

#define VIR_FROM_THIS VIR_FROM_LOCKING

58 59
VIR_LOG_INIT("locking.lock_daemon");

60 61
#define VIR_LOCK_DAEMON_NUM_LOCKSPACES 3

62 63
struct _virLockDaemon {
    virMutex lock;
64
    virNetDaemonPtr dmn;
65 66
    virHashTablePtr lockspaces;
    virLockSpacePtr defaultLockspace;
67 68 69 70
};

virLockDaemonPtr lockDaemon = NULL;

71
static bool execRestart;
72

73 74 75 76 77 78 79 80 81 82
enum {
    VIR_LOCK_DAEMON_ERR_NONE = 0,
    VIR_LOCK_DAEMON_ERR_PIDFILE,
    VIR_LOCK_DAEMON_ERR_RUNDIR,
    VIR_LOCK_DAEMON_ERR_INIT,
    VIR_LOCK_DAEMON_ERR_SIGNAL,
    VIR_LOCK_DAEMON_ERR_PRIVS,
    VIR_LOCK_DAEMON_ERR_NETWORK,
    VIR_LOCK_DAEMON_ERR_CONFIG,
    VIR_LOCK_DAEMON_ERR_HOOKS,
83
    VIR_LOCK_DAEMON_ERR_REEXEC,
84 85 86 87 88 89 90 91 92 93 94 95 96 97

    VIR_LOCK_DAEMON_ERR_LAST
};

VIR_ENUM_DECL(virDaemonErr)
VIR_ENUM_IMPL(virDaemonErr, VIR_LOCK_DAEMON_ERR_LAST,
              "Initialization successful",
              "Unable to obtain pidfile",
              "Unable to create rundir",
              "Unable to initialize libvirt",
              "Unable to setup signal handlers",
              "Unable to drop privileges",
              "Unable to initialize network sockets",
              "Unable to load configuration file",
98 99
              "Unable to look for hook scripts",
              "Unable to re-execute daemon");
100 101 102 103 104 105 106

static void *
virLockDaemonClientNew(virNetServerClientPtr client,
                       void *opaque);
static void
virLockDaemonClientFree(void *opaque);

107 108 109 110 111 112 113 114
static void *
virLockDaemonClientNewPostExecRestart(virNetServerClientPtr client,
                                      virJSONValuePtr object,
                                      void *opaque);
static virJSONValuePtr
virLockDaemonClientPreExecRestart(virNetServerClientPtr client,
                                  void *opaque);

115 116 117 118 119 120
static void
virLockDaemonFree(virLockDaemonPtr lockd)
{
    if (!lockd)
        return;

121
    virObjectUnref(lockd->dmn);
122 123
    virHashFree(lockd->lockspaces);
    virLockSpaceFree(lockd->defaultLockspace);
124 125 126 127 128

    VIR_FREE(lockd);
}


129 130 131 132 133 134
static void virLockDaemonLockSpaceDataFree(void *data,
                                           const void *key ATTRIBUTE_UNUSED)
{
    virLockSpaceFree(data);
}

135
static virLockDaemonPtr
136
virLockDaemonNew(virLockDaemonConfigPtr config, bool privileged)
137 138
{
    virLockDaemonPtr lockd;
139
    virNetServerPtr srv;
140

141
    if (VIR_ALLOC(lockd) < 0)
142 143 144 145 146 147 148 149 150
        return NULL;

    if (virMutexInit(&lockd->lock) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to initialize mutex"));
        VIR_FREE(lockd);
        return NULL;
    }

151 152 153 154 155 156 157
    if (!(srv = virNetServerNew(1, 1, 0, config->max_clients,
                                config->max_clients, -1, 0,
                                NULL,
                                virLockDaemonClientNew,
                                virLockDaemonClientPreExecRestart,
                                virLockDaemonClientFree,
                                (void*)(intptr_t)(privileged ? 0x1 : 0x0))))
158 159
        goto error;

160
    if (!(lockd->dmn = virNetDaemonNew()) ||
161
        virNetDaemonAddServer(lockd->dmn, srv) < 0)
162 163
        goto error;

164 165 166 167 168 169 170
    if (!(lockd->lockspaces = virHashCreate(VIR_LOCK_DAEMON_NUM_LOCKSPACES,
                                            virLockDaemonLockSpaceDataFree)))
        goto error;

    if (!(lockd->defaultLockspace = virLockSpaceNew(NULL)))
        goto error;

171 172
    return lockd;

173
 error:
174 175 176 177 178
    virLockDaemonFree(lockd);
    return NULL;
}


179 180 181 182 183 184
static virLockDaemonPtr
virLockDaemonNewPostExecRestart(virJSONValuePtr object, bool privileged)
{
    virLockDaemonPtr lockd;
    virJSONValuePtr child;
    virJSONValuePtr lockspaces;
185
    virNetServerPtr srv;
186
    size_t i;
187
    ssize_t n;
188

189
    if (VIR_ALLOC(lockd) < 0)
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
        return NULL;

    if (virMutexInit(&lockd->lock) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to initialize mutex"));
        VIR_FREE(lockd);
        return NULL;
    }

    if (!(lockd->lockspaces = virHashCreate(VIR_LOCK_DAEMON_NUM_LOCKSPACES,
                                            virLockDaemonLockSpaceDataFree)))
        goto error;

    if (!(child = virJSONValueObjectGet(object, "defaultLockspace"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing defaultLockspace data from JSON file"));
        goto error;
    }

    if (!(lockd->defaultLockspace =
          virLockSpaceNewPostExecRestart(child)))
        goto error;

    if (!(lockspaces = virJSONValueObjectGet(object, "lockspaces"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing lockspaces data from JSON file"));
        goto error;
    }

    if ((n = virJSONValueArraySize(lockspaces)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Malformed lockspaces data from JSON file"));
        goto error;
    }

225
    for (i = 0; i < n; i++) {
226 227 228 229 230 231 232 233 234 235 236 237 238 239
        virLockSpacePtr lockspace;

        child = virJSONValueArrayGet(lockspaces, i);

        if (!(lockspace = virLockSpaceNewPostExecRestart(child)))
            goto error;

        if (virHashAddEntry(lockd->lockspaces,
                            virLockSpaceGetDirectory(lockspace),
                            lockspace) < 0) {
            virLockSpaceFree(lockspace);
        }
    }

240 241 242 243 244 245 246 247 248 249 250 251
    if (virJSONValueObjectHasKey(object, "daemon")) {
        if (!(child = virJSONValueObjectGet(object, "daemon"))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Malformed daemon data from JSON file"));
            goto error;
        }
    } else {
        if (!(child = virJSONValueObjectGet(object, "server"))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing server data from JSON file"));
            goto error;
        }
252 253
    }

254 255 256
    if (!(lockd->dmn = virNetDaemonNewPostExecRestart(child)))
        goto error;

257 258 259 260 261 262
    if (!(srv = virNetDaemonAddServerPostExec(lockd->dmn,
                                              virLockDaemonClientNew,
                                              virLockDaemonClientNewPostExecRestart,
                                              virLockDaemonClientPreExecRestart,
                                              virLockDaemonClientFree,
                                              (void*)(intptr_t)(privileged ? 0x1 : 0x0))))
263 264 265 266
        goto error;

    return lockd;

267
 error:
268 269 270 271 272
    virLockDaemonFree(lockd);
    return NULL;
}


273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
int virLockDaemonAddLockSpace(virLockDaemonPtr lockd,
                              const char *path,
                              virLockSpacePtr lockspace)
{
    int ret;
    virMutexLock(&lockd->lock);
    ret = virHashAddEntry(lockd->lockspaces, path, lockspace);
    virMutexUnlock(&lockd->lock);
    return ret;
}

virLockSpacePtr virLockDaemonFindLockSpace(virLockDaemonPtr lockd,
                                           const char *path)
{
    virLockSpacePtr lockspace;
    virMutexLock(&lockd->lock);
    if (path && STRNEQ(path, ""))
        lockspace = virHashLookup(lockd->lockspaces, path);
    else
        lockspace = lockd->defaultLockspace;
    virMutexUnlock(&lockd->lock);
    return lockspace;
}


298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
static int
virLockDaemonForkIntoBackground(const char *argv0)
{
    int statuspipe[2];
    if (pipe(statuspipe) < 0)
        return -1;

    pid_t pid = fork();
    switch (pid) {
    case 0:
        {
            int stdinfd = -1;
            int stdoutfd = -1;
            int nextpid;

            VIR_FORCE_CLOSE(statuspipe[0]);

            if ((stdinfd = open("/dev/null", O_RDONLY)) < 0)
                goto cleanup;
            if ((stdoutfd = open("/dev/null", O_WRONLY)) < 0)
                goto cleanup;
            if (dup2(stdinfd, STDIN_FILENO) != STDIN_FILENO)
                goto cleanup;
            if (dup2(stdoutfd, STDOUT_FILENO) != STDOUT_FILENO)
                goto cleanup;
            if (dup2(stdoutfd, STDERR_FILENO) != STDERR_FILENO)
                goto cleanup;
            if (VIR_CLOSE(stdinfd) < 0)
                goto cleanup;
            if (VIR_CLOSE(stdoutfd) < 0)
                goto cleanup;

            if (setsid() < 0)
                goto cleanup;

            nextpid = fork();
            switch (nextpid) {
            case 0:
                return statuspipe[1];
            case -1:
                return -1;
            default:
                _exit(0);
            }

        cleanup:
            VIR_FORCE_CLOSE(stdoutfd);
            VIR_FORCE_CLOSE(stdinfd);
            return -1;

        }

    case -1:
        return -1;

    default:
        {
            int got, exitstatus = 0;
            int ret;
            char status;

            VIR_FORCE_CLOSE(statuspipe[1]);

            /* We wait to make sure the first child forked successfully */
            if ((got = waitpid(pid, &exitstatus, 0)) < 0 ||
                got != pid ||
                exitstatus != 0) {
                return -1;
            }

            /* Now block until the second child initializes successfully */
        again:
            ret = read(statuspipe[0], &status, 1);
            if (ret == -1 && errno == EINTR)
                goto again;

            if (ret == 1 && status != 0) {
                fprintf(stderr,
                        _("%s: error: %s. Check /var/log/messages or run without "
                          "--daemon for more info.\n"), argv0,
                        virDaemonErrTypeToString(status));
            }
            _exit(ret == 1 && status == 0 ? 0 : 1);
        }
    }
}


static int
virLockDaemonUnixSocketPaths(bool privileged,
                             char **sockfile)
{
    if (privileged) {
391 392
        if (VIR_STRDUP(*sockfile, LOCALSTATEDIR "/run/libvirt/virtlockd-sock") < 0)
            goto error;
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
    } else {
        char *rundir = NULL;
        mode_t old_umask;

        if (!(rundir = virGetUserRuntimeDirectory()))
            goto error;

        old_umask = umask(077);
        if (virFileMakePath(rundir) < 0) {
            umask(old_umask);
            goto error;
        }
        umask(old_umask);

        if (virAsprintf(sockfile, "%s/virtlockd-sock", rundir) < 0) {
            VIR_FREE(rundir);
409
            goto error;
410 411 412 413 414 415
        }

        VIR_FREE(rundir);
    }
    return 0;

416
 error:
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    return -1;
}


static void
virLockDaemonErrorHandler(void *opaque ATTRIBUTE_UNUSED,
                          virErrorPtr err ATTRIBUTE_UNUSED)
{
    /* Don't do anything, since logging infrastructure already
     * took care of reporting the error */
}


/*
 * Set up the logging environment
 * By default if daemonized all errors go to the logfile libvirtd.log,
 * but if verbose or error debugging is asked for then also output
 * informational and debug messages. Default size if 64 kB.
 */
static int
virLockDaemonSetupLogging(virLockDaemonConfigPtr config,
                          bool privileged,
                          bool verbose,
                          bool godaemon)
{
    virLogReset();

    /*
     * Libvirtd's order of precedence is:
     * cmdline > environment > config
     *
     * In order to achieve this, we must process configuration in
     * different order for the log level versus the filters and
     * outputs. Because filters and outputs append, we have to look at
     * the environment first and then only check the config file if
     * there was no result from the environment. The default output is
     * then applied only if there was no setting from either of the
     * first two. Because we don't have a way to determine if the log
     * level has been set, we must process variables in the opposite
     * order, each one overriding the previous.
     */
    if (config->log_level != 0)
        virLogSetDefaultPriority(config->log_level);

    virLogSetFromEnv();

    if (virLogGetNbFilters() == 0)
        virLogParseFilters(config->log_filters);

    if (virLogGetNbOutputs() == 0)
        virLogParseOutputs(config->log_outputs);

    /*
     * If no defined outputs, and either running
     * as daemon or not on a tty, then first try
     * to direct it to the systemd journal
     * (if it exists)....
     */
    if (virLogGetNbOutputs() == 0 &&
        (godaemon || !isatty(STDIN_FILENO))) {
        char *tmp;
        if (access("/run/systemd/journal/socket", W_OK) >= 0) {
            if (virAsprintf(&tmp, "%d:journald", virLogGetDefaultPriority()) < 0)
480
                goto error;
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
            virLogParseOutputs(tmp);
            VIR_FREE(tmp);
        }
    }

    /*
     * otherwise direct to libvirtd.log when running
     * as daemon. Otherwise the default output is stderr.
     */
    if (virLogGetNbOutputs() == 0) {
        char *tmp = NULL;

        if (godaemon) {
            if (privileged) {
                if (virAsprintf(&tmp, "%d:file:%s/log/libvirt/virtlockd.log",
                                virLogGetDefaultPriority(),
                                LOCALSTATEDIR) == -1)
498
                    goto error;
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
            } else {
                char *logdir = virGetUserCacheDirectory();
                mode_t old_umask;

                if (!logdir)
                    goto error;

                old_umask = umask(077);
                if (virFileMakePath(logdir) < 0) {
                    umask(old_umask);
                    goto error;
                }
                umask(old_umask);

                if (virAsprintf(&tmp, "%d:file:%s/virtlockd.log",
                                virLogGetDefaultPriority(), logdir) == -1) {
                    VIR_FREE(logdir);
516
                    goto error;
517 518 519 520 521
                }
                VIR_FREE(logdir);
            }
        } else {
            if (virAsprintf(&tmp, "%d:stderr", virLogGetDefaultPriority()) < 0)
522
                goto error;
523 524 525 526 527 528 529 530 531 532 533 534 535
        }
        virLogParseOutputs(tmp);
        VIR_FREE(tmp);
    }

    /*
     * Command line override for --verbose
     */
    if ((verbose) && (virLogGetDefaultPriority() > VIR_LOG_INFO))
        virLogSetDefaultPriority(VIR_LOG_INFO);

    return 0;

536
 error:
537 538 539 540 541 542 543 544 545 546 547 548 549
    return -1;
}



/* Display version information. */
static void
virLockDaemonVersion(const char *argv0)
{
    printf("%s (%s) %s\n", argv0, PACKAGE_NAME, PACKAGE_VERSION);
}

static void
550
virLockDaemonShutdownHandler(virNetDaemonPtr dmn,
551 552 553
                             siginfo_t *sig ATTRIBUTE_UNUSED,
                             void *opaque ATTRIBUTE_UNUSED)
{
554
    virNetDaemonQuit(dmn);
555 556
}

557
static void
558
virLockDaemonExecRestartHandler(virNetDaemonPtr dmn,
559 560 561 562
                                siginfo_t *sig ATTRIBUTE_UNUSED,
                                void *opaque ATTRIBUTE_UNUSED)
{
    execRestart = true;
563
    virNetDaemonQuit(dmn);
564 565
}

566
static int
567
virLockDaemonSetupSignals(virNetDaemonPtr dmn)
568
{
569
    if (virNetDaemonAddSignalHandler(dmn, SIGINT, virLockDaemonShutdownHandler, NULL) < 0)
570
        return -1;
571
    if (virNetDaemonAddSignalHandler(dmn, SIGQUIT, virLockDaemonShutdownHandler, NULL) < 0)
572
        return -1;
573
    if (virNetDaemonAddSignalHandler(dmn, SIGTERM, virLockDaemonShutdownHandler, NULL) < 0)
574
        return -1;
575
    if (virNetDaemonAddSignalHandler(dmn, SIGUSR1, virLockDaemonExecRestartHandler, NULL) < 0)
576
        return -1;
577 578 579
    return 0;
}

580

581
static int
582 583 584 585 586
virLockDaemonSetupNetworkingSystemD(virNetServerPtr srv)
{
    virNetServerServicePtr svc;
    unsigned int nfds;

587
    if ((nfds = virGetListenFDs()) == 0)
588
        return 0;
589 590 591
    if (nfds > 1)
        VIR_DEBUG("Too many (%d) file descriptors from systemd", nfds);
    nfds = 1;
592 593 594

    /* Systemd passes FDs, starting immediately after stderr,
     * so the first FD we'll get is '3'. */
595
    if (!(svc = virNetServerServiceNewFD(3, 0,
596
#if WITH_GNUTLS
597 598
                                         NULL,
#endif
599
                                         false, 0, 1)))
600 601 602 603 604 605 606 607 608 609 610 611
        return -1;

    if (virNetServerAddService(srv, svc, NULL) < 0) {
        virObjectUnref(svc);
        return -1;
    }
    return 1;
}


static int
virLockDaemonSetupNetworkingNative(virNetServerPtr srv, const char *sock_path)
612 613 614 615 616
{
    virNetServerServicePtr svc;

    VIR_DEBUG("Setting up networking natively");

617
    if (!(svc = virNetServerServiceNewUNIX(sock_path, 0700, 0, 0,
618
#if WITH_GNUTLS
619 620
                                           NULL,
#endif
M
Michal Privoznik 已提交
621
                                           false, 0, 1)))
622 623 624 625 626 627 628 629 630 631
        return -1;

    if (virNetServerAddService(srv, svc, NULL) < 0) {
        virObjectUnref(svc);
        return -1;
    }
    return 0;
}


632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
struct virLockDaemonClientReleaseData {
    virLockDaemonClientPtr client;
    bool hadSomeLeases;
    bool gotError;
};

static void
virLockDaemonClientReleaseLockspace(void *payload,
                                    const void *name ATTRIBUTE_UNUSED,
                                    void *opaque)
{
    virLockSpacePtr lockspace = payload;
    struct virLockDaemonClientReleaseData *data = opaque;
    int rc;

    rc = virLockSpaceReleaseResourcesForOwner(lockspace,
                                              data->client->clientPid);
    if (rc > 0)
        data->hadSomeLeases = true;
    else if (rc < 0)
        data->gotError = true;
}


656 657 658 659 660 661 662 663
static void
virLockDaemonClientFree(void *opaque)
{
    virLockDaemonClientPtr priv = opaque;

    if (!priv)
        return;

664
    VIR_DEBUG("priv=%p client=%lld owner=%lld",
665
              priv,
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
              (unsigned long long)priv->clientPid,
              (unsigned long long)priv->ownerPid);

    /* If client & owner match, this is the lock holder */
    if (priv->clientPid == priv->ownerPid) {
        size_t i;
        struct virLockDaemonClientReleaseData data = {
            .client = priv, .hadSomeLeases = false, .gotError = false
        };

        /* Release all locks associated with this
         * owner in all lockspaces */
        virMutexLock(&lockDaemon->lock);
        virHashForEach(lockDaemon->lockspaces,
                       virLockDaemonClientReleaseLockspace,
                       &data);
        virLockDaemonClientReleaseLockspace(lockDaemon->defaultLockspace,
                                            "",
                                            &data);
        virMutexUnlock(&lockDaemon->lock);

        /* If the client had some active leases when it
         * closed the connection, we must kill it off
         * to make sure it doesn't do nasty stuff */
        if (data.gotError || data.hadSomeLeases) {
691
            for (i = 0; i < 15; i++) {
692 693 694 695 696 697 698
                int signum;
                if (i == 0)
                    signum = SIGTERM;
                else if (i == 8)
                    signum = SIGKILL;
                else
                    signum = 0;
J
Jim Fehlig 已提交
699
                if (priv->clientPid != 0 && virProcessKill(priv->clientPid, signum) < 0) {
700 701 702 703 704 705 706 707 708 709
                    if (errno == ESRCH)
                        break;

                    VIR_WARN("Failed to kill off pid %lld",
                             (unsigned long long)priv->clientPid);
                }
                usleep(200 * 1000);
            }
        }
    }
710 711 712 713 714 715 716 717 718 719 720 721 722

    virMutexDestroy(&priv->lock);
    VIR_FREE(priv);
}


static void *
virLockDaemonClientNew(virNetServerClientPtr client,
                       void *opaque)
{
    virLockDaemonClientPtr priv;
    uid_t clientuid;
    gid_t clientgid;
723
    unsigned long long timestamp;
724 725
    bool privileged = opaque != NULL;

726
    if (VIR_ALLOC(priv) < 0)
727 728 729 730
        return NULL;

    if (virMutexInit(&priv->lock) < 0) {
        VIR_FREE(priv);
731
        virReportSystemError(errno, "%s", _("unable to init mutex"));
732 733 734 735 736 737
        return NULL;
    }

    if (virNetServerClientGetUNIXIdentity(client,
                                          &clientuid,
                                          &clientgid,
738 739
                                          &priv->clientPid,
                                          &timestamp) < 0)
740 741 742 743 744 745 746 747
        goto error;

    VIR_DEBUG("New client pid %llu uid %llu",
              (unsigned long long)priv->clientPid,
              (unsigned long long)clientuid);

    if (!privileged) {
        if (geteuid() != clientuid) {
748 749 750
            virReportRestrictedError(_("Disallowing client %llu with uid %llu"),
                                     (unsigned long long)priv->clientPid,
                                     (unsigned long long)clientuid);
751 752 753 754
            goto error;
        }
    } else {
        if (clientuid != 0) {
755 756 757
            virReportRestrictedError(_("Disallowing client %llu with uid %llu"),
                                     (unsigned long long)priv->clientPid,
                                     (unsigned long long)clientuid);
758 759 760 761 762 763
            goto error;
        }
    }

    return priv;

764
 error:
765 766 767 768 769 770
    virMutexDestroy(&priv->lock);
    VIR_FREE(priv);
    return NULL;
}


771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
static void *
virLockDaemonClientNewPostExecRestart(virNetServerClientPtr client,
                                      virJSONValuePtr object,
                                      void *opaque)
{
    virLockDaemonClientPtr priv = virLockDaemonClientNew(client, opaque);
    unsigned int ownerPid;
    const char *ownerUUID;
    const char *ownerName;

    if (!priv)
        return NULL;

    if (virJSONValueObjectGetBoolean(object, "restricted", &priv->restricted) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing restricted data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectGetNumberUint(object, "ownerPid", &ownerPid) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing ownerPid data in JSON document"));
        goto error;
    }
    priv->ownerPid = (pid_t)ownerPid;
    if (virJSONValueObjectGetNumberUint(object, "ownerId", &priv->ownerId) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing ownerId data in JSON document"));
        goto error;
    }
    if (!(ownerName = virJSONValueObjectGetString(object, "ownerName"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing ownerName data in JSON document"));
        goto error;
    }
805
    if (VIR_STRDUP(priv->ownerName, ownerName) < 0)
806 807 808 809 810 811 812 813 814 815 816 817 818
        goto error;
    if (!(ownerUUID = virJSONValueObjectGetString(object, "ownerUUID"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing ownerUUID data in JSON document"));
        goto error;
    }
    if (virUUIDParse(ownerUUID, priv->ownerUUID) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing ownerUUID data in JSON document"));
        goto error;
    }
    return priv;

819
 error:
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    virLockDaemonClientFree(priv);
    return NULL;
}


static virJSONValuePtr
virLockDaemonClientPreExecRestart(virNetServerClientPtr client ATTRIBUTE_UNUSED,
                                  void *opaque)
{
    virLockDaemonClientPtr priv = opaque;
    virJSONValuePtr object = virJSONValueNewObject();
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    if (!object)
        return NULL;

    if (virJSONValueObjectAppendBoolean(object, "restricted", priv->restricted) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set restricted data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectAppendNumberUint(object, "ownerPid", priv->ownerPid) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set ownerPid data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectAppendNumberUint(object, "ownerId", priv->ownerId) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set ownerId data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectAppendString(object, "ownerName", priv->ownerName) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set ownerName data in JSON document"));
        goto error;
    }
    virUUIDFormat(priv->ownerUUID, uuidstr);
    if (virJSONValueObjectAppendString(object, "ownerUUID", uuidstr) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set ownerUUID data in JSON document"));
        goto error;
    }

    return object;

865
 error:
866 867 868 869 870
    virJSONValueFree(object);
    return NULL;
}


871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
static int
virLockDaemonExecRestartStatePath(bool privileged,
                                  char **state_file)
{
    if (privileged) {
        if (VIR_STRDUP(*state_file, LOCALSTATEDIR "/run/virtlockd-restart-exec.json") < 0)
            goto error;
    } else {
        char *rundir = NULL;
        mode_t old_umask;

        if (!(rundir = virGetUserRuntimeDirectory()))
            goto error;

        old_umask = umask(077);
        if (virFileMakePath(rundir) < 0) {
            umask(old_umask);
            VIR_FREE(rundir);
            goto error;
        }
        umask(old_umask);

        if (virAsprintf(state_file, "%s/virtlockd-restart-exec.json", rundir) < 0) {
            VIR_FREE(rundir);
            goto error;
        }

        VIR_FREE(rundir);
    }

    return 0;

903
 error:
904 905 906
    return -1;
}

907 908 909 910 911 912

static char *
virLockDaemonGetExecRestartMagic(void)
{
    char *ret;

913
    ignore_value(virAsprintf(&ret, "%lld", (long long int)getpid()));
914 915 916 917 918
    return ret;
}


static int
919 920 921 922
virLockDaemonPostExecRestart(const char *state_file,
                             const char *pid_file,
                             int *pid_file_fd,
                             bool privileged)
923 924 925 926 927 928 929 930 931
{
    const char *gotmagic;
    char *wantmagic = NULL;
    int ret = -1;
    char *state = NULL;
    virJSONValuePtr object = NULL;

    VIR_DEBUG("Running post-restart exec");

932 933 934
    if (!virFileExists(state_file)) {
        VIR_DEBUG("No restart state file %s present",
                  state_file);
935 936 937 938
        ret = 0;
        goto cleanup;
    }

939
    if (virFileReadAll(state_file,
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
                       1024 * 1024 * 10, /* 10 MB */
                       &state) < 0)
        goto cleanup;

    VIR_DEBUG("Loading state %s", state);

    if (!(object = virJSONValueFromString(state)))
        goto cleanup;

    gotmagic = virJSONValueObjectGetString(object, "magic");
    if (!gotmagic) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing magic data in JSON document"));
        goto cleanup;
    }

    if (!(wantmagic = virLockDaemonGetExecRestartMagic()))
        goto cleanup;

    if (STRNEQ(gotmagic, wantmagic)) {
        VIR_WARN("Found restart exec file with old magic %s vs wanted %s",
                 gotmagic, wantmagic);
        ret = 0;
        goto cleanup;
    }

966 967
    /* Re-claim PID file now as we will not be daemonizing */
    if (pid_file &&
968
        (*pid_file_fd = virPidFileAcquirePath(pid_file, false, getpid())) < 0)
969 970
        goto cleanup;

971 972 973 974 975
    if (!(lockDaemon = virLockDaemonNewPostExecRestart(object, privileged)))
        goto cleanup;

    ret = 1;

976
 cleanup:
977
    unlink(state_file);
978 979 980 981 982 983 984 985
    VIR_FREE(wantmagic);
    VIR_FREE(state);
    virJSONValueFree(object);
    return ret;
}


static int
986
virLockDaemonPreExecRestart(const char *state_file,
987
                            virNetDaemonPtr dmn,
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
                            char **argv)
{
    virJSONValuePtr child;
    char *state = NULL;
    int ret = -1;
    virJSONValuePtr object;
    char *magic;
    virHashKeyValuePairPtr pairs = NULL, tmp;
    virJSONValuePtr lockspaces;

    VIR_DEBUG("Running pre-restart exec");

    if (!(object = virJSONValueNewObject()))
        goto cleanup;

1003
    if (!(child = virNetDaemonPreExecRestart(dmn)))
1004 1005
        goto cleanup;

1006
    if (virJSONValueObjectAppend(object, "daemon", child) < 0) {
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
        virJSONValueFree(child);
        goto cleanup;
    }

    if (!(child = virLockSpacePreExecRestart(lockDaemon->defaultLockspace)))
        goto cleanup;

    if (virJSONValueObjectAppend(object, "defaultLockspace", child) < 0) {
        virJSONValueFree(child);
        goto cleanup;
    }

    if (!(lockspaces = virJSONValueNewArray()))
        goto cleanup;
    if (virJSONValueObjectAppend(object, "lockspaces", lockspaces) < 0) {
        virJSONValueFree(lockspaces);
        goto cleanup;
    }


    tmp = pairs = virHashGetItems(lockDaemon->lockspaces, NULL);
    while (tmp && tmp->key) {
        virLockSpacePtr lockspace = (virLockSpacePtr)tmp->value;

        if (!(child = virLockSpacePreExecRestart(lockspace)))
            goto cleanup;

        if (virJSONValueArrayAppend(lockspaces, child) < 0) {
            virJSONValueFree(child);
            goto cleanup;
        }

        tmp++;
    }

    if (!(magic = virLockDaemonGetExecRestartMagic()))
        goto cleanup;

    if (virJSONValueObjectAppendString(object, "magic", magic) < 0) {
        VIR_FREE(magic);
        goto cleanup;
    }

    if (!(state = virJSONValueToString(object, true)))
        goto cleanup;

    VIR_DEBUG("Saving state %s", state);

1055
    if (virFileWriteStr(state_file,
1056 1057 1058
                        state, 0700) < 0) {
        virReportSystemError(errno,
                             _("Unable to save state file %s"),
1059
                             state_file);
1060 1061 1062
        goto cleanup;
    }

1063
    if (execvp(argv[0], argv) < 0) {
1064 1065 1066 1067 1068 1069 1070
        virReportSystemError(errno, "%s",
                             _("Unable to restart self"));
        goto cleanup;
    }

    abort(); /* This should be impossible to reach */

1071
 cleanup:
1072 1073 1074 1075 1076 1077 1078
    VIR_FREE(pairs);
    VIR_FREE(state);
    virJSONValueFree(object);
    return ret;
}


1079 1080 1081 1082 1083 1084 1085 1086 1087
static void
virLockDaemonUsage(const char *argv0, bool privileged)
{
    fprintf(stderr,
            _("\n"
              "Usage:\n"
              "  %s [options]\n"
              "\n"
              "Options:\n"
1088
              "  -h | --help            Display program help:\n"
1089 1090
              "  -v | --verbose         Verbose messages.\n"
              "  -d | --daemon          Run as a daemon & write PID file.\n"
1091
              "  -t | --timeout <secs>  Exit after timeout period.\n"
1092
              "  -f | --config <file>   Configuration file.\n"
1093
              "  -V | --version         Display version information.\n"
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
              "  -p | --pid-file <file> Change name of PID file.\n"
              "\n"
              "libvirt lock management daemon:\n"), argv0);

    if (privileged) {
        fprintf(stderr,
                _("\n"
                  "  Default paths:\n"
                  "\n"
                  "    Configuration file (unless overridden by -f):\n"
                  "      %s/libvirt/virtlockd.conf\n"
                  "\n"
                  "    Sockets:\n"
                  "      %s/run/libvirt/virtlockd-sock\n"
                  "\n"
                  "    PID file (unless overridden by -p):\n"
                  "      %s/run/virtlockd.pid\n"
                  "\n"),
                SYSCONFDIR,
                LOCALSTATEDIR,
                LOCALSTATEDIR);
    } else {
        fprintf(stderr, "%s",
                _("\n"
                  "  Default paths:\n"
                  "\n"
                  "    Configuration file (unless overridden by -f):\n"
                  "      $XDG_CONFIG_HOME/libvirt/virtlockd.conf\n"
                  "\n"
                  "    Sockets:\n"
                  "      $XDG_RUNTIME_DIR/libvirt/virtlockd-sock\n"
                  "\n"
                  "    PID file:\n"
                  "      $XDG_RUNTIME_DIR/libvirt/virtlockd.pid\n"
                  "\n"));
    }
}

int main(int argc, char **argv) {
1133
    virNetServerPtr srv = NULL;
1134
    virNetServerProgramPtr lockProgram = NULL;
1135 1136 1137 1138 1139 1140 1141 1142 1143
    char *remote_config_file = NULL;
    int statuswrite = -1;
    int ret = 1;
    int verbose = 0;
    int godaemon = 0;
    char *run_dir = NULL;
    char *pid_file = NULL;
    int pid_file_fd = -1;
    char *sock_file = NULL;
1144
    int timeout = -1;        /* -t: Shutdown timeout */
1145
    char *state_file = NULL;
1146 1147 1148 1149
    bool implicit_conf = false;
    mode_t old_umask;
    bool privileged = false;
    virLockDaemonConfigPtr config = NULL;
1150
    int rv;
1151 1152

    struct option opts[] = {
1153 1154
        { "verbose", no_argument, &verbose, 'v'},
        { "daemon", no_argument, &godaemon, 'd'},
1155
        { "config", required_argument, NULL, 'f'},
1156
        { "timeout", required_argument, NULL, 't'},
1157
        { "pid-file", required_argument, NULL, 'p'},
1158 1159
        { "version", no_argument, NULL, 'V' },
        { "help", no_argument, NULL, 'h' },
1160 1161 1162
        {0, 0, 0, 0}
    };

1163
    privileged = geteuid() == 0;
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176

    if (setlocale(LC_ALL, "") == NULL ||
        bindtextdomain(PACKAGE, LOCALEDIR) == NULL ||
        textdomain(PACKAGE) == NULL ||
        virThreadInitialize() < 0 ||
        virErrorInitialize() < 0) {
        fprintf(stderr, _("%s: initialization failed\n"), argv[0]);
        exit(EXIT_FAILURE);
    }

    while (1) {
        int optidx = 0;
        int c;
1177
        char *tmp;
1178

1179
        c = getopt_long(argc, argv, "ldf:p:t:vVh", opts, &optidx);
1180

1181
        if (c == -1)
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
            break;

        switch (c) {
        case 0:
            /* Got one of the flags */
            break;
        case 'v':
            verbose = 1;
            break;
        case 'd':
            godaemon = 1;
            break;

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        case 't':
            if (virStrToLong_i(optarg, &tmp, 10, &timeout) != 0
                || timeout <= 0
                /* Ensure that we can multiply by 1000 without overflowing.  */
                || timeout > INT_MAX / 1000) {
                VIR_ERROR(_("Invalid value for timeout"));
                exit(EXIT_FAILURE);
            }
            break;

1205 1206
        case 'p':
            VIR_FREE(pid_file);
1207 1208
            if (VIR_STRDUP_QUIET(pid_file, optarg) < 0)
                goto no_memory;
1209 1210 1211 1212
            break;

        case 'f':
            VIR_FREE(remote_config_file);
1213 1214
            if (VIR_STRDUP_QUIET(remote_config_file, optarg) < 0)
                goto no_memory;
1215 1216
            break;

1217
        case 'V':
1218
            virLockDaemonVersion(argv[0]);
1219
            exit(EXIT_SUCCESS);
1220

1221
        case 'h':
1222
            virLockDaemonUsage(argv[0], privileged);
1223
            exit(EXIT_SUCCESS);
1224

1225
        case '?':
1226
        default:
1227
            virLockDaemonUsage(argv[0], privileged);
1228 1229 1230 1231
            exit(EXIT_FAILURE);
        }
    }

1232 1233
    virFileActivateDirOverride(argv[0]);

1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
    if (!(config = virLockDaemonConfigNew(privileged))) {
        VIR_ERROR(_("Can't create initial configuration"));
        exit(EXIT_FAILURE);
    }

    /* No explicit config, so try and find a default one */
    if (remote_config_file == NULL) {
        implicit_conf = true;
        if (virLockDaemonConfigFilePath(privileged,
                                        &remote_config_file) < 0) {
            VIR_ERROR(_("Can't determine config path"));
            exit(EXIT_FAILURE);
        }
    }

    /* Read the config file if it exists*/
    if (remote_config_file &&
        virLockDaemonConfigLoadFile(config, remote_config_file, implicit_conf) < 0) {
        virErrorPtr err = virGetLastError();
        if (err && err->message)
            VIR_ERROR(_("Can't load config file: %s: %s"),
                      err->message, remote_config_file);
        else
            VIR_ERROR(_("Can't load config file: %s"), remote_config_file);
        exit(EXIT_FAILURE);
    }

    if (virLockDaemonSetupLogging(config, privileged, verbose, godaemon) < 0) {
        VIR_ERROR(_("Can't initialize logging"));
        exit(EXIT_FAILURE);
    }

    if (!pid_file &&
1267 1268 1269 1270
        virPidFileConstructPath(privileged,
                                LOCALSTATEDIR,
                                "virtlockd",
                                &pid_file) < 0) {
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
        VIR_ERROR(_("Can't determine pid file path."));
        exit(EXIT_FAILURE);
    }
    VIR_DEBUG("Decided on pid file path '%s'", NULLSTR(pid_file));

    if (virLockDaemonUnixSocketPaths(privileged,
                                     &sock_file) < 0) {
        VIR_ERROR(_("Can't determine socket paths"));
        exit(EXIT_FAILURE);
    }
    VIR_DEBUG("Decided on socket paths '%s'",
              sock_file);

1284 1285 1286 1287
    if (virLockDaemonExecRestartStatePath(privileged,
                                          &state_file) < 0) {
        VIR_ERROR(_("Can't determine restart state file path"));
        exit(EXIT_FAILURE);
1288
    }
1289 1290
    VIR_DEBUG("Decided on restart state file path '%s'",
              state_file);
1291 1292 1293

    /* Ensure the rundir exists (on tmpfs on some systems) */
    if (privileged) {
1294 1295
        if (VIR_STRDUP_QUIET(run_dir, LOCALSTATEDIR "/run/libvirt") < 0)
            goto no_memory;
1296
    } else {
1297
        if (!(run_dir = virGetUserRuntimeDirectory())) {
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
            VIR_ERROR(_("Can't determine user directory"));
            goto cleanup;
        }
    }

    if (privileged)
        old_umask = umask(022);
    else
        old_umask = umask(077);
    VIR_DEBUG("Ensuring run dir '%s' exists", run_dir);
    if (virFileMakePath(run_dir) < 0) {
        char ebuf[1024];
        VIR_ERROR(_("unable to create rundir %s: %s"), run_dir,
                  virStrerror(errno, ebuf, sizeof(ebuf)));
        ret = VIR_LOCK_DAEMON_ERR_RUNDIR;
        goto cleanup;
    }
    umask(old_umask);

1317 1318 1319 1320
    if ((rv = virLockDaemonPostExecRestart(state_file,
                                           pid_file,
                                           &pid_file_fd,
                                           privileged)) < 0) {
1321 1322 1323 1324
        ret = VIR_LOCK_DAEMON_ERR_INIT;
        goto cleanup;
    }

1325
    /* rv == 1, means we setup everything from saved state,
1326 1327 1328
     * so only (possibly) daemonize and setup stuff from
     * scratch if rv == 0
     */
1329
    if (rv == 0) {
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
        if (godaemon) {
            char ebuf[1024];

            if (chdir("/") < 0) {
                VIR_ERROR(_("cannot change to root directory: %s"),
                          virStrerror(errno, ebuf, sizeof(ebuf)));
                goto cleanup;
            }

            if ((statuswrite = virLockDaemonForkIntoBackground(argv[0])) < 0) {
                VIR_ERROR(_("Failed to fork as daemon: %s"),
                          virStrerror(errno, ebuf, sizeof(ebuf)));
                goto cleanup;
            }
        }

        /* If we have a pidfile set, claim it now, exiting if already taken */
1347
        if ((pid_file_fd = virPidFileAcquirePath(pid_file, false, getpid())) < 0) {
1348 1349 1350 1351
            ret = VIR_LOCK_DAEMON_ERR_PIDFILE;
            goto cleanup;
        }

1352
        if (!(lockDaemon = virLockDaemonNew(config, privileged))) {
1353 1354 1355
            ret = VIR_LOCK_DAEMON_ERR_INIT;
            goto cleanup;
        }
1356

1357 1358
        srv = virNetDaemonGetServer(lockDaemon->dmn, 0);
        if ((rv = virLockDaemonSetupNetworkingSystemD(srv) < 0)) {
1359 1360 1361 1362 1363 1364
            ret = VIR_LOCK_DAEMON_ERR_NETWORK;
            goto cleanup;
        }

        /* Only do this, if systemd did not pass a FD */
        if (rv == 0 &&
1365
            virLockDaemonSetupNetworkingNative(srv, sock_file) < 0) {
1366 1367 1368
            ret = VIR_LOCK_DAEMON_ERR_NETWORK;
            goto cleanup;
        }
1369 1370
    }

1371 1372
    if (timeout != -1) {
        VIR_DEBUG("Registering shutdown timeout %d", timeout);
1373
        virNetDaemonAutoShutdown(lockDaemon->dmn,
1374 1375 1376
                                 timeout);
    }

1377
    if ((virLockDaemonSetupSignals(lockDaemon->dmn)) < 0) {
1378 1379 1380 1381
        ret = VIR_LOCK_DAEMON_ERR_SIGNAL;
        goto cleanup;
    }

1382 1383 1384 1385 1386 1387 1388
    if (!(lockProgram = virNetServerProgramNew(VIR_LOCK_SPACE_PROTOCOL_PROGRAM,
                                               VIR_LOCK_SPACE_PROTOCOL_PROGRAM_VERSION,
                                               virLockSpaceProtocolProcs,
                                               virLockSpaceProtocolNProcs))) {
        ret = VIR_LOCK_DAEMON_ERR_INIT;
        goto cleanup;
    }
1389

1390
    if (virNetServerAddProgram(srv, lockProgram) < 0) {
1391 1392 1393 1394
        ret = VIR_LOCK_DAEMON_ERR_INIT;
        goto cleanup;
    }

1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
    /* Disable error func, now logging is setup */
    virSetErrorFunc(NULL, virLockDaemonErrorHandler);


    /* Tell parent of daemon that basic initialization is complete
     * In particular we're ready to accept net connections & have
     * written the pidfile
     */
    if (statuswrite != -1) {
        char status = 0;
        while (write(statuswrite, &status, 1) == -1 &&
               errno == EINTR)
            ;
        VIR_FORCE_CLOSE(statuswrite);
    }

    /* Start accepting new clients from network */

1413 1414
    virNetDaemonUpdateServices(lockDaemon->dmn, true);
    virNetDaemonRun(lockDaemon->dmn);
1415 1416

    if (execRestart &&
1417
        virLockDaemonPreExecRestart(state_file,
1418
                                    lockDaemon->dmn,
1419
                                    argv) < 0)
1420
        ret = VIR_LOCK_DAEMON_ERR_REEXEC;
1421 1422
    else
        ret = 0;
1423

1424
 cleanup:
1425
    virObjectUnref(srv);
1426
    virObjectUnref(lockProgram);
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
    virLockDaemonFree(lockDaemon);
    if (statuswrite != -1) {
        if (ret != 0) {
            /* Tell parent of daemon what failed */
            char status = ret;
            while (write(statuswrite, &status, 1) == -1 &&
                   errno == EINTR)
                ;
        }
        VIR_FORCE_CLOSE(statuswrite);
    }
    if (pid_file_fd != -1)
        virPidFileReleasePath(pid_file, pid_file_fd);
    VIR_FREE(pid_file);
    VIR_FREE(sock_file);
1442
    VIR_FREE(state_file);
1443 1444
    VIR_FREE(run_dir);
    return ret;
1445

1446
 no_memory:
1447 1448
    VIR_ERROR(_("Can't allocate memory"));
    exit(EXIT_FAILURE);
1449
}