vircommand.c 85.9 KB
Newer Older
1
/*
2
 * vircommand.c: Child command execution
3
 *
4
 * Copyright (C) 2010-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23 24
 *
 */

#include <config.h>

#include <poll.h>
25
#include <regex.h>
26
#include <signal.h>
27
#include <stdarg.h>
28
#include <sys/stat.h>
29
#include <sys/wait.h>
30
#include <fcntl.h>
M
Michal Privoznik 已提交
31
#include <unistd.h>
32

33
#if WITH_CAPNG
34 35
# include <cap-ng.h>
#endif
36

37 38 39 40 41 42 43
#if defined(WITH_SECDRIVER_SELINUX)
# include <selinux/selinux.h>
#endif
#if defined(WITH_SECDRIVER_APPARMOR)
# include <sys/apparmor.h>
#endif

44
#define LIBVIRT_VIRCOMMANDPRIV_H_ALLOW
45
#include "vircommandpriv.h"
46
#include "virerror.h"
47
#include "virutil.h"
48
#include "virlog.h"
E
Eric Blake 已提交
49
#include "virfile.h"
50
#include "virpidfile.h"
51
#include "virprocess.h"
52
#include "virbuffer.h"
53
#include "virthread.h"
54
#include "virstring.h"
55

56 57
#define VIR_FROM_THIS VIR_FROM_NONE

58 59
VIR_LOG_INIT("util.command");

60
/* Flags for virExec */
61
enum {
62 63 64
    VIR_EXEC_NONE       = 0,
    VIR_EXEC_NONBLOCK   = (1 << 0),
    VIR_EXEC_DAEMON     = (1 << 1),
65
    VIR_EXEC_CLEAR_CAPS = (1 << 2),
66 67
    VIR_EXEC_RUN_SYNC   = (1 << 3),
    VIR_EXEC_ASYNC_IO   = (1 << 4),
68
    VIR_EXEC_LISTEN_FDS = (1 << 5),
69 70
};

71 72 73 74 75 76 77 78
typedef struct _virCommandFD virCommandFD;
typedef virCommandFD *virCommandFDPtr;

struct _virCommandFD {
    int fd;
    unsigned int flags;
};

79 80 81 82 83 84 85 86 87 88 89 90 91
struct _virCommand {
    int has_error; /* ENOMEM on allocation failure, -1 for anything else.  */

    char **args;
    size_t nargs;
    size_t maxargs;

    char **env;
    size_t nenv;
    size_t maxenv;

    char *pwd;

92 93
    size_t npassfd;
    virCommandFDPtr passfd;
94 95 96 97 98 99 100 101

    unsigned int flags;

    char *inbuf;
    char **outbuf;
    char **errbuf;

    int infd;
102
    int inpipe;
103 104 105 106 107
    int outfd;
    int errfd;
    int *outfdptr;
    int *errfdptr;

108
    virThreadPtr asyncioThread;
109

110 111 112 113
    bool handshake;
    int handshakeWait[2];
    int handshakeNotify[2];

114 115 116 117 118
    virExecHook hook;
    void *opaque;

    pid_t pid;
    char *pidfile;
119
    bool reap;
120
    bool rawStatus;
121

122 123 124
    unsigned long long maxMemLock;
    unsigned int maxProcesses;
    unsigned int maxFiles;
125 126
    bool setMaxCore;
    unsigned long long maxCore;
127

128 129
    uid_t uid;
    gid_t gid;
130
    unsigned long long capabilities;
131 132 133 134 135 136
#if defined(WITH_SECDRIVER_SELINUX)
    char *seLinuxLabel;
#endif
#if defined(WITH_SECDRIVER_APPARMOR)
    char *appArmorProfile;
#endif
137
    int mask;
138 139
};

140 141
/* See virCommandSetDryRun for description for this variable */
static virBufferPtr dryRunBuffer;
142 143 144
static virCommandDryRunCallback dryRunCallback;
static void *dryRunOpaque;
static int dryRunStatus;
145

146 147
/*
 * virCommandFDIsSet:
148 149
 * @cmd: pointer to virCommand
 * @fd: file descriptor to query
150 151 152 153 154 155 156
 *
 * Check if FD is already in @set or not.
 *
 * Returns true if @set contains @fd,
 * false otherwise.
 */
static bool
157 158
virCommandFDIsSet(virCommandPtr cmd,
                  int fd)
159
{
160
    size_t i = 0;
161 162
    if (!cmd)
        return false;
163

164 165
    while (i < cmd->npassfd)
        if (cmd->passfd[i++].fd == fd)
166 167 168 169 170 171 172
            return true;

    return false;
}

/*
 * virCommandFDSet:
173 174 175
 * @cmd: pointer to virCommand
 * @fd: file descriptor to pass
 * @flags: extra flags; binary-OR of virCommandPassFDFlags
176 177 178 179 180 181 182 183 184 185
 *
 * This is practically generalized implementation
 * of FD_SET() as we do not want to be limited
 * by FD_SETSIZE.
 *
 * Returns: 0 on success,
 *          -1 on usage error,
 *          ENOMEM on OOM
 */
static int
186 187 188
virCommandFDSet(virCommandPtr cmd,
                int fd,
                unsigned int flags)
189
{
190
    if (!cmd || fd < 0)
191 192
        return -1;

193
    if (virCommandFDIsSet(cmd, fd))
194 195
        return 0;

196
    if (VIR_EXPAND_N(cmd->passfd, cmd->npassfd, 1) < 0)
197 198
        return ENOMEM;

199 200
    cmd->passfd[cmd->npassfd - 1].fd = fd;
    cmd->passfd[cmd->npassfd - 1].flags = flags;
201 202 203

    return 0;
}
204

205 206
#ifndef WIN32

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
static void
virCommandReorderFDs(virCommandPtr cmd)
{
    int maxfd = 0;
    int openmax = 0;
    size_t i = 0;

    if (!cmd || cmd->has_error || !cmd->npassfd)
        return;

    for (i = 0; i < cmd->npassfd; i++)
        maxfd = MAX(cmd->passfd[i].fd, maxfd);

    openmax = sysconf(_SC_OPEN_MAX);
    if (openmax < 0 ||
        maxfd + cmd->npassfd > openmax)
        goto error;

    /*
     * Simple two-pass sort, nothing fancy.  This is not designed for
     * anything else than passing around 2 FDs into the child.
     *
     * So first dup2() them somewhere else.
     */
    for (i = 0; i < cmd->npassfd; i++) {
        int newfd = maxfd + i + 1;
        int oldfd = cmd->passfd[i].fd;
        if (dup2(oldfd, newfd) != newfd) {
            virReportSystemError(errno,
                                 _("Cannot dup2() fd %d before "
                                   "passing it to the child"),
                                 oldfd);
            goto error;
        }
        VIR_FORCE_CLOSE(cmd->passfd[i].fd);
    }

    VIR_DEBUG("First reorder pass done");

    /*
     * And then dup2() them in orderly manner.
     */
    for (i = 0; i < cmd->npassfd; i++) {
        int newfd = STDERR_FILENO + i + 1;
        int oldfd = maxfd + i + 1;
        if (dup2(oldfd, newfd) != newfd) {
            virReportSystemError(errno,
                                 _("Cannot dup2() fd %d before "
                                   "passing it to the child"),
                                 oldfd);
            goto error;
        }
        if (virSetInherit(newfd, true) < 0) {
            virReportSystemError(errno,
                                 _("Cannot set O_CLOEXEC on fd %d before "
                                   "passing it to the child"),
                                 newfd);
            goto error;
        }
        VIR_FORCE_CLOSE(oldfd);
        cmd->passfd[i].fd = newfd;
    }

    VIR_DEBUG("Second reorder pass done");

    return;

 error:
    cmd->has_error = -1;
    return;
}

E
Eric Blake 已提交
279 280 281
/**
 * virFork:
 *
282
 * Wrapper around fork() that avoids various race/deadlock conditions.
E
Eric Blake 已提交
283
 *
E
Eric Blake 已提交
284 285 286 287 288 289 290 291 292 293 294
 * Like fork(), there are several return possibilities:
 * 1. No child was created: the return is -1, errno is set, and an error
 * message has been reported.  The semantics of virWaitProcess() recognize
 * this to avoid clobbering the error message from here.
 * 2. This is the parent: the return is > 0.  The parent can now attempt
 * to interact with the child (but be aware that unlike raw fork(), the
 * child may not return - some failures in the child result in this
 * function calling _exit(EXIT_CANCELED) if the child cannot be set up
 * correctly).
 * 3. This is the child: the return is 0.  If this happens, the parent
 * is also guaranteed to return.
295
 */
E
Eric Blake 已提交
296 297
pid_t
virFork(void)
E
Eric Blake 已提交
298
{
299 300
    sigset_t oldmask, newmask;
    struct sigaction sig_action;
E
Eric Blake 已提交
301 302
    int saved_errno;
    pid_t pid;
303 304 305 306 307 308 309 310 311

    /*
     * Need to block signals now, so that child process can safely
     * kill off caller's signal handlers without a race.
     */
    sigfillset(&newmask);
    if (pthread_sigmask(SIG_SETMASK, &newmask, &oldmask) != 0) {
        virReportSystemError(errno,
                             "%s", _("cannot block signals"));
E
Eric Blake 已提交
312
        return -1;
313 314 315 316 317 318
    }

    /* Ensure we hold the logging lock, to protect child processes
     * from deadlocking on another thread's inherited mutex state */
    virLogLock();

E
Eric Blake 已提交
319
    pid = fork();
320 321 322 323 324
    saved_errno = errno; /* save for caller */

    /* Unlock for both parent and child process */
    virLogUnlock();

E
Eric Blake 已提交
325
    if (pid < 0) {
326
        /* attempt to restore signal mask, but ignore failure, to
E
Eric Blake 已提交
327
         * avoid obscuring the fork failure */
328
        ignore_value(pthread_sigmask(SIG_SETMASK, &oldmask, NULL));
329 330
        virReportSystemError(saved_errno,
                             "%s", _("cannot fork child process"));
E
Eric Blake 已提交
331
        errno = saved_errno;
332

E
Eric Blake 已提交
333
    } else if (pid) {
334 335 336
        /* parent process */

        /* Restore our original signal mask now that the child is
E
Eric Blake 已提交
337 338 339 340
         * safely running. Only documented failures are EFAULT (not
         * possible, since we are using just-grabbed mask) or EINVAL
         * (not possible, since we are using correct arguments).  */
        ignore_value(pthread_sigmask(SIG_SETMASK, &oldmask, NULL));
341 342 343 344 345

    } else {
        /* child process */

        int logprio;
346
        size_t i;
347

E
Eric Blake 已提交
348 349 350
        /* Remove any error callback so errors in child now get sent
         * to stderr where they stand a fighting chance of being seen
         * and logged */
351 352 353 354 355 356 357 358 359 360
        virSetErrorFunc(NULL, NULL);
        virSetErrorLogPriorityFunc(NULL);

        /* Make sure any hook logging is sent to stderr, since child
         * process may close the logfile FDs */
        logprio = virLogGetDefaultPriority();
        virLogReset();
        virLogSetDefaultPriority(logprio);

        /* Clear out all signal handlers from parent so nothing
E
Eric Blake 已提交
361 362
         * unexpected can happen in our child once we unblock
         * signals */
363 364 365 366 367
        sig_action.sa_handler = SIG_DFL;
        sig_action.sa_flags = 0;
        sigemptyset(&sig_action.sa_mask);

        for (i = 1; i < NSIG; i++) {
E
Eric Blake 已提交
368 369 370 371
            /* Only possible errors are EFAULT or EINVAL The former
             * won't happen, the latter we expect, so no need to check
             * return value */
            ignore_value(sigaction(i, &sig_action, NULL));
372 373
        }

E
Eric Blake 已提交
374 375 376
        /* Unmask all signals in child, since we've no idea what the
         * caller's done with their signal mask and don't want to
         * propagate that to children */
377 378 379
        sigemptyset(&newmask);
        if (pthread_sigmask(SIG_SETMASK, &newmask, NULL) != 0) {
            virReportSystemError(errno, "%s", _("cannot unblock signals"));
380 381
            virDispatchError(NULL);
            _exit(EXIT_CANCELED);
382 383
        }
    }
E
Eric Blake 已提交
384
    return pid;
385 386
}

E
Eric Blake 已提交
387 388 389 390 391 392 393 394
/*
 * Ensure that *null is an fd visiting /dev/null.  Return 0 on
 * success, -1 on failure.  Allows for lazy opening of shared
 * /dev/null fd only as required.
 */
static int
getDevNull(int *null)
{
395
    if (*null == -1 && (*null = open("/dev/null", O_RDWR|O_CLOEXEC)) < 0) {
E
Eric Blake 已提交
396 397 398 399 400 401 402 403
        virReportSystemError(errno,
                             _("cannot open %s"),
                             "/dev/null");
        return -1;
    }
    return 0;
}

404 405 406 407 408 409 410 411 412 413 414 415
/* Ensure that STD is an inheritable copy of FD.  Return 0 on success,
 * -1 on failure.  */
static int
prepareStdFd(int fd, int std)
{
    if (fd == std)
        return virSetInherit(fd, true);
    if (dup2(fd, std) != std)
        return -1;
    return 0;
}

416 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
/* virCommandHandshakeChild:
 *
 *   child side of handshake - called by child process in virExec() to
 *   indicate to parent that the child process has successfully
 *   completed its pre-exec initialization.
 */
static int
virCommandHandshakeChild(virCommandPtr cmd)
{
    char c = '1';
    int rv;

    if (!cmd->handshake)
       return true;

    VIR_DEBUG("Notifying parent for handshake start on %d",
              cmd->handshakeWait[1]);
    if (safewrite(cmd->handshakeWait[1], &c, sizeof(c)) != sizeof(c)) {
        virReportSystemError(errno, "%s",
                             _("Unable to notify parent process"));
        return -1;
    }

    VIR_DEBUG("Waiting on parent for handshake complete on %d",
              cmd->handshakeNotify[0]);
    if ((rv = saferead(cmd->handshakeNotify[0], &c,
                       sizeof(c))) != sizeof(c)) {
        if (rv < 0)
            virReportSystemError(errno, "%s",
                                 _("Unable to wait on parent process"));
        else
            virReportSystemError(EIO, "%s",
                                 _("libvirtd quit during handshake"));
        return -1;
    }
    if (c != '1') {
        virReportSystemError(EINVAL,
                             _("Unexpected confirm code '%c' from parent"),
                             c);
        return -1;
    }
    VIR_FORCE_CLOSE(cmd->handshakeWait[1]);
    VIR_FORCE_CLOSE(cmd->handshakeNotify[0]);

    VIR_DEBUG("Handshake with parent is done");
    return 0;
}

464
static int
M
Marc Hartmayer 已提交
465
virExecCommon(virCommandPtr cmd, gid_t *groups, int ngroups)
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
{
    int ret = -1;

    if (cmd->uid != (uid_t)-1 || cmd->gid != (gid_t)-1 ||
        cmd->capabilities || (cmd->flags & VIR_EXEC_CLEAR_CAPS)) {
        VIR_DEBUG("Setting child uid:gid to %d:%d with caps %llx",
                  (int)cmd->uid, (int)cmd->gid, cmd->capabilities);
        if (virSetUIDGIDWithCaps(cmd->uid, cmd->gid, groups, ngroups,
                                 cmd->capabilities,
                                 !!(cmd->flags & VIR_EXEC_CLEAR_CAPS)) < 0)
            goto cleanup;
    }

    if (cmd->pwd) {
        VIR_DEBUG("Running child in %s", cmd->pwd);
        if (chdir(cmd->pwd) < 0) {
            virReportSystemError(errno,
                                 _("Unable to change to %s"), cmd->pwd);
            goto cleanup;
        }
    }
    ret = 0;

 cleanup:
    return ret;
}

493
/*
494 495 496
 * virExec:
 * @cmd virCommandPtr containing all information about the program to
 *      exec.
497 498
 */
static int
499
virExec(virCommandPtr cmd)
500 501
{
    pid_t pid;
502
    int null = -1, fd, openmax;
E
Eric Blake 已提交
503 504
    int pipeout[2] = {-1, -1};
    int pipeerr[2] = {-1, -1};
505
    int childin = cmd->infd;
506 507 508
    int childout = -1;
    int childerr = -1;
    int tmpfd;
509
    VIR_AUTOFREE(char *) binarystr = NULL;
510
    const char *binary = NULL;
E
Eric Blake 已提交
511
    int ret;
512
    struct sigaction waxon, waxoff;
513
    VIR_AUTOFREE(gid_t *) groups = NULL;
M
Marc Hartmayer 已提交
514
    int ngroups;
515

516
    if (cmd->args[0][0] != '/') {
517
        if (!(binary = binarystr = virFindFileInPath(cmd->args[0]))) {
518 519
            virReportSystemError(ENOENT,
                                 _("Cannot find '%s' in path"),
520
                                 cmd->args[0]);
521 522 523
            return -1;
        }
    } else {
524
        binary = cmd->args[0];
525 526
    }

527
    if (childin < 0) {
E
Eric Blake 已提交
528 529
        if (getDevNull(&null) < 0)
            goto cleanup;
530
        childin = null;
531 532
    }

533 534
    if (cmd->outfdptr != NULL) {
        if (*cmd->outfdptr == -1) {
535
            if (pipe2(pipeout, O_CLOEXEC) < 0) {
536 537 538 539 540
                virReportSystemError(errno,
                                     "%s", _("cannot create pipe"));
                goto cleanup;
            }

541
            if ((cmd->flags & VIR_EXEC_NONBLOCK) &&
542
                virSetNonBlock(pipeout[0]) == -1) {
543 544
                virReportSystemError(errno, "%s",
                                     _("Failed to set non-blocking file descriptor flag"));
545 546 547 548 549
                goto cleanup;
            }

            childout = pipeout[1];
        } else {
550
            childout = *cmd->outfdptr;
551 552
        }
    } else {
E
Eric Blake 已提交
553 554
        if (getDevNull(&null) < 0)
            goto cleanup;
555 556 557
        childout = null;
    }

558 559
    if (cmd->errfdptr != NULL) {
        if (cmd->errfdptr == cmd->outfdptr) {
560
            childerr = childout;
561
        } else if (*cmd->errfdptr == -1) {
562
            if (pipe2(pipeerr, O_CLOEXEC) < 0) {
563 564 565 566 567
                virReportSystemError(errno,
                                     "%s", _("Failed to create pipe"));
                goto cleanup;
            }

568
            if ((cmd->flags & VIR_EXEC_NONBLOCK) &&
569
                virSetNonBlock(pipeerr[0]) == -1) {
570 571
                virReportSystemError(errno, "%s",
                                     _("Failed to set non-blocking file descriptor flag"));
572 573 574 575 576
                goto cleanup;
            }

            childerr = pipeerr[1];
        } else {
577
            childerr = *cmd->errfdptr;
578 579
        }
    } else {
E
Eric Blake 已提交
580 581
        if (getDevNull(&null) < 0)
            goto cleanup;
582 583 584
        childerr = null;
    }

M
Marc Hartmayer 已提交
585 586 587
    if ((ngroups = virGetGroupList(cmd->uid, cmd->gid, &groups)) < 0)
        goto cleanup;

E
Eric Blake 已提交
588
    pid = virFork();
589

590
    if (pid < 0)
591 592 593 594
        goto cleanup;

    if (pid) { /* parent */
        VIR_FORCE_CLOSE(null);
595
        if (cmd->outfdptr && *cmd->outfdptr == -1) {
596
            VIR_FORCE_CLOSE(pipeout[1]);
597
            *cmd->outfdptr = pipeout[0];
598
        }
599
        if (cmd->errfdptr && *cmd->errfdptr == -1) {
600
            VIR_FORCE_CLOSE(pipeerr[1]);
601
            *cmd->errfdptr = pipeerr[0];
602 603
        }

604
        cmd->pid = pid;
605 606 607 608 609 610

        return 0;
    }

    /* child */

611 612
    if (cmd->mask)
        umask(cmd->mask);
613
    ret = EXIT_CANCELED;
614
    openmax = sysconf(_SC_OPEN_MAX);
J
John Ferlan 已提交
615 616 617 618 619
    if (openmax < 0) {
        virReportSystemError(errno,  "%s",
                             _("sysconf(_SC_OPEN_MAX) failed"));
        goto fork_error;
    }
620 621
    for (fd = 3; fd < openmax; fd++) {
        if (fd == childin || fd == childout || fd == childerr)
622
            continue;
623
        if (!virCommandFDIsSet(cmd, fd)) {
624
            tmpfd = fd;
625
            VIR_MASS_CLOSE(tmpfd);
626 627
        } else if (virSetInherit(fd, true) < 0) {
            virReportSystemError(errno, _("failed to preserve fd %d"), fd);
628
            goto fork_error;
629
        }
630
    }
631

632
    if (prepareStdFd(childin, STDIN_FILENO) < 0) {
633 634 635 636
        virReportSystemError(errno,
                             "%s", _("failed to setup stdin file handle"));
        goto fork_error;
    }
637
    if (childout > 0 && prepareStdFd(childout, STDOUT_FILENO) < 0) {
638 639 640 641
        virReportSystemError(errno,
                             "%s", _("failed to setup stdout file handle"));
        goto fork_error;
    }
642
    if (childerr > 0 && prepareStdFd(childerr, STDERR_FILENO) < 0) {
643 644 645 646 647
        virReportSystemError(errno,
                             "%s", _("failed to setup stderr file handle"));
        goto fork_error;
    }

648 649 650
    if (childin != STDIN_FILENO && childin != null &&
        childin != childerr && childin != childout)
        VIR_FORCE_CLOSE(childin);
651 652 653
    if (childout > STDERR_FILENO && childout != null && childout != childerr)
        VIR_FORCE_CLOSE(childout);
    if (childerr > STDERR_FILENO && childerr != null)
654
        VIR_FORCE_CLOSE(childerr);
E
Eric Blake 已提交
655
    VIR_FORCE_CLOSE(null);
656 657 658 659 660 661

    /* Initialize full logging for a while */
    virLogSetFromEnv();

    /* Daemonize as late as possible, so the parent process can detect
     * the above errors with wait* */
662
    if (cmd->flags & VIR_EXEC_DAEMON) {
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
        if (setsid() < 0) {
            virReportSystemError(errno,
                                 "%s", _("cannot become session leader"));
            goto fork_error;
        }

        if (chdir("/") < 0) {
            virReportSystemError(errno,
                                 "%s", _("cannot change to root directory"));
            goto fork_error;
        }

        pid = fork();
        if (pid < 0) {
            virReportSystemError(errno,
                                 "%s", _("cannot fork child process"));
            goto fork_error;
        }

        if (pid > 0) {
683
            if (cmd->pidfile && (virPidFileWritePath(cmd->pidfile, pid) < 0)) {
E
Eric Blake 已提交
684 685 686 687
                if (virProcessKillPainfully(pid, true) >= 0)
                    virReportSystemError(errno,
                                         _("could not write pidfile %s for %d"),
                                         cmd->pidfile, pid);
688 689
                goto fork_error;
            }
690
            _exit(EXIT_SUCCESS);
691 692 693
        }
    }

694 695 696 697 698 699 700 701 702 703 704 705 706 707
    /* virFork reset all signal handlers to the defaults.
     * This is good for the child process, but our hook
     * risks running something that generates SIGPIPE,
     * so we need to temporarily block that again
     */
    memset(&waxoff, 0, sizeof(waxoff));
    waxoff.sa_handler = SIG_IGN;
    sigemptyset(&waxoff.sa_mask);
    memset(&waxon, 0, sizeof(waxon));
    if (sigaction(SIGPIPE, &waxoff, &waxon) < 0) {
        virReportSystemError(errno, "%s",
                             _("Could not disable SIGPIPE"));
        goto fork_error;
    }
708

709 710 711 712 713 714
    if (virProcessSetMaxMemLock(0, cmd->maxMemLock) < 0)
        goto fork_error;
    if (virProcessSetMaxProcesses(0, cmd->maxProcesses) < 0)
        goto fork_error;
    if (virProcessSetMaxFiles(0, cmd->maxFiles) < 0)
        goto fork_error;
715 716 717
    if (cmd->setMaxCore &&
        virProcessSetMaxCoreSize(0, cmd->maxCore) < 0)
        goto fork_error;
718

719 720 721 722 723 724
    if (cmd->hook) {
        VIR_DEBUG("Run hook %p %p", cmd->hook, cmd->opaque);
        ret = cmd->hook(cmd->opaque);
        VIR_DEBUG("Done hook %d", ret);
        if (ret < 0)
           goto fork_error;
725
    }
726

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
# if defined(WITH_SECDRIVER_SELINUX)
    if (cmd->seLinuxLabel) {
        VIR_DEBUG("Setting child security label to %s", cmd->seLinuxLabel);
        if (setexeccon_raw(cmd->seLinuxLabel) == -1) {
            virReportSystemError(errno,
                                 _("unable to set SELinux security context "
                                   "'%s' for '%s'"),
                                 cmd->seLinuxLabel, cmd->args[0]);
            if (security_getenforce() == 1)
                goto fork_error;
        }
    }
# endif
# if defined(WITH_SECDRIVER_APPARMOR)
    if (cmd->appArmorProfile) {
        VIR_DEBUG("Setting child AppArmor profile to %s", cmd->appArmorProfile);
        if (aa_change_profile(cmd->appArmorProfile) < 0) {
            virReportSystemError(errno,
                                 _("unable to set AppArmor profile '%s' "
                                   "for '%s'"),
                                 cmd->appArmorProfile, cmd->args[0]);
            goto fork_error;
        }
    }
# endif

M
Marc Hartmayer 已提交
753
    if (virExecCommon(cmd, groups, ngroups) < 0)
754
        goto fork_error;
755 756 757 758

    if (virCommandHandshakeChild(cmd) < 0)
       goto fork_error;

759 760 761 762
    if (sigaction(SIGPIPE, &waxon, NULL) < 0) {
        virReportSystemError(errno, "%s",
                             _("Could not re-enable SIGPIPE"));
        goto fork_error;
763 764
    }

765 766 767 768 769 770 771 772 773
    if (cmd->flags & VIR_EXEC_LISTEN_FDS) {
        virCommandReorderFDs(cmd);
        virCommandAddEnvFormat(cmd, "LISTEN_PID=%u", getpid());
        virCommandAddEnvFormat(cmd, "LISTEN_FDS=%zu", cmd->npassfd);

        if (cmd->has_error)
            goto fork_error;
    }

774 775 776
    /* Close logging again to ensure no FDs leak to child */
    virLogReset();

777 778
    if (cmd->env)
        execve(binary, cmd->args, cmd->env);
779
    else
780
        execv(binary, cmd->args);
781

782
    ret = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
783 784
    virReportSystemError(errno,
                         _("cannot execute binary %s"),
785
                         cmd->args[0]);
786 787 788

 fork_error:
    virDispatchError(NULL);
789
    _exit(ret);
790 791 792 793 794

 cleanup:
    /* This is cleanup of parent process only - child
       should never jump here on error */

795 796
    /* NB we don't virReportError() on any failures here
       because the code which jumped here already raised
797 798 799 800 801 802 803 804 805 806
       an error condition which we must not overwrite */
    VIR_FORCE_CLOSE(pipeerr[0]);
    VIR_FORCE_CLOSE(pipeerr[1]);
    VIR_FORCE_CLOSE(pipeout[0]);
    VIR_FORCE_CLOSE(pipeout[1]);
    VIR_FORCE_CLOSE(null);
    return -1;
}

/**
E
Eric Blake 已提交
807
 * virRun:
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
 * @argv NULL terminated argv to run
 * @status optional variable to return exit status in
 *
 * Run a command without using the shell.
 *
 * If status is NULL, then return 0 if the command run and
 * exited with 0 status; Otherwise return -1
 *
 * If status is not-NULL, then return 0 if the command ran.
 * The status variable is filled with the command exit status
 * and should be checked by caller for success. Return -1
 * only if the command could not be run.
 */
int
virRun(const char *const*argv, int *status)
{
824
    VIR_AUTOPTR(virCommand) cmd = virCommandNewArgs(argv);
825

826
    return virCommandRun(cmd, status);
827 828 829 830 831 832 833 834 835 836 837
}

#else /* WIN32 */

int
virRun(const char *const *argv ATTRIBUTE_UNUSED,
       int *status)
{
    if (status)
        *status = ENOTSUP;
    else
838 839
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("virRun is not implemented for WIN32"));
840 841 842 843
    return -1;
}

static int
844
virExec(virCommandPtr cmd ATTRIBUTE_UNUSED)
845 846 847 848
{
    /* XXX: Some day we can implement pieces of virCommand/virExec on
     * top of _spawn() or CreateProcess(), but we can't implement
     * everything, since mingw completely lacks fork(), so we cannot
849
     * run our own code in the child process.  */
850 851
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virExec is not implemented for WIN32"));
852 853 854
    return -1;
}

E
Eric Blake 已提交
855 856
pid_t
virFork(void)
857 858 859 860 861 862 863 864 865
{
    errno = ENOTSUP;

    return -1;
}

#endif /* WIN32 */


E
Eric Blake 已提交
866 867 868 869 870 871 872
/**
 * virCommandNew:
 * @binary: program to run
 *
 * Create a new command for named binary.  If @binary is relative,
 * it will be found via a PATH search of the parent's PATH (and not
 * any altered PATH set by virCommandAddEnv* commands).
873 874 875 876 877 878 879 880 881
 */
virCommandPtr
virCommandNew(const char *binary)
{
    const char *const args[] = { binary, NULL };

    return virCommandNewArgs(args);
}

E
Eric Blake 已提交
882 883 884 885
/**
 * virCommandNewArgs:
 * @args: array of arguments
 *
886
 * Create a new command with a NULL terminated
E
Eric Blake 已提交
887 888
 * set of args, taking binary from args[0].  More arguments can
 * be added later.  @args[0] is handled like @binary of virCommandNew.
889 890 891 892 893 894 895 896 897
 */
virCommandPtr
virCommandNewArgs(const char *const*args)
{
    virCommandPtr cmd;

    if (VIR_ALLOC(cmd) < 0)
        return NULL;

898 899 900 901 902
    cmd->handshakeWait[0] = -1;
    cmd->handshakeWait[1] = -1;
    cmd->handshakeNotify[0] = -1;
    cmd->handshakeNotify[1] = -1;

903
    cmd->infd = cmd->inpipe = cmd->outfd = cmd->errfd = -1;
904
    cmd->pid = -1;
905 906
    cmd->uid = -1;
    cmd->gid = -1;
907 908 909 910 911 912

    virCommandAddArgSet(cmd, args);

    return cmd;
}

E
Eric Blake 已提交
913 914 915 916 917
/**
 * virCommandNewArgList:
 * @binary: program to run
 * @...: additional arguments
 *
918
 * Create a new command with a NULL terminated
E
Eric Blake 已提交
919 920
 * list of args, starting with the binary to run.  More arguments can
 * be added later.  @binary is handled as in virCommandNew.
921 922 923 924
 */
virCommandPtr
virCommandNewArgList(const char *binary, ...)
{
925
    virCommandPtr cmd;
926 927 928
    va_list list;

    va_start(list, binary);
929
    cmd = virCommandNewVAList(binary, list);
930
    va_end(list);
931

932 933 934
    return cmd;
}

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
/**
 * virCommandNewVAList:
 * @binary: program to run
 * @va_list: additional arguments
 *
 * Create a new command with a NULL terminated
 * variable argument list.  @binary is handled as in virCommandNew.
 */
virCommandPtr
virCommandNewVAList(const char *binary, va_list list)
{
    virCommandPtr cmd = virCommandNew(binary);
    const char *arg;

    if (!cmd || cmd->has_error)
        return cmd;

    while ((arg = va_arg(list, const char *)) != NULL)
        virCommandAddArg(cmd, arg);
    return cmd;
}

957

958 959
#define VIR_COMMAND_MAYBE_CLOSE_FD(fd, flags) \
    if ((fd > STDERR_FILENO) && \
960 961
        (flags & VIR_COMMAND_PASS_FD_CLOSE_PARENT)) \
        VIR_FORCE_CLOSE(fd)
962

E
Eric Blake 已提交
963
/**
964
 * virCommandPassFD:
E
Eric Blake 已提交
965 966
 * @cmd: the command to modify
 * @fd: fd to reassign to the child
967
 * @flags: extra flags; binary-OR of virCommandPassFDFlags
E
Eric Blake 已提交
968
 *
969 970 971 972 973 974 975
 * Transfer the specified file descriptor to the child, instead
 * of closing it on exec. @fd must not be one of the three
 * standard streams.
 *
 * If the flag VIR_COMMAND_PASS_FD_CLOSE_PARENT is set then fd will
 * be closed in the parent no later than Run/RunAsync/Free. The parent
 * should cease using the @fd when this call completes
976 977
 */
void
978
virCommandPassFD(virCommandPtr cmd, int fd, unsigned int flags)
979
{
980 981 982 983 984 985 986 987 988 989 990 991 992 993
    int ret = 0;

    if (!cmd) {
        VIR_COMMAND_MAYBE_CLOSE_FD(fd, flags);
        return;
    }

    if (fd <= STDERR_FILENO) {
        VIR_DEBUG("invalid fd %d", fd);
        VIR_COMMAND_MAYBE_CLOSE_FD(fd, flags);
        if (!cmd->has_error)
            cmd->has_error = -1;
        return;
    }
994

995 996 997 998 999 1000 1001 1002
    if ((ret = virCommandFDSet(cmd, fd, flags)) != 0) {
        if (!cmd->has_error)
            cmd->has_error = ret;
        VIR_DEBUG("cannot preserve %d", fd);
        VIR_COMMAND_MAYBE_CLOSE_FD(fd, flags);
        return;
    }
}
1003

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
/**
 * virCommandPassListenFDs:
 * @cmd: the command to modify
 *
 * Pass LISTEN_FDS and LISTEN_PID environment variables into the
 * child.  LISTEN_PID has the value of the child's PID and LISTEN_FDS
 * is a number of passed file descriptors starting from 3.
 */
void
virCommandPassListenFDs(virCommandPtr cmd)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->flags |= VIR_EXEC_LISTEN_FDS;
}

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
/*
 * virCommandPassFDGetFDIndex:
 * @cmd: pointer to virCommand
 * @fd: FD to get index of
 *
 * Determine the index of the FD in the transfer set.
 *
 * Returns index >= 0 if @set contains @fd,
 * -1 otherwise.
 */
int
virCommandPassFDGetFDIndex(virCommandPtr cmd, int fd)
{
    size_t i = 0;

    while (i < cmd->npassfd) {
        if (cmd->passfd[i].fd == fd)
            return i;
        i++;
    }

    return -1;
}

E
Eric Blake 已提交
1045 1046 1047 1048 1049 1050 1051
/**
 * virCommandSetPidFile:
 * @cmd: the command to modify
 * @pidfile: filename to use
 *
 * Save the child PID in a pidfile.  The pidfile will be populated
 * before the exec of the child.
1052 1053 1054 1055 1056 1057 1058 1059
 */
void
virCommandSetPidFile(virCommandPtr cmd, const char *pidfile)
{
    if (!cmd || cmd->has_error)
        return;

    VIR_FREE(cmd->pidfile);
1060
    if (VIR_STRDUP_QUIET(cmd->pidfile, pidfile) < 0)
1061 1062 1063 1064
        cmd->has_error = ENOMEM;
}


1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
gid_t
virCommandGetGID(virCommandPtr cmd)
{
    return cmd->gid;
}


uid_t
virCommandGetUID(virCommandPtr cmd)
{
    return cmd->uid;
}


1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
void
virCommandSetGID(virCommandPtr cmd, gid_t gid)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->gid = gid;
}

void
virCommandSetUID(virCommandPtr cmd, uid_t uid)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->uid = uid;
}

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
void
virCommandSetMaxMemLock(virCommandPtr cmd, unsigned long long bytes)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->maxMemLock = bytes;
}

void
virCommandSetMaxProcesses(virCommandPtr cmd, unsigned int procs)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->maxProcesses = procs;
}

void
virCommandSetMaxFiles(virCommandPtr cmd, unsigned int files)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->maxFiles = files;
}

1124 1125 1126 1127 1128 1129 1130 1131 1132
void virCommandSetMaxCoreSize(virCommandPtr cmd, unsigned long long bytes)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->maxCore = bytes;
    cmd->setMaxCore = true;
}

1133
void virCommandSetUmask(virCommandPtr cmd, int mask)
1134 1135 1136 1137
{
    if (!cmd || cmd->has_error)
        return;

1138
    cmd->mask = mask;
1139 1140
}

E
Eric Blake 已提交
1141 1142 1143 1144 1145
/**
 * virCommandClearCaps:
 * @cmd: the command to modify
 *
 * Remove all capabilities from the child, after any hooks have been run.
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
 */
void
virCommandClearCaps(virCommandPtr cmd)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->flags |= VIR_EXEC_CLEAR_CAPS;
}

E
Eric Blake 已提交
1156 1157 1158 1159 1160
/**
 * virCommandAllowCap:
 * @cmd: the command to modify
 * @capability: what to allow
 *
1161
 * Allow specific capabilities
1162 1163 1164
 */
void
virCommandAllowCap(virCommandPtr cmd,
1165
                   int capability)
1166 1167 1168 1169
{
    if (!cmd || cmd->has_error)
        return;

1170
    cmd->capabilities |= (1ULL << capability);
1171 1172 1173
}


1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
/**
 * virCommandSetSELinuxLabel:
 * @cmd: the command to modify
 * @label: the SELinux label to use for the child process
 *
 * Saves a copy of @label to use when setting the SELinux context
 * label (with setexeccon_raw()) after the child process has been
 * started. If SELinux isn't compiled into libvirt, or if label is
 * NULL, nothing will be done.
 */
void
virCommandSetSELinuxLabel(virCommandPtr cmd,
                          const char *label ATTRIBUTE_UNUSED)
{
    if (!cmd || cmd->has_error)
        return;

#if defined(WITH_SECDRIVER_SELINUX)
    VIR_FREE(cmd->seLinuxLabel);
1193
    if (VIR_STRDUP_QUIET(cmd->seLinuxLabel, label) < 0)
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
        cmd->has_error = ENOMEM;
#endif
    return;
}


/**
 * virCommandSetAppArmorProfile:
 * @cmd: the command to modify
 * @profile: the AppArmor profile to use
 *
 * Saves a copy of @profile to use when aa_change_profile() after the
 * child process has been started. If AppArmor support isn't
 * configured into libvirt, or if profile is NULL, nothing will be done.
 */
void
virCommandSetAppArmorProfile(virCommandPtr cmd,
                             const char *profile ATTRIBUTE_UNUSED)
{
    if (!cmd || cmd->has_error)
        return;

#if defined(WITH_SECDRIVER_APPARMOR)
    VIR_FREE(cmd->appArmorProfile);
1218
    if (VIR_STRDUP_QUIET(cmd->appArmorProfile, profile) < 0)
1219 1220 1221 1222 1223
        cmd->has_error = ENOMEM;
#endif
    return;
}

1224

E
Eric Blake 已提交
1225 1226 1227 1228 1229 1230 1231
/**
 * virCommandDaemonize:
 * @cmd: the command to modify
 *
 * Daemonize the child process.  The child will have a current working
 * directory of /, and must be started with virCommandRun, which will
 * complete as soon as the daemon grandchild has started.
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
 */
void
virCommandDaemonize(virCommandPtr cmd)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->flags |= VIR_EXEC_DAEMON;
}

E
Eric Blake 已提交
1242 1243 1244 1245
/**
 * virCommandNonblockingFDs:
 * @cmd: the command to modify
 *
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
 * Set FDs created by virCommandSetOutputFD and virCommandSetErrorFD
 * as non-blocking in the parent.
 */
void
virCommandNonblockingFDs(virCommandPtr cmd)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->flags |= VIR_EXEC_NONBLOCK;
}

1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
/**
 * virCommandRawStatus:
 * @cmd: the command to modify
 *
 * Mark this command as returning raw exit status via virCommandRun() or
 * virCommandWait() (caller must use WIFEXITED() and friends, and can
 * detect death from signals) instead of the default of only allowing
 * normal exit status (caller must not use WEXITSTATUS(), and death from
 * signals returns -1).
 */
void
virCommandRawStatus(virCommandPtr cmd)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->rawStatus = true;
}

1277
/* Add an environment variable to the cmd->env list.  'env' is a
1278 1279
 * string like "name=value".  If the named environment variable is
 * already set, then it is replaced in the list.
1280
 */
1281
static void
1282 1283
virCommandAddEnv(virCommandPtr cmd, char *env)
{
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    size_t namelen;
    size_t i;

    /* Search for the name in the existing environment. */
    namelen = strcspn(env, "=");
    for (i = 0; i < cmd->nenv; ++i) {
        /* + 1 because we want to match the '=' character too. */
        if (STREQLEN(cmd->env[i], env, namelen + 1)) {
            VIR_FREE(cmd->env[i]);
            cmd->env[i] = env;
            return;
        }
    }

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    /* Arg plus trailing NULL. */
    if (VIR_RESIZE_N(cmd->env, cmd->maxenv, cmd->nenv, 1 + 1) < 0) {
        VIR_FREE(env);
        cmd->has_error = ENOMEM;
        return;
    }

    cmd->env[cmd->nenv++] = env;
}

E
Eric Blake 已提交
1308 1309 1310 1311 1312 1313 1314
/**
 * virCommandAddEnvFormat:
 * @cmd: the command to modify
 * @format: format of arguments, end result must be in name=value format
 * @...: arguments to be formatted
 *
 * Add an environment variable to the child created by a printf-style format.
1315 1316
 */
void
1317
virCommandAddEnvFormat(virCommandPtr cmd, const char *format, ...)
1318 1319
{
    char *env;
1320
    va_list list;
1321 1322 1323 1324

    if (!cmd || cmd->has_error)
        return;

1325 1326
    va_start(list, format);
    if (virVasprintf(&env, format, list) < 0) {
1327
        cmd->has_error = ENOMEM;
1328
        va_end(list);
1329 1330
        return;
    }
1331
    va_end(list);
1332

1333
    virCommandAddEnv(cmd, env);
1334 1335
}

E
Eric Blake 已提交
1336 1337 1338 1339 1340 1341
/**
 * virCommandAddEnvPair:
 * @cmd: the command to modify
 * @name: variable name, must not contain =
 * @value: value to assign to name
 *
1342 1343 1344 1345 1346 1347 1348 1349 1350
 * Add an environment variable to the child
 * using separate name & value strings
 */
void
virCommandAddEnvPair(virCommandPtr cmd, const char *name, const char *value)
{
    virCommandAddEnvFormat(cmd, "%s=%s", name, value);
}

1351

E
Eric Blake 已提交
1352 1353 1354 1355 1356
/**
 * virCommandAddEnvString:
 * @cmd: the command to modify
 * @str: name=value format
 *
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
 * Add an environment variable to the child
 * using a preformatted env string FOO=BAR
 */
void
virCommandAddEnvString(virCommandPtr cmd, const char *str)
{
    char *env;

    if (!cmd || cmd->has_error)
        return;

1368
    if (VIR_STRDUP_QUIET(env, str) < 0) {
1369 1370 1371 1372
        cmd->has_error = ENOMEM;
        return;
    }

1373
    virCommandAddEnv(cmd, env);
1374 1375 1376
}


E
Eric Blake 已提交
1377 1378 1379 1380 1381
/**
 * virCommandAddEnvBuffer:
 * @cmd: the command to modify
 * @buf: buffer that contains name=value string, which will be reset on return
 *
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
 * Convert a buffer containing preformatted name=value into an
 * environment variable of the child.
 * Correctly transfers memory errors or contents from buf to cmd.
 */
void
virCommandAddEnvBuffer(virCommandPtr cmd, virBufferPtr buf)
{
    if (!cmd || cmd->has_error) {
        virBufferFreeAndReset(buf);
        return;
    }

1394
    if (virBufferError(buf)) {
1395 1396 1397 1398
        cmd->has_error = ENOMEM;
        virBufferFreeAndReset(buf);
        return;
    }
1399 1400 1401 1402
    if (!virBufferUse(buf)) {
        cmd->has_error = EINVAL;
        return;
    }
1403

1404
    virCommandAddEnv(cmd, virBufferContentAndReset(buf));
1405 1406 1407
}


E
Eric Blake 已提交
1408
/**
1409
 * virCommandAddEnvPassAllowSUID:
E
Eric Blake 已提交
1410 1411 1412
 * @cmd: the command to modify
 * @name: the name to look up in current environment
 *
1413 1414
 * Pass an environment variable to the child
 * using current process' value
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
 *
 * Allow to be passed even if setuid
 */
void
virCommandAddEnvPassAllowSUID(virCommandPtr cmd, const char *name)
{
    const char *value;
    if (!cmd || cmd->has_error)
        return;

    value = virGetEnvAllowSUID(name);
    if (value)
        virCommandAddEnvPair(cmd, name, value);
}


/**
 * virCommandAddEnvPassBlockSUID:
 * @cmd: the command to modify
 * @name: the name to look up in current environment
 * @defvalue: value to return if running setuid, may be NULL
 *
 * Pass an environment variable to the child
 * using current process' value.
 *
 * Do not pass if running setuid
1441 1442
 */
void
1443
virCommandAddEnvPassBlockSUID(virCommandPtr cmd, const char *name, const char *defvalue)
1444
{
1445
    const char *value;
1446 1447 1448
    if (!cmd || cmd->has_error)
        return;

1449 1450 1451
    value = virGetEnvBlockSUID(name);
    if (!value)
        value = defvalue;
1452 1453 1454 1455 1456
    if (value)
        virCommandAddEnvPair(cmd, name, value);
}


E
Eric Blake 已提交
1457 1458 1459 1460
/**
 * virCommandAddEnvPassCommon:
 * @cmd: the command to modify
 *
1461
 * Set LC_ALL to C, and propagate other essential environment
E
Eric Blake 已提交
1462
 * variables (such as PATH) from the parent process.
1463 1464 1465 1466
 */
void
virCommandAddEnvPassCommon(virCommandPtr cmd)
{
1467 1468 1469
    if (!cmd || cmd->has_error)
        return;

1470 1471 1472 1473
    if (VIR_RESIZE_N(cmd->env, cmd->maxenv, cmd->nenv, 9) < 0) {
        cmd->has_error = ENOMEM;
        return;
    }
1474 1475 1476

    virCommandAddEnvPair(cmd, "LC_ALL", "C");

1477 1478 1479 1480 1481 1482 1483
    virCommandAddEnvPassBlockSUID(cmd, "LD_PRELOAD", NULL);
    virCommandAddEnvPassBlockSUID(cmd, "LD_LIBRARY_PATH", NULL);
    virCommandAddEnvPassBlockSUID(cmd, "PATH", "/bin:/usr/bin");
    virCommandAddEnvPassBlockSUID(cmd, "HOME", NULL);
    virCommandAddEnvPassAllowSUID(cmd, "USER");
    virCommandAddEnvPassAllowSUID(cmd, "LOGNAME");
    virCommandAddEnvPassBlockSUID(cmd, "TMPDIR", NULL);
1484 1485
}

E
Eric Blake 已提交
1486 1487 1488 1489 1490
/**
 * virCommandAddArg:
 * @cmd: the command to modify
 * @val: the argument to add
 *
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
 * Add a command line argument to the child
 */
void
virCommandAddArg(virCommandPtr cmd, const char *val)
{
    char *arg;

    if (!cmd || cmd->has_error)
        return;

1501 1502 1503 1504 1505 1506
    if (val == NULL) {
        cmd->has_error = EINVAL;
        abort();
        return;
    }

1507
    if (VIR_STRDUP_QUIET(arg, val) < 0) {
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
        cmd->has_error = ENOMEM;
        return;
    }

    /* Arg plus trailing NULL. */
    if (VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, 1 + 1) < 0) {
        VIR_FREE(arg);
        cmd->has_error = ENOMEM;
        return;
    }

    cmd->args[cmd->nargs++] = arg;
}


E
Eric Blake 已提交
1523 1524 1525 1526 1527
/**
 * virCommandAddArgBuffer:
 * @cmd: the command to modify
 * @buf: buffer that contains argument string, which will be reset on return
 *
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
 * Convert a buffer into a command line argument to the child.
 * Correctly transfers memory errors or contents from buf to cmd.
 */
void
virCommandAddArgBuffer(virCommandPtr cmd, virBufferPtr buf)
{
    if (!cmd || cmd->has_error) {
        virBufferFreeAndReset(buf);
        return;
    }

    /* Arg plus trailing NULL. */
    if (virBufferError(buf) ||
        VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, 1 + 1) < 0) {
        cmd->has_error = ENOMEM;
        virBufferFreeAndReset(buf);
        return;
    }

1547 1548
    cmd->args[cmd->nargs] = virBufferContentAndReset(buf);
    if (!cmd->args[cmd->nargs]) {
1549 1550 1551 1552
        if (VIR_STRDUP_QUIET(cmd->args[cmd->nargs], "") < 0) {
            cmd->has_error = ENOMEM;
            return;
        }
1553 1554
    }
    cmd->nargs++;
1555 1556 1557
}


E
Eric Blake 已提交
1558 1559 1560 1561 1562 1563 1564
/**
 * virCommandAddArgFormat:
 * @cmd: the command to modify
 * @format: format of arguments, end result must be in name=value format
 * @...: arguments to be formatted
 *
 * Add a command line argument created by a printf-style format.
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
 */
void
virCommandAddArgFormat(virCommandPtr cmd, const char *format, ...)
{
    char *arg;
    va_list list;

    if (!cmd || cmd->has_error)
        return;

    va_start(list, format);
    if (virVasprintf(&arg, format, list) < 0) {
        cmd->has_error = ENOMEM;
        va_end(list);
        return;
    }
    va_end(list);

    /* Arg plus trailing NULL. */
    if (VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, 1 + 1) < 0) {
        VIR_FREE(arg);
        cmd->has_error = ENOMEM;
        return;
    }

    cmd->args[cmd->nargs++] = arg;
}

E
Eric Blake 已提交
1593 1594 1595 1596 1597 1598
/**
 * virCommandAddArgPair:
 * @cmd: the command to modify
 * @name: left half of argument
 * @value: right half of argument
 *
1599 1600 1601 1602 1603
 * Add "NAME=VAL" as a single command line argument to the child
 */
void
virCommandAddArgPair(virCommandPtr cmd, const char *name, const char *val)
{
1604 1605 1606 1607
    if (name == NULL || val == NULL) {
        cmd->has_error = EINVAL;
        return;
    }
1608 1609 1610
    virCommandAddArgFormat(cmd, "%s=%s", name, val);
}

E
Eric Blake 已提交
1611 1612 1613 1614 1615
/**
 * virCommandAddArgSet:
 * @cmd: the command to modify
 * @vals: array of arguments to add
 *
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
 * Add a NULL terminated list of args
 */
void
virCommandAddArgSet(virCommandPtr cmd, const char *const*vals)
{
    int narg = 0;

    if (!cmd || cmd->has_error)
        return;

1626 1627 1628 1629 1630
    if (vals[0] == NULL) {
        cmd->has_error = EINVAL;
        return;
    }

1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
    while (vals[narg] != NULL)
        narg++;

    /* narg plus trailing NULL. */
    if (VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, narg + 1) < 0) {
        cmd->has_error = ENOMEM;
        return;
    }

    narg = 0;
    while (vals[narg] != NULL) {
1642 1643 1644
        char *arg;

        if (VIR_STRDUP_QUIET(arg, vals[narg++]) < 0) {
1645 1646 1647 1648 1649 1650 1651
            cmd->has_error = ENOMEM;
            return;
        }
        cmd->args[cmd->nargs++] = arg;
    }
}

E
Eric Blake 已提交
1652 1653 1654 1655 1656 1657
/**
 * virCommandAddArgList:
 * @cmd: the command to modify
 * @...: list of arguments to add
 *
 * Add a NULL terminated list of args.
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
 */
void
virCommandAddArgList(virCommandPtr cmd, ...)
{
    va_list list;
    int narg = 0;

    if (!cmd || cmd->has_error)
        return;

    va_start(list, cmd);
    while (va_arg(list, const char *) != NULL)
        narg++;
    va_end(list);

    /* narg plus trailing NULL. */
    if (VIR_RESIZE_N(cmd->args, cmd->maxargs, cmd->nargs, narg + 1) < 0) {
        cmd->has_error = ENOMEM;
        return;
    }

    va_start(list, cmd);
    while (1) {
        char *arg = va_arg(list, char *);
        if (!arg)
            break;
1684
        if (VIR_STRDUP_QUIET(arg, arg) < 0) {
1685 1686 1687 1688 1689 1690 1691 1692 1693
            cmd->has_error = ENOMEM;
            va_end(list);
            return;
        }
        cmd->args[cmd->nargs++] = arg;
    }
    va_end(list);
}

E
Eric Blake 已提交
1694 1695 1696 1697 1698
/**
 * virCommandSetWorkingDirectory:
 * @cmd: the command to modify
 * @pwd: directory to use
 *
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
 * Set the working directory of a non-daemon child process, rather
 * than the parent's working directory.  Daemons automatically get /
 * without using this call.
 */
void
virCommandSetWorkingDirectory(virCommandPtr cmd, const char *pwd)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->pwd) {
        cmd->has_error = -1;
1711
        VIR_DEBUG("cannot set directory twice");
1712
    } else {
1713
        if (VIR_STRDUP_QUIET(cmd->pwd, pwd) < 0)
1714 1715 1716 1717 1718
            cmd->has_error = ENOMEM;
    }
}


E
Eric Blake 已提交
1719 1720 1721 1722 1723
/**
 * virCommandSetInputBuffer:
 * @cmd: the command to modify
 * @inbuf: string to feed to stdin
 *
1724 1725 1726
 * Feed the child's stdin from a string buffer.  This requires the
 * use of virCommandRun() or combination of virCommandDoAsyncIO and
 * virCommandRunAsync. The buffer is forgotten after each @cmd run.
1727 1728 1729 1730 1731 1732 1733 1734 1735
 */
void
virCommandSetInputBuffer(virCommandPtr cmd, const char *inbuf)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->infd != -1 || cmd->inbuf) {
        cmd->has_error = -1;
1736
        VIR_DEBUG("cannot specify input twice");
1737 1738 1739
        return;
    }

1740
    if (VIR_STRDUP_QUIET(cmd->inbuf, inbuf) < 0)
1741 1742 1743 1744
        cmd->has_error = ENOMEM;
}


E
Eric Blake 已提交
1745 1746 1747 1748 1749
/**
 * virCommandSetOutputBuffer:
 * @cmd: the command to modify
 * @outbuf: address of variable to store malloced result buffer
 *
1750 1751 1752
 * Capture the child's stdout to a string buffer.  *outbuf is
 * guaranteed to be allocated after successful virCommandRun or
 * virCommandWait, and is best-effort allocated after failed
1753 1754 1755 1756
 * virCommandRun or virCommandRunAsync; caller is responsible for
 * freeing *outbuf. This requires the use of virCommandRun() or
 * combination of virCommandDoAsyncIO and virCommandRunAsync. The
 * buffer is forgotten after each @cmd run.
1757 1758 1759 1760
 */
void
virCommandSetOutputBuffer(virCommandPtr cmd, char **outbuf)
{
1761
    *outbuf = NULL;
1762 1763 1764 1765 1766
    if (!cmd || cmd->has_error)
        return;

    if (cmd->outfdptr) {
        cmd->has_error = -1;
1767
        VIR_DEBUG("cannot specify output twice");
1768 1769 1770 1771 1772 1773 1774 1775
        return;
    }

    cmd->outbuf = outbuf;
    cmd->outfdptr = &cmd->outfd;
}


E
Eric Blake 已提交
1776 1777 1778 1779 1780
/**
 * virCommandSetErrorBuffer:
 * @cmd: the command to modify
 * @errbuf: address of variable to store malloced result buffer
 *
1781 1782 1783
 * Capture the child's stderr to a string buffer.  *errbuf is
 * guaranteed to be allocated after successful virCommandRun or
 * virCommandWait, and is best-effort allocated after failed
1784 1785 1786 1787 1788 1789 1790
 * virCommandRun or virCommandRunAsync; caller is responsible for
 * freeing *errbuf. It is possible to pass the same pointer as
 * for virCommandSetOutputBuffer(), in which case the child
 * process will interleave all output into a single string.  This
 * requires the use of virCommandRun() or combination of
 * virCommandDoAsyncIO and virCommandRunAsync.The buffer is
 * forgotten after each @cmd run.
1791 1792 1793 1794
 */
void
virCommandSetErrorBuffer(virCommandPtr cmd, char **errbuf)
{
1795
    *errbuf = NULL;
1796 1797 1798 1799 1800
    if (!cmd || cmd->has_error)
        return;

    if (cmd->errfdptr) {
        cmd->has_error = -1;
1801
        VIR_DEBUG("cannot specify stderr twice");
1802 1803 1804 1805 1806 1807 1808 1809
        return;
    }

    cmd->errbuf = errbuf;
    cmd->errfdptr = &cmd->errfd;
}


E
Eric Blake 已提交
1810 1811 1812 1813 1814
/**
 * virCommandSetInputFD:
 * @cmd: the command to modify
 * @infd: the descriptor to use
 *
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
 * Attach a file descriptor to the child's stdin
 */
void
virCommandSetInputFD(virCommandPtr cmd, int infd)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->infd != -1 || cmd->inbuf) {
        cmd->has_error = -1;
1825
        VIR_DEBUG("cannot specify input twice");
1826 1827 1828 1829
        return;
    }
    if (infd < 0) {
        cmd->has_error = -1;
1830
        VIR_DEBUG("cannot specify invalid input fd");
1831 1832 1833 1834 1835 1836 1837
        return;
    }

    cmd->infd = infd;
}


E
Eric Blake 已提交
1838 1839 1840 1841 1842 1843 1844 1845
/**
 * virCommandSetOutputFD:
 * @cmd: the command to modify
 * @outfd: location of output fd
 *
 * Attach a file descriptor to the child's stdout.  If *@outfd is -1 on
 * entry, then a pipe will be created and returned in this variable when
 * the child is run.  Otherwise, *@outfd is used as the output.
1846 1847 1848 1849 1850 1851 1852 1853 1854
 */
void
virCommandSetOutputFD(virCommandPtr cmd, int *outfd)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->outfdptr) {
        cmd->has_error = -1;
1855
        VIR_DEBUG("cannot specify output twice");
1856 1857 1858 1859 1860 1861 1862
        return;
    }

    cmd->outfdptr = outfd;
}


E
Eric Blake 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871
/**
 * virCommandSetErrorFD:
 * @cmd: the command to modify
 * @errfd: location of error fd
 *
 * Attach a file descriptor to the child's stderr.  If *@errfd is -1 on
 * entry, then a pipe will be created and returned in this variable when
 * the child is run.  Otherwise, *@errfd is used for error collection,
 * and may be the same as outfd given to virCommandSetOutputFD().
1872 1873 1874 1875 1876 1877 1878 1879 1880
 */
void
virCommandSetErrorFD(virCommandPtr cmd, int *errfd)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->errfdptr) {
        cmd->has_error = -1;
1881
        VIR_DEBUG("cannot specify stderr twice");
1882 1883 1884 1885 1886 1887 1888
        return;
    }

    cmd->errfdptr = errfd;
}


E
Eric Blake 已提交
1889 1890 1891 1892 1893 1894
/**
 * virCommandSetPreExecHook:
 * @cmd: the command to modify
 * @hook: the hook to run
 * @opaque: argument to pass to the hook
 *
1895 1896 1897
 * Run HOOK(OPAQUE) in the child as the last thing before changing
 * directories, dropping capabilities, and executing the new process.
 * Force the child to fail if HOOK does not return zero.
E
Eric Blake 已提交
1898 1899 1900
 *
 * Since @hook runs in the child, it should be careful to avoid
 * any functions that are not async-signal-safe.
1901 1902 1903 1904 1905 1906 1907 1908 1909
 */
void
virCommandSetPreExecHook(virCommandPtr cmd, virExecHook hook, void *opaque)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->hook) {
        cmd->has_error = -1;
1910
        VIR_DEBUG("cannot specify hook twice");
1911 1912 1913 1914 1915 1916 1917
        return;
    }
    cmd->hook = hook;
    cmd->opaque = opaque;
}


E
Eric Blake 已提交
1918 1919 1920 1921 1922
/**
 * virCommandWriteArgLog:
 * @cmd: the command to log
 * @logfd: where to log the results
 *
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
 * Call after adding all arguments and environment settings, but before
 * Run/RunAsync, to immediately output the environment and arguments of
 * cmd to logfd.  If virCommandRun cannot succeed (because of an
 * out-of-memory condition while building cmd), nothing will be logged.
 */
void
virCommandWriteArgLog(virCommandPtr cmd, int logfd)
{
    int ioError = 0;
    size_t i;

    /* Any errors will be reported later by virCommandRun, which means
     * no command will be run, so there is nothing to log. */
    if (!cmd || cmd->has_error)
        return;

1939
    for (i = 0; i < cmd->nenv; i++) {
1940 1941 1942 1943 1944
        if (safewrite(logfd, cmd->env[i], strlen(cmd->env[i])) < 0)
            ioError = errno;
        if (safewrite(logfd, " ", 1) < 0)
            ioError = errno;
    }
1945
    for (i = 0; i < cmd->nargs; i++) {
1946 1947 1948 1949 1950 1951 1952 1953 1954
        if (safewrite(logfd, cmd->args[i], strlen(cmd->args[i])) < 0)
            ioError = errno;
        if (safewrite(logfd, i == cmd->nargs - 1 ? "\n" : " ", 1) < 0)
            ioError = errno;
    }

    if (ioError) {
        char ebuf[1024];
        VIR_WARN("Unable to write command %s args to logfile: %s",
1955
                 cmd->args[0], virStrerror(ioError, ebuf, sizeof(ebuf)));
1956 1957 1958 1959
    }
}


E
Eric Blake 已提交
1960 1961 1962
/**
 * virCommandToString:
 * @cmd: the command to convert
1963
 * @linebreaks: true to break line after each env var or option
E
Eric Blake 已提交
1964
 *
1965 1966 1967 1968
 * Call after adding all arguments and environment settings, but
 * before Run/RunAsync, to return a string representation of the
 * environment and arguments of cmd, suitably quoted for pasting into
 * a shell.  If virCommandRun cannot succeed (because of an
1969 1970 1971 1972
 * out-of-memory condition while building cmd), NULL will be returned.
 * Caller is responsible for freeing the resulting string.
 */
char *
1973
virCommandToString(virCommandPtr cmd, bool linebreaks)
1974 1975 1976
{
    size_t i;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1977
    bool prevopt = false;
1978 1979 1980

    /* Cannot assume virCommandRun will be called; so report the error
     * now.  If virCommandRun is called, it will report the same error. */
1981 1982
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
1983 1984
        return NULL;
    }
1985
    if (cmd->has_error) {
1986 1987
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid use of command API"));
1988 1989 1990 1991
        return NULL;
    }

    for (i = 0; i < cmd->nenv; i++) {
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
        /* In shell, a='b c' has a different meaning than 'a=b c', so
         * we must determine where the '=' lives.  */
        char *eq = strchr(cmd->env[i], '=');

        if (!eq) {
            virBufferFreeAndReset(&buf);
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("invalid use of command API"));
            return NULL;
        }
        eq++;
        virBufferAdd(&buf, cmd->env[i], eq - cmd->env[i]);
        virBufferEscapeShell(&buf, eq);
2005
        virBufferAddChar(&buf, ' ');
2006 2007
        if (linebreaks)
            virBufferAddLit(&buf, "\\\n");
2008
    }
2009
    virBufferEscapeShell(&buf, cmd->args[0]);
2010 2011
    for (i = 1; i < cmd->nargs; i++) {
        virBufferAddChar(&buf, ' ');
2012 2013 2014 2015 2016 2017 2018 2019
        if (linebreaks) {
            /* Line break if this is a --arg or if
             * the previous arg was a positional option
             */
            if (cmd->args[i][0] == '-' ||
                !prevopt)
                virBufferAddLit(&buf, "\\\n");
        }
2020
        virBufferEscapeShell(&buf, cmd->args[i]);
2021
        prevopt = (cmd->args[i][0] == '-');
2022 2023
    }

2024
    if (virBufferCheckError(&buf) < 0)
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
        return NULL;

    return virBufferContentAndReset(&buf);
}


/*
 * Manage input and output to the child process.
 */
static int
2035
virCommandProcessIO(virCommandPtr cmd)
2036
{
2037
    int outfd = -1, errfd = -1;
2038 2039
    size_t inlen = 0, outlen = 0, errlen = 0;
    size_t inoff = 0;
2040
    int ret = 0;
2041

2042 2043 2044 2045 2046
    if (dryRunBuffer || dryRunCallback) {
        VIR_DEBUG("Dry run requested, skipping I/O processing");
        return 0;
    }

2047 2048
    /* With an input buffer, feed data to child
     * via pipe */
2049
    if (cmd->inbuf)
2050 2051
        inlen = strlen(cmd->inbuf);

2052 2053 2054 2055 2056
    /* With out/err buffer, the outfd/errfd have been filled with an
     * FD for us.  Guarantee an allocated string with partial results
     * even if we encounter a later failure, as well as freeing any
     * results accumulated over a prior run of the same command.  */
    if (cmd->outbuf) {
2057
        outfd = cmd->outfd;
2058 2059
        VIR_FREE(*cmd->outbuf);
        if (VIR_ALLOC_N(*cmd->outbuf, 1) < 0)
2060 2061 2062
            ret = -1;
    }
    if (cmd->errbuf) {
2063
        errfd = cmd->errfd;
2064 2065
        VIR_FREE(*cmd->errbuf);
        if (VIR_ALLOC_N(*cmd->errbuf, 1) < 0)
2066 2067 2068 2069 2070
            ret = -1;
    }
    if (ret == -1)
        goto cleanup;
    ret = -1;
2071 2072

    for (;;) {
2073
        size_t i;
2074 2075 2076
        struct pollfd fds[3];
        int nfds = 0;

2077 2078
        if (cmd->inpipe != -1) {
            fds[nfds].fd = cmd->inpipe;
2079
            fds[nfds].events = POLLOUT;
2080
            fds[nfds].revents = 0;
2081 2082 2083 2084 2085
            nfds++;
        }
        if (outfd != -1) {
            fds[nfds].fd = outfd;
            fds[nfds].events = POLLIN;
2086
            fds[nfds].revents = 0;
2087 2088 2089 2090 2091
            nfds++;
        }
        if (errfd != -1) {
            fds[nfds].fd = errfd;
            fds[nfds].events = POLLIN;
2092
            fds[nfds].revents = 0;
2093 2094 2095 2096 2097 2098 2099
            nfds++;
        }

        if (nfds == 0)
            break;

        if (poll(fds, nfds, -1) < 0) {
2100
            if (errno == EAGAIN || errno == EINTR)
2101 2102 2103
                continue;
            virReportSystemError(errno, "%s",
                                 _("unable to poll on child"));
2104
            goto cleanup;
2105 2106
        }

2107
        for (i = 0; i < nfds; i++) {
2108
            if (fds[i].revents & (POLLIN | POLLHUP | POLLERR) &&
2109
                (fds[i].fd == errfd || fds[i].fd == outfd)) {
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
                char data[1024];
                char **buf;
                size_t *len;
                int done;
                if (fds[i].fd == outfd) {
                    buf = cmd->outbuf;
                    len = &outlen;
                } else {
                    buf = cmd->errbuf;
                    len = &errlen;
                }
2121 2122
                /* Silence a false positive from clang. */
                sa_assert(buf);
2123 2124 2125 2126 2127 2128

                done = read(fds[i].fd, data, sizeof(data));
                if (done < 0) {
                    if (errno != EINTR &&
                        errno != EAGAIN) {
                        virReportSystemError(errno, "%s",
2129 2130 2131
                                             (fds[i].fd == outfd) ?
                                             _("unable to read child stdout") :
                                             _("unable to read child stderr"));
2132
                        goto cleanup;
2133 2134 2135 2136 2137 2138 2139
                    }
                } else if (done == 0) {
                    if (fds[i].fd == outfd)
                        outfd = -1;
                    else
                        errfd = -1;
                } else {
2140
                    if (VIR_REALLOC_N(*buf, *len + done + 1) < 0)
2141
                        goto cleanup;
2142 2143 2144
                    memcpy(*buf + *len, data, done);
                    *len += done;
                }
2145 2146
            }

2147
            if (fds[i].revents & (POLLOUT | POLLHUP | POLLERR) &&
2148
                fds[i].fd == cmd->inpipe) {
2149 2150
                int done;

2151
                done = write(cmd->inpipe, cmd->inbuf + inoff,
2152 2153
                             inlen - inoff);
                if (done < 0) {
2154 2155
                    if (errno == EPIPE) {
                        VIR_DEBUG("child closed stdin early, ignoring EPIPE "
2156 2157
                                  "on fd %d", cmd->inpipe);
                        VIR_FORCE_CLOSE(cmd->inpipe);
2158
                    } else if (errno != EINTR && errno != EAGAIN) {
2159 2160
                        virReportSystemError(errno, "%s",
                                             _("unable to write to child input"));
2161
                        goto cleanup;
2162 2163 2164
                    }
                } else {
                    inoff += done;
2165 2166
                    if (inoff == inlen)
                        VIR_FORCE_CLOSE(cmd->inpipe);
2167 2168 2169 2170 2171
                }
            }
        }
    }

2172
    ret = 0;
2173
 cleanup:
2174
    if (cmd->outbuf && *cmd->outbuf)
2175
        (*cmd->outbuf)[outlen] = '\0';
2176
    if (cmd->errbuf && *cmd->errbuf)
2177 2178
        (*cmd->errbuf)[errlen] = '\0';
    return ret;
2179 2180
}

E
Eric Blake 已提交
2181 2182 2183
/**
 * virCommandExec:
 * @cmd: command to run
M
Marc Hartmayer 已提交
2184 2185
 * @groups: array of supplementary group IDs used for the command
 * @ngroups: number of group IDs in @groups
E
Eric Blake 已提交
2186
 *
2187
 * Exec the command, replacing the current process. Meant to be called
E
Eric Blake 已提交
2188 2189
 * in the hook after already forking / cloning, so does not attempt to
 * daemonize or preserve any FDs.
2190 2191 2192 2193
 *
 * Returns -1 on any error executing the command.
 * Will not return on success.
 */
2194
#ifndef WIN32
M
Marc Hartmayer 已提交
2195
int virCommandExec(virCommandPtr cmd, gid_t *groups, int ngroups)
2196 2197 2198 2199 2200 2201
{
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
        return -1;
    }
    if (cmd->has_error) {
2202 2203
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid use of command API"));
2204 2205 2206
        return -1;
    }

M
Marc Hartmayer 已提交
2207
    if (virExecCommon(cmd, groups, ngroups) < 0)
2208 2209
        return -1;

2210 2211 2212 2213 2214 2215
    execve(cmd->args[0], cmd->args, cmd->env);

    virReportSystemError(errno,
                         _("cannot execute binary %s"),
                         cmd->args[0]);
    return -1;
2216
}
2217
#else
M
Marc Hartmayer 已提交
2218 2219
int virCommandExec(virCommandPtr cmd ATTRIBUTE_UNUSED, gid_t *groups ATTRIBUTE_UNUSED,
                   int ngroups ATTRIBUTE_UNUSED)
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
{
    /* Mingw execve() has a broken signature. Disable this
     * function until gnulib fixes the signature, since we
     * don't really need this on Win32 anyway.
     */
    virReportSystemError(ENOSYS, "%s",
                         _("Executing new processes is not supported on Win32 platform"));
    return -1;
}
#endif
2230

E
Eric Blake 已提交
2231 2232 2233 2234 2235
/**
 * virCommandRun:
 * @cmd: command to run
 * @exitstatus: optional status collection
 *
2236 2237 2238
 * Run the command and wait for completion.
 * Returns -1 on any error executing the
 * command. Returns 0 if the command executed,
E
Eric Blake 已提交
2239
 * with the exit status set.  If @exitstatus is NULL, then the
2240 2241 2242 2243 2244
 * child must exit with status 0 for this to succeed.  By default,
 * a non-NULL @exitstatus contains the normal exit status of the child
 * (death from a signal is treated as execution error); but if
 * virCommandRawStatus() was used, it instead contains the raw exit
 * status that the caller must then decipher using WIFEXITED() and friends.
2245 2246 2247 2248 2249 2250 2251
 */
int
virCommandRun(virCommandPtr cmd, int *exitstatus)
{
    int ret = 0;
    char *outbuf = NULL;
    char *errbuf = NULL;
2252 2253 2254
    struct stat st;
    bool string_io;
    bool async_io = false;
2255
    char *str;
2256
    int tmpfd;
2257

2258 2259
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
2260 2261
        return -1;
    }
2262
    if (cmd->has_error) {
2263 2264
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid use of command API"));
2265 2266 2267
        return -1;
    }

2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
    /* Avoid deadlock, by requiring that any open fd not under our
     * control must be visiting a regular file, or that we are
     * daemonized and no string io is required.  */
    string_io = cmd->inbuf || cmd->outbuf || cmd->errbuf;
    if (cmd->infd != -1 &&
        (fstat(cmd->infd, &st) < 0 || !S_ISREG(st.st_mode)))
        async_io = true;
    if (cmd->outfdptr && cmd->outfdptr != &cmd->outfd &&
        (*cmd->outfdptr == -1 ||
         fstat(*cmd->outfdptr, &st) < 0 || !S_ISREG(st.st_mode)))
        async_io = true;
    if (cmd->errfdptr && cmd->errfdptr != &cmd->errfd &&
        (*cmd->errfdptr == -1 ||
         fstat(*cmd->errfdptr, &st) < 0 || !S_ISREG(st.st_mode)))
        async_io = true;
    if (async_io) {
        if (!(cmd->flags & VIR_EXEC_DAEMON) || string_io) {
2285 2286
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot mix caller fds with blocking execution"));
2287 2288 2289 2290
            return -1;
        }
    } else {
        if ((cmd->flags & VIR_EXEC_DAEMON) && string_io) {
2291 2292
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot mix string I/O with daemon"));
2293 2294 2295 2296
            return -1;
        }
    }

2297 2298 2299 2300 2301 2302 2303
    /* If caller requested the same string for stdout and stderr, then
     * merge those into one string.  */
    if (cmd->outbuf && cmd->outbuf == cmd->errbuf) {
        cmd->errfdptr = &cmd->outfd;
        cmd->errbuf = NULL;
    }

2304
    /* If caller hasn't requested capture of stdout/err, then capture
2305 2306 2307
     * it ourselves so we can log it.  But the intermediate child for
     * a daemon has no expected output, and we don't want our
     * capturing pipes passed on to the daemon grandchild.
2308
     */
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
    if (!(cmd->flags & VIR_EXEC_DAEMON)) {
        if (!cmd->outfdptr) {
            cmd->outfdptr = &cmd->outfd;
            cmd->outbuf = &outbuf;
            string_io = true;
        }
        if (!cmd->errfdptr) {
            cmd->errfdptr = &cmd->errfd;
            cmd->errbuf = &errbuf;
            string_io = true;
        }
2320 2321
    }

2322
    cmd->flags |= VIR_EXEC_RUN_SYNC;
2323 2324 2325 2326 2327
    if (virCommandRunAsync(cmd, NULL) < 0) {
        cmd->has_error = -1;
        return -1;
    }

2328 2329 2330 2331
    if (string_io) {
        VIR_FORCE_CLOSE(cmd->infd);
        ret = virCommandProcessIO(cmd);
    }
2332 2333 2334 2335

    if (virCommandWait(cmd, exitstatus) < 0)
        ret = -1;

2336
    str = (exitstatus ? virProcessTranslateStatus(*exitstatus)
2337 2338 2339
           : (char *) "status 0");
    VIR_DEBUG("Result %s, stdout: '%s' stderr: '%s'",
              NULLSTR(str),
2340 2341
              cmd->outbuf ? NULLSTR(*cmd->outbuf) : "(null)",
              cmd->errbuf ? NULLSTR(*cmd->errbuf) : "(null)");
2342 2343
    if (exitstatus)
        VIR_FREE(str);
2344 2345 2346

    /* Reset any capturing, in case caller runs
     * this identical command again */
2347
    VIR_FORCE_CLOSE(cmd->inpipe);
2348
    if (cmd->outbuf == &outbuf) {
2349
        tmpfd = cmd->outfd;
2350 2351 2352 2353
        if (VIR_CLOSE(cmd->outfd) < 0)
            VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
        cmd->outfdptr = NULL;
        cmd->outbuf = NULL;
E
Eric Blake 已提交
2354
        VIR_FREE(outbuf);
2355 2356
    }
    if (cmd->errbuf == &errbuf) {
2357
        tmpfd = cmd->errfd;
2358 2359 2360 2361
        if (VIR_CLOSE(cmd->errfd) < 0)
            VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
        cmd->errfdptr = NULL;
        cmd->errbuf = NULL;
E
Eric Blake 已提交
2362
        VIR_FREE(errbuf);
2363 2364 2365 2366 2367 2368
    }

    return ret;
}


2369
static void
2370
virCommandDoAsyncIOHelper(void *opaque)
2371
{
2372 2373 2374 2375
    virCommandPtr cmd = opaque;
    if (virCommandProcessIO(cmd) < 0) {
        /* If something went wrong, save errno or -1*/
        cmd->has_error = errno ? errno : -1;
2376 2377 2378 2379
    }
}


E
Eric Blake 已提交
2380 2381 2382 2383 2384
/**
 * virCommandRunAsync:
 * @cmd: command to start
 * @pid: optional variable to track child pid
 *
2385 2386 2387
 * Run the command asynchronously
 * Returns -1 on any error executing the
 * command. Returns 0 if the command executed.
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
 *
 * There are two approaches to child process cleanup.
 * 1. Use auto-cleanup, by passing NULL for pid.  The child will be
 * auto-reaped by virCommandFree, unless you reap it earlier via
 * virCommandWait or virCommandAbort.  Good for where cmd is in
 * scope for the duration of the child process.
 * 2. Use manual cleanup, by passing the address of a pid_t variable
 * for pid.  While cmd is still in scope, you may reap the child via
 * virCommandWait or virCommandAbort.  But after virCommandFree, if
 * you have not yet reaped the child, then it continues to run until
2398
 * you call virProcessWait or virProcessAbort.
2399 2400 2401 2402
 */
int
virCommandRunAsync(virCommandPtr cmd, pid_t *pid)
{
2403
    int ret = -1;
2404
    VIR_AUTOFREE(char *) str = NULL;
2405
    size_t i;
2406
    bool synchronous = false;
2407
    int infd[2] = {-1, -1};
2408

2409 2410
    if (!cmd || cmd->has_error == ENOMEM) {
        virReportOOMError();
2411 2412
        return -1;
    }
2413
    if (cmd->has_error) {
2414 2415
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid use of command API"));
2416 2417 2418
        return -1;
    }

2419 2420 2421
    synchronous = cmd->flags & VIR_EXEC_RUN_SYNC;
    cmd->flags &= ~VIR_EXEC_RUN_SYNC;

2422 2423 2424 2425 2426 2427 2428 2429 2430
    /* Buffer management can only be requested via virCommandRun or
     * virCommandDoAsyncIO. */
    if (cmd->inbuf && cmd->infd == -1 &&
        (synchronous || cmd->flags & VIR_EXEC_ASYNC_IO)) {
        if (pipe2(infd, O_CLOEXEC) < 0) {
            virReportSystemError(errno, "%s",
                                 _("unable to open pipe"));
            cmd->has_error = -1;
            return -1;
2431
        }
2432 2433
        cmd->infd = infd[0];
        cmd->inpipe = infd[1];
2434
    } else if ((cmd->inbuf && cmd->infd == -1) ||
2435 2436
               (cmd->outbuf && cmd->outfdptr != &cmd->outfd) ||
               (cmd->errbuf && cmd->errfdptr != &cmd->errfd)) {
2437 2438
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot mix string I/O with asynchronous command"));
2439 2440 2441
        return -1;
    }

2442
    if (cmd->pid != -1) {
2443 2444 2445
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("command is already running as pid %lld"),
                       (long long) cmd->pid);
2446
        goto cleanup;
2447 2448
    }

2449
    if (!synchronous && (cmd->flags & VIR_EXEC_DAEMON)) {
2450 2451
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("daemonized command cannot use virCommandRunAsync"));
2452
        goto cleanup;
2453
    }
2454
    if (cmd->pwd && (cmd->flags & VIR_EXEC_DAEMON)) {
2455 2456 2457
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("daemonized command cannot set working directory %s"),
                       cmd->pwd);
2458
        goto cleanup;
2459
    }
2460
    if (cmd->pidfile && !(cmd->flags & VIR_EXEC_DAEMON)) {
2461 2462
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("creation of pid file requires daemonized command"));
2463
        goto cleanup;
2464
    }
2465

2466
    str = virCommandToString(cmd, false);
2467 2468
    if (dryRunBuffer || dryRunCallback) {
        dryRunStatus = 0;
2469 2470 2471 2472 2473
        if (!str) {
            /* error already reported by virCommandToString */
            goto cleanup;
        }

2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
        if (dryRunBuffer) {
            VIR_DEBUG("Dry run requested, appending stringified "
                      "command to dryRunBuffer=%p", dryRunBuffer);
            virBufferAdd(dryRunBuffer, str, -1);
            virBufferAddChar(dryRunBuffer, '\n');
        }
        if (dryRunCallback) {
            dryRunCallback((const char *const*)cmd->args,
                           (const char *const*)cmd->env,
                           cmd->inbuf, cmd->outbuf, cmd->errbuf,
                           &dryRunStatus, dryRunOpaque);
        }
2486 2487 2488
        ret = 0;
        goto cleanup;
    }
2489

2490
    VIR_DEBUG("About to run %s", str ? str : cmd->args[0]);
2491
    ret = virExec(cmd);
2492 2493 2494
    VIR_DEBUG("Command result %d, with PID %d",
              ret, (int)cmd->pid);

2495 2496 2497
    for (i = 0; i < cmd->npassfd; i++) {
        if (cmd->passfd[i].flags & VIR_COMMAND_PASS_FD_CLOSE_PARENT)
            VIR_FORCE_CLOSE(cmd->passfd[i].fd);
2498
    }
2499 2500
    cmd->npassfd = 0;
    VIR_FREE(cmd->passfd);
2501 2502 2503

    if (ret == 0 && pid)
        *pid = cmd->pid;
2504 2505
    else
        cmd->reap = true;
2506

2507
    if (ret == 0 && cmd->flags & VIR_EXEC_ASYNC_IO) {
2508
        if (cmd->inbuf)
2509
            VIR_FORCE_CLOSE(cmd->infd);
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
        /* clear any error so we can catch if the helper thread reports one */
        cmd->has_error = 0;
        if (VIR_ALLOC(cmd->asyncioThread) < 0 ||
            virThreadCreate(cmd->asyncioThread, true,
                            virCommandDoAsyncIOHelper, cmd) < 0) {
            virReportSystemError(errno, "%s",
                                 _("Unable to create thread "
                                   "to process command's IO"));
            VIR_FREE(cmd->asyncioThread);
            virCommandAbort(cmd);
            ret = -1;
2521 2522 2523
        }
    }

2524
 cleanup:
2525 2526 2527 2528
    if (ret < 0) {
        VIR_FORCE_CLOSE(cmd->infd);
        VIR_FORCE_CLOSE(cmd->inpipe);
    }
2529 2530 2531 2532
    return ret;
}


E
Eric Blake 已提交
2533 2534 2535 2536 2537 2538 2539
/**
 * virCommandWait:
 * @cmd: command to wait on
 * @exitstatus: optional status collection
 *
 * Wait for the command previously started with virCommandRunAsync()
 * to complete. Return -1 on any error waiting for
2540
 * completion. Returns 0 if the command
E
Eric Blake 已提交
2541
 * finished with the exit status set.  If @exitstatus is NULL, then the
2542 2543 2544 2545 2546
 * child must exit with status 0 for this to succeed.  By default,
 * a non-NULL @exitstatus contains the normal exit status of the child
 * (death from a signal is treated as execution error); but if
 * virCommandRawStatus() was used, it instead contains the raw exit
 * status that the caller must then decipher using WIFEXITED() and friends.
2547 2548 2549 2550 2551
 */
int
virCommandWait(virCommandPtr cmd, int *exitstatus)
{
    int ret;
2552
    int status = 0;
2553

2554 2555
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
2556 2557
        return -1;
    }
2558
    if (cmd->has_error) {
2559 2560
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid use of command API"));
2561 2562 2563
        return -1;
    }

2564 2565 2566
    if (dryRunBuffer || dryRunCallback) {
        VIR_DEBUG("Dry run requested, returning status %d",
                  dryRunStatus);
2567
        if (exitstatus)
2568
            *exitstatus = dryRunStatus;
2569 2570
        else if (dryRunStatus)
            return -1;
2571 2572 2573
        return 0;
    }

2574
    if (cmd->pid == -1) {
2575 2576
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("command is not yet running"));
2577 2578 2579
        return -1;
    }

2580
    /* If virProcessWait reaps pid but then returns failure because
2581 2582 2583
     * exitstatus was NULL, then a second virCommandWait would risk
     * calling waitpid on an unrelated process.  Besides, that error
     * message is not as detailed as what we can provide.  So, we
2584
     * guarantee that virProcessWait only fails due to failure to wait,
2585
     * and repeat the exitstatus check code ourselves.  */
2586
    ret = virProcessWait(cmd->pid, &status, true);
2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
    if (cmd->flags & VIR_EXEC_ASYNC_IO) {
        cmd->flags &= ~VIR_EXEC_ASYNC_IO;
        virThreadJoin(cmd->asyncioThread);
        VIR_FREE(cmd->asyncioThread);
        VIR_FORCE_CLOSE(cmd->inpipe);
        if (cmd->has_error) {
            const char *msg = _("Error while processing command's IO");
            if (cmd->has_error < 0)
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s", msg);
            else
                virReportSystemError(cmd->has_error, "%s", msg);
            ret = -1;
        }
2600
    }
2601 2602 2603
    if (ret == 0) {
        cmd->pid = -1;
        cmd->reap = false;
2604 2605 2606
        if (exitstatus && (cmd->rawStatus || WIFEXITED(status))) {
            *exitstatus = cmd->rawStatus ? status : WEXITSTATUS(status);
        } else if (status) {
2607
            VIR_AUTOFREE(char *) str = virCommandToString(cmd, false);
2608
            VIR_AUTOFREE(char *) st = virProcessTranslateStatus(status);
2609 2610
            bool haveErrMsg = cmd->errbuf && *cmd->errbuf && (*cmd->errbuf)[0];

2611
            virReportError(VIR_ERR_INTERNAL_ERROR,
2612 2613 2614 2615
                           _("Child process (%s) unexpected %s%s%s"),
                           str ? str : cmd->args[0], NULLSTR(st),
                           haveErrMsg ? ": " : "",
                           haveErrMsg ? *cmd->errbuf : "");
2616 2617 2618 2619
            return -1;
        }
    }

2620
    return ret;
2621 2622 2623
}


E
Eric Blake 已提交
2624
#ifndef WIN32
E
Eric Blake 已提交
2625 2626 2627 2628
/**
 * virCommandAbort:
 * @cmd: command to abort
 *
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
 * Abort an async command if it is running, without issuing
 * any errors or affecting errno.  Designed for error paths
 * where some but not all paths to the cleanup code might
 * have started the child process.
 */
void
virCommandAbort(virCommandPtr cmd)
{
    if (!cmd || cmd->pid == -1)
        return;
2639
    virProcessAbort(cmd->pid);
2640 2641 2642
    cmd->pid = -1;
    cmd->reap = false;
}
E
Eric Blake 已提交
2643 2644 2645 2646 2647
#else /* WIN32 */
void
virCommandAbort(virCommandPtr cmd ATTRIBUTE_UNUSED)
{
    /* Mingw lacks WNOHANG and kill().  But since we haven't ported
2648
     * virExec to mingw yet, there's no process to be killed,
E
Eric Blake 已提交
2649 2650 2651
     * making this implementation trivially correct for now :)  */
}
#endif
2652

2653

E
Eric Blake 已提交
2654 2655 2656 2657 2658 2659 2660 2661 2662
/**
 * virCommandRequireHandshake:
 * @cmd: command to modify
 *
 * Request that the child perform a handshake with
 * the parent when the hook function has completed
 * execution. The child will not exec() until the
 * parent has notified
 */
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
void virCommandRequireHandshake(virCommandPtr cmd)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->handshake) {
        cmd->has_error = -1;
        VIR_DEBUG("Cannot require handshake twice");
        return;
    }

2674
    if (pipe2(cmd->handshakeWait, O_CLOEXEC) < 0) {
2675 2676 2677
        cmd->has_error = errno;
        return;
    }
2678
    if (pipe2(cmd->handshakeNotify, O_CLOEXEC) < 0) {
2679 2680 2681 2682 2683 2684
        VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
        VIR_FORCE_CLOSE(cmd->handshakeWait[1]);
        cmd->has_error = errno;
        return;
    }

2685 2686 2687 2688
    VIR_DEBUG("Transfer handshake wait=%d notify=%d, "
              "keep handshake wait=%d notify=%d",
              cmd->handshakeWait[1], cmd->handshakeNotify[0],
              cmd->handshakeWait[0], cmd->handshakeNotify[1]);
2689 2690 2691 2692
    virCommandPassFD(cmd, cmd->handshakeWait[1],
                     VIR_COMMAND_PASS_FD_CLOSE_PARENT);
    virCommandPassFD(cmd, cmd->handshakeNotify[0],
                     VIR_COMMAND_PASS_FD_CLOSE_PARENT);
2693 2694 2695
    cmd->handshake = true;
}

E
Eric Blake 已提交
2696 2697 2698 2699 2700 2701 2702
/**
 * virCommandHandshakeWait:
 * @cmd: command to wait on
 *
 * Wait for the child to complete execution of its
 * hook function.  To be called in the parent.
 */
2703 2704 2705 2706 2707 2708 2709 2710 2711
int virCommandHandshakeWait(virCommandPtr cmd)
{
    char c;
    int rv;
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
        return -1;
    }
    if (cmd->has_error || !cmd->handshake) {
2712 2713
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid use of command API"));
2714 2715 2716 2717
        return -1;
    }

    if (cmd->handshakeWait[0] == -1) {
2718 2719
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Handshake is already complete"));
2720 2721 2722 2723 2724 2725
        return -1;
    }

    VIR_DEBUG("Wait for handshake on %d", cmd->handshakeWait[0]);
    if ((rv = saferead(cmd->handshakeWait[0], &c, sizeof(c))) != sizeof(c)) {
        if (rv < 0)
2726 2727
            virReportSystemError(errno, "%s",
                                 _("Unable to wait for child process"));
2728
        else
2729 2730
            virReportSystemError(EIO, "%s",
                                 _("Child quit during startup handshake"));
2731 2732 2733 2734
        VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
        return -1;
    }
    if (c != '1') {
2735
        VIR_AUTOFREE(char *) msg = NULL;
2736 2737 2738 2739 2740
        ssize_t len;
        if (VIR_ALLOC_N(msg, 1024) < 0) {
            VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
            return -1;
        }
2741 2742 2743 2744 2745
        /* Close the handshakeNotify fd before trying to read anything
         * further on the handshakeWait pipe; so that a child waiting
         * on our acknowledgment will die rather than deadlock.  */
        VIR_FORCE_CLOSE(cmd->handshakeNotify[1]);

2746 2747
        if ((len = saferead(cmd->handshakeWait[0], msg, 1024)) < 0) {
            VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
2748 2749
            virReportSystemError(errno, "%s",
                                 _("No error message from child failure"));
2750 2751 2752 2753
            return -1;
        }
        VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
        msg[len-1] = '\0';
2754
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", msg);
2755 2756 2757 2758 2759 2760
        return -1;
    }
    VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
    return 0;
}

E
Eric Blake 已提交
2761 2762 2763 2764 2765 2766 2767
/**
 * virCommandHandshakeNotify:
 * @cmd: command to resume
 *
 * Notify the child that it is OK to exec() the
 * real binary now.  To be called in the parent.
 */
2768 2769 2770 2771 2772 2773 2774 2775
int virCommandHandshakeNotify(virCommandPtr cmd)
{
    char c = '1';
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
        return -1;
    }
    if (cmd->has_error || !cmd->handshake) {
2776 2777
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid use of command API"));
2778 2779 2780 2781
        return -1;
    }

    if (cmd->handshakeNotify[1] == -1) {
2782 2783
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Handshake is already complete"));
2784 2785 2786
        return -1;
    }

2787
    VIR_DEBUG("Notify handshake on %d", cmd->handshakeNotify[1]);
2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
    if (safewrite(cmd->handshakeNotify[1], &c, sizeof(c)) != sizeof(c)) {
        virReportSystemError(errno, "%s", _("Unable to notify child process"));
        VIR_FORCE_CLOSE(cmd->handshakeNotify[1]);
        return -1;
    }
    VIR_FORCE_CLOSE(cmd->handshakeNotify[1]);
    return 0;
}


E
Eric Blake 已提交
2798 2799 2800 2801
/**
 * virCommandFree:
 * @cmd: optional command to free
 *
2802 2803
 * Release all resources.  The only exception is that if you called
 * virCommandRunAsync with a non-null pid, then the asynchronous child
2804
 * is not reaped, and you must call virProcessWait() or virProcessAbort() yourself.
2805 2806 2807 2808
 */
void
virCommandFree(virCommandPtr cmd)
{
2809
    size_t i;
2810 2811 2812
    if (!cmd)
        return;

2813 2814 2815
    for (i = 0; i < cmd->npassfd; i++) {
        if (cmd->passfd[i].flags & VIR_COMMAND_PASS_FD_CLOSE_PARENT)
            VIR_FORCE_CLOSE(cmd->passfd[i].fd);
2816
    }
2817 2818
    cmd->npassfd = 0;
    VIR_FREE(cmd->passfd);
2819

2820 2821 2822 2823
    if (cmd->asyncioThread) {
        virThreadJoin(cmd->asyncioThread);
        VIR_FREE(cmd->asyncioThread);
    }
E
Eric Blake 已提交
2824
    VIR_FREE(cmd->inbuf);
2825 2826 2827
    VIR_FORCE_CLOSE(cmd->outfd);
    VIR_FORCE_CLOSE(cmd->errfd);

2828
    for (i = 0; i < cmd->nargs; i++)
2829 2830 2831
        VIR_FREE(cmd->args[i]);
    VIR_FREE(cmd->args);

2832
    for (i = 0; i < cmd->nenv; i++)
2833 2834 2835 2836 2837
        VIR_FREE(cmd->env[i]);
    VIR_FREE(cmd->env);

    VIR_FREE(cmd->pwd);

2838 2839
    if (cmd->handshake) {
        /* The other 2 fds in these arrays are closed
2840
         * due to use with virCommandPassFD
2841 2842 2843 2844 2845
         */
        VIR_FORCE_CLOSE(cmd->handshakeWait[0]);
        VIR_FORCE_CLOSE(cmd->handshakeNotify[1]);
    }

2846 2847
    VIR_FREE(cmd->pidfile);

2848 2849 2850
    if (cmd->reap)
        virCommandAbort(cmd);

2851 2852 2853 2854 2855 2856
#if defined(WITH_SECDRIVER_SELINUX)
    VIR_FREE(cmd->seLinuxLabel);
#endif
#if defined(WITH_SECDRIVER_APPARMOR)
    VIR_FREE(cmd->appArmorProfile);
#endif
2857

2858 2859
    VIR_FREE(cmd);
}
2860 2861 2862 2863 2864 2865 2866 2867

/**
 * virCommandDoAsyncIO:
 * @cmd: command to do async IO on
 *
 * This requests asynchronous string IO on @cmd. It is useful in
 * combination with virCommandRunAsync():
 *
2868 2869
 *      VIR_AUTOPTR(virCommand) cmd = virCommandNew*(...);
 *      VIR_AUTOFREE(char *) buf = NULL;
2870 2871 2872 2873 2874 2875 2876
 *
 *      ...
 *
 *      virCommandSetOutputBuffer(cmd, &buf);
 *      virCommandDoAsyncIO(cmd);
 *
 *      if (virCommandRunAsync(cmd, NULL) < 0)
2877
 *          return;
2878 2879 2880 2881
 *
 *      ...
 *
 *      if (virCommandWait(cmd, NULL) < 0)
2882
 *          return;
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
 *
 *      // @buf now contains @cmd's stdout
 *      VIR_DEBUG("STDOUT: %s", NULLSTR(buf));
 *
 *      ...
 *
 *
 * The libvirt's event loop is used for handling stdios of @cmd.
 * Since current implementation uses strlen to determine length
 * of data to be written to @cmd's stdin, don't pass any binary
 * data. If you want to re-run command, you need to call this and
 * buffer setting functions (virCommandSet.*Buffer) prior each run.
 */
void
virCommandDoAsyncIO(virCommandPtr cmd)
{
2899 2900
    if (!cmd || cmd->has_error)
        return;
2901

2902
    cmd->flags |= VIR_EXEC_ASYNC_IO | VIR_EXEC_NONBLOCK;
2903
}
2904 2905 2906 2907

/**
 * virCommandSetDryRun:
 * @buf: buffer to store stringified commands
2908
 * @callback: callback to process input/output/args
2909 2910 2911 2912 2913 2914 2915 2916
 *
 * Sometimes it's desired to not actually run given command, but
 * see its string representation without having to change the
 * callee. Unit testing serves as a great example. In such cases,
 * the callee constructs the command and calls it via
 * virCommandRun* API. The virCommandSetDryRun allows you to
 * modify this behavior: once called, every call to
 * virCommandRun* results in command string representation being
2917 2918 2919 2920 2921 2922 2923
 * appended to @buf instead of being executed. If @callback is
 * provided, then it is invoked with the argv, env and stdin
 * data string for the command. It is expected to fill the stdout
 * and stderr data strings and exit status variables.
 *
 * The strings stored in @buf are escaped for a shell and
 * separated by a newline. For example:
2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934
 *
 * virBuffer buffer = VIR_BUFFER_INITIALIZER;
 * virCommandSetDryRun(&buffer);
 *
 * virCommandPtr echocmd = virCommandNewArgList("/bin/echo", "Hello world", NULL);
 * virCommandRun(echocmd, NULL);
 *
 * After this, the @buffer should contain:
 *
 * /bin/echo 'Hello world'\n
 *
2935
 * To cancel this effect pass NULL for @buf and @callback.
2936 2937
 */
void
2938 2939 2940
virCommandSetDryRun(virBufferPtr buf,
                    virCommandDryRunCallback cb,
                    void *opaque)
2941 2942
{
    dryRunBuffer = buf;
2943 2944
    dryRunCallback = cb;
    dryRunOpaque = opaque;
2945
}
2946 2947

#ifndef WIN32
2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
/**
 * virCommandRunRegex:
 * @cmd: command to run
 * @nregex: number of regexes to apply
 * @regex: array of regexes to apply
 * @nvars: array of numbers of variables each regex will produce
 * @func: callback function that is called for every line of output,
 * needs to return 0 on success
 * @data: additional data that will be passed to the callback function
 * @prefix: prefix that will be skipped at the beginning of each line
2958
 * @exitstatus: allows the caller to handle command run exit failures
2959
 *
2960 2961 2962 2963
 * Run an external program.
 *
 * Read its output and apply a series of regexes to each line
 * When the entire set of regexes has matched consecutively
2964 2965 2966 2967
 * then run a callback passing in all the matches on the current line.
 *
 * Returns: 0 on success, -1 on memory allocation error, virCommandRun
 * error or callback function error
2968 2969 2970 2971 2972 2973 2974 2975
 */
int
virCommandRunRegex(virCommandPtr cmd,
                   int nregex,
                   const char **regex,
                   int *nvars,
                   virCommandRunRegexFunc func,
                   void *data,
2976 2977
                   const char *prefix,
                   int *exitstatus)
2978
{
2979
    int err;
2980
    regex_t *reg;
2981
    VIR_AUTOFREE(regmatch_t *) vars = NULL;
2982
    size_t i, j, k;
2983 2984
    int totgroups = 0, ngroup = 0, maxvars = 0;
    char **groups;
2985
    VIR_AUTOFREE(char *) outbuf = NULL;
2986
    VIR_AUTOSTRINGLIST lines = NULL;
2987
    int ret = -1;
2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017

    /* Compile all regular expressions */
    if (VIR_ALLOC_N(reg, nregex) < 0)
        return -1;

    for (i = 0; i < nregex; i++) {
        err = regcomp(&reg[i], regex[i], REG_EXTENDED);
        if (err != 0) {
            char error[100];
            regerror(err, &reg[i], error, sizeof(error));
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to compile regex %s"), error);
            for (j = 0; j < i; j++)
                regfree(&reg[j]);
            VIR_FREE(reg);
            return -1;
        }

        totgroups += nvars[i];
        if (nvars[i] > maxvars)
            maxvars = nvars[i];

    }

    /* Storage for matched variables */
    if (VIR_ALLOC_N(groups, totgroups) < 0)
        goto cleanup;
    if (VIR_ALLOC_N(vars, maxvars+1) < 0)
        goto cleanup;

3018
    virCommandSetOutputBuffer(cmd, &outbuf);
3019
    if (virCommandRun(cmd, exitstatus) < 0)
3020 3021
        goto cleanup;

3022 3023 3024
    if (!outbuf) {
        /* no output */
        ret = 0;
3025 3026 3027
        goto cleanup;
    }

3028 3029 3030 3031
    if (!(lines = virStringSplit(outbuf, "\n", 0)))
        goto cleanup;

    for (k = 0; lines[k]; k++) {
3032
        const char *p = NULL;
3033 3034 3035

        /* ignore any command prefix */
        if (prefix)
3036
            p = STRSKIP(lines[k], prefix);
3037
        if (!p)
3038
            p = lines[k];
3039

3040
        ngroup = 0;
J
Ján Tomko 已提交
3041 3042 3043
        for (i = 0; i < nregex; i++) {
            if (regexec(&reg[i], p, nvars[i]+1, vars, 0) != 0)
                break;
3044

3045 3046 3047 3048
            /* NB vars[0] is the full pattern, so we offset j by 1 */
            for (j = 1; j <= nvars[i]; j++) {
                if (VIR_STRNDUP(groups[ngroup++], p + vars[j].rm_so,
                                vars[j].rm_eo - vars[j].rm_so) < 0)
J
Ján Tomko 已提交
3049 3050
                    goto cleanup;
            }
3051

3052 3053 3054 3055 3056
        }
        /* We've matched on the last regex, so callback time */
        if (i == nregex) {
            if (((*func)(groups, data)) < 0)
                goto cleanup;
3057
        }
3058 3059 3060

        for (j = 0; j < ngroup; j++)
            VIR_FREE(groups[j]);
3061 3062
    }

3063
    ret = 0;
3064
 cleanup:
3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
    if (groups) {
        for (j = 0; j < totgroups; j++)
            VIR_FREE(groups[j]);
        VIR_FREE(groups);
    }

    for (i = 0; i < nregex; i++)
        regfree(&reg[i]);

    VIR_FREE(reg);
    return ret;
}

/*
 * Run an external program and read from its standard output
 * a stream of tokens from IN_STREAM, applying FUNC to
 * each successive sequence of N_COLUMNS tokens.
 * If FUNC returns < 0, stop processing input and return -1.
 * Return -1 if N_COLUMNS == 0.
 * Return -1 upon memory allocation error.
 * If the number of input tokens is not a multiple of N_COLUMNS,
 * then the final FUNC call will specify a number smaller than N_COLUMNS.
 * If there are no input tokens (empty input), call FUNC with N_COLUMNS == 0.
 */
int
virCommandRunNul(virCommandPtr cmd,
                 size_t n_columns,
                 virCommandRunNulFunc func,
                 void *data)
{
    size_t n_tok = 0;
    int fd = -1;
    FILE *fp = NULL;
    char **v;
    int ret = -1;
    size_t i;

    if (n_columns == 0)
        return -1;

    if (VIR_ALLOC_N(v, n_columns) < 0)
        return -1;
    for (i = 0; i < n_columns; i++)
        v[i] = NULL;

    virCommandSetOutputFD(cmd, &fd);
3111
    if (virCommandRunAsync(cmd, NULL) < 0)
3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138
        goto cleanup;

    if ((fp = VIR_FDOPEN(fd, "r")) == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot open file using fd"));
        goto cleanup;
    }

    while (1) {
        char *buf = NULL;
        size_t buf_len = 0;
        /* Be careful: even when it returns -1,
           this use of getdelim allocates memory.  */
        ssize_t tok_len = getdelim(&buf, &buf_len, 0, fp);
        v[n_tok] = buf;
        if (tok_len < 0) {
            /* Maybe EOF, maybe an error.
               If n_tok > 0, then we know it's an error.  */
            if (n_tok && func(n_tok, v, data) < 0)
                goto cleanup;
            break;
        }
        ++n_tok;
        if (n_tok == n_columns) {
            if (func(n_tok, v, data) < 0)
                goto cleanup;
            n_tok = 0;
3139
            for (i = 0; i < n_columns; i++)
3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170
                VIR_FREE(v[i]);
        }
    }

    if (feof(fp) < 0) {
        virReportSystemError(errno, "%s",
                             _("read error on pipe"));
        goto cleanup;
    }

    ret = virCommandWait(cmd, NULL);
 cleanup:
    for (i = 0; i < n_columns; i++)
        VIR_FREE(v[i]);
    VIR_FREE(v);

    VIR_FORCE_FCLOSE(fp);
    VIR_FORCE_CLOSE(fd);

    return ret;
}

#else /* WIN32 */

int
virCommandRunRegex(virCommandPtr cmd ATTRIBUTE_UNUSED,
                   int nregex ATTRIBUTE_UNUSED,
                   const char **regex ATTRIBUTE_UNUSED,
                   int *nvars ATTRIBUTE_UNUSED,
                   virCommandRunRegexFunc func ATTRIBUTE_UNUSED,
                   void *data ATTRIBUTE_UNUSED,
3171 3172
                   const char *prefix ATTRIBUTE_UNUSED,
                   int *exitstatus ATTRIBUTE_UNUSED)
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("%s not implemented on Win32"), __FUNCTION__);
    return -1;
}

int
virCommandRunNul(virCommandPtr cmd ATTRIBUTE_UNUSED,
                 size_t n_columns ATTRIBUTE_UNUSED,
                 virCommandRunNulFunc func ATTRIBUTE_UNUSED,
                 void *data ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("%s not implemented on Win32"), __FUNCTION__);
    return -1;
}
#endif /* WIN32 */