command.c 35.6 KB
Newer Older
1 2 3
/*
 * command.c: Child command execution
 *
4
 * Copyright (C) 2010-2011 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 */

#include <config.h>

#include <poll.h>
25
#include <signal.h>
26 27
#include <stdarg.h>
#include <stdlib.h>
28
#include <sys/stat.h>
29 30 31 32 33 34 35 36 37 38 39 40 41
#include <sys/wait.h>

#include "command.h"
#include "memory.h"
#include "virterror_internal.h"
#include "util.h"
#include "logging.h"
#include "files.h"
#include "buf.h"

#define VIR_FROM_THIS VIR_FROM_NONE

#define virCommandError(code, ...)                                      \
42
    virReportErrorHelper(VIR_FROM_NONE, code, __FILE__,                 \
43 44
                         __FUNCTION__, __LINE__, __VA_ARGS__)

45 46 47 48 49
enum {
    /* Internal-use extension beyond public VIR_EXEC_ flags */
    VIR_EXEC_RUN_SYNC = 0x40000000,
};

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
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;

    /* XXX Use int[] if we ever need to support more than FD_SETSIZE fd's.  */
    fd_set preserve; /* FDs to pass to child. */
    fd_set transfer; /* FDs to close in parent. */

    unsigned int flags;

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

    int infd;
    int inpipe;
    int outfd;
    int errfd;
    int *outfdptr;
    int *errfdptr;

    virExecHook hook;
    void *opaque;

    pid_t pid;
    char *pidfile;
85
    bool reap;
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 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
};

/*
 * Create a new command for named binary
 */
virCommandPtr
virCommandNew(const char *binary)
{
    const char *const args[] = { binary, NULL };

    return virCommandNewArgs(args);
}

/*
 * Create a new command with a NULL terminated
 * set of args, taking binary from args[0]
 */
virCommandPtr
virCommandNewArgs(const char *const*args)
{
    virCommandPtr cmd;

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

    FD_ZERO(&cmd->preserve);
    FD_ZERO(&cmd->transfer);
    cmd->infd = cmd->outfd = cmd->errfd = -1;
    cmd->inpipe = -1;
    cmd->pid = -1;

    virCommandAddArgSet(cmd, args);

    return cmd;
}

/*
 * Create a new command with a NULL terminated
 * list of args, starting with the binary to run
 */
virCommandPtr
virCommandNewArgList(const char *binary, ...)
{
    virCommandPtr cmd = virCommandNew(binary);
    va_list list;
    const char *arg;

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

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


/*
 * Preserve the specified file descriptor in the child, instead of
 * closing it.  FD must not be one of the three standard streams.  If
 * transfer is true, then fd will be closed in the parent after a call
 * to Run/RunAsync/Free, otherwise caller is still responsible for fd.
 */
static void
virCommandKeepFD(virCommandPtr cmd, int fd, bool transfer)
{
    if (!cmd)
        return;

    if (fd <= STDERR_FILENO || FD_SETSIZE <= fd) {
        if (!cmd->has_error)
            cmd->has_error = -1;
        VIR_DEBUG("cannot preserve %d", fd);
        return;
    }

    FD_SET(fd, &cmd->preserve);
    if (transfer)
        FD_SET(fd, &cmd->transfer);
}

/*
 * Preserve the specified file descriptor
 * in the child, instead of closing it.
 * The parent is still responsible for managing fd.
 */
void
virCommandPreserveFD(virCommandPtr cmd, int fd)
{
    return virCommandKeepFD(cmd, fd, false);
}

/*
 * Transfer the specified file descriptor
 * to the child, instead of closing it.
 * Close the fd in the parent during Run/RunAsync/Free.
 */
void
virCommandTransferFD(virCommandPtr cmd, int fd)
{
    return virCommandKeepFD(cmd, fd, true);
}


/*
 * Save the child PID in a pidfile
 */
void
virCommandSetPidFile(virCommandPtr cmd, const char *pidfile)
{
    if (!cmd || cmd->has_error)
        return;

    VIR_FREE(cmd->pidfile);
    if (!(cmd->pidfile = strdup(pidfile))) {
        cmd->has_error = ENOMEM;
    }
}


/*
 * Remove all capabilities from the child
 */
void
virCommandClearCaps(virCommandPtr cmd)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->flags |= VIR_EXEC_CLEAR_CAPS;
}

#if 0 /* XXX Enable if we have a need for capability management.  */

/*
 * Re-allow a specific capability
 */
void
virCommandAllowCap(virCommandPtr cmd,
                   int capability ATTRIBUTE_UNUSED)
{
    if (!cmd || cmd->has_error)
        return;

    /* XXX ? */
}

#endif /* 0 */


/*
 * Daemonize the child process
 */
void
virCommandDaemonize(virCommandPtr cmd)
{
    if (!cmd || cmd->has_error)
        return;

    cmd->flags |= VIR_EXEC_DAEMON;
}

/*
 * 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;
}

/*
263
 * Add an environment variable to the child created by a printf-style format
264 265
 */
void
266
virCommandAddEnvFormat(virCommandPtr cmd, const char *format, ...)
267 268
{
    char *env;
269
    va_list list;
270 271 272 273

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

274 275
    va_start(list, format);
    if (virVasprintf(&env, format, list) < 0) {
276
        cmd->has_error = ENOMEM;
277
        va_end(list);
278 279
        return;
    }
280
    va_end(list);
281

282
    /* Arg plus trailing NULL. */
283 284 285 286 287 288 289 290 291
    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;
}

292 293 294 295 296 297 298 299 300 301
/*
 * 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);
}

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

/*
 * 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;

    if (!(env = strdup(str))) {
        cmd->has_error = ENOMEM;
        return;
    }

    /* env 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;
}


331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
/*
 * 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;
    }

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

    cmd->env[cmd->nenv++] = virBufferContentAndReset(buf);
}


356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
/*
 * Pass an environment variable to the child
 * using current process' value
 */
void
virCommandAddEnvPass(virCommandPtr cmd, const char *name)
{
    char *value;
    if (!cmd || cmd->has_error)
        return;

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


/*
 * Set LC_ALL to C, and propagate other essential environment
 * variables from the parent process.
 */
void
virCommandAddEnvPassCommon(virCommandPtr cmd)
{
380 381 382
    if (!cmd || cmd->has_error)
        return;

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    /* Attempt to Pre-allocate; allocation failure will be detected
     * later during virCommandAdd*.  */
    ignore_value(VIR_RESIZE_N(cmd->env, cmd->maxenv, cmd->nenv, 9));

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

    virCommandAddEnvPass(cmd, "LD_PRELOAD");
    virCommandAddEnvPass(cmd, "LD_LIBRARY_PATH");
    virCommandAddEnvPass(cmd, "PATH");
    virCommandAddEnvPass(cmd, "HOME");
    virCommandAddEnvPass(cmd, "USER");
    virCommandAddEnvPass(cmd, "LOGNAME");
    virCommandAddEnvPass(cmd, "TMPDIR");
}

/*
 * Add a command line argument to the child
 */
void
virCommandAddArg(virCommandPtr cmd, const char *val)
{
    char *arg;

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

    if (!(arg = strdup(val))) {
        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;
}


425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
/*
 * 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;
    }

    cmd->args[cmd->nargs++] = virBufferContentAndReset(buf);
}


449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
/*
 * Add a command line argument created by a printf-style format
 */
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;
}

/*
 * Add "NAME=VAL" as a single command line argument to the child
 */
void
virCommandAddArgPair(virCommandPtr cmd, const char *name, const char *val)
{
    virCommandAddArgFormat(cmd, "%s=%s", name, val);
}

/*
 * Add a NULL terminated list of args
 */
void
virCommandAddArgSet(virCommandPtr cmd, const char *const*vals)
{
    int narg = 0;

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

499 500 501 502 503
    if (vals[0] == NULL) {
        cmd->has_error = EINVAL;
        return;
    }

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    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) {
        char *arg = strdup(vals[narg++]);
        if (!arg) {
            cmd->has_error = ENOMEM;
            return;
        }
        cmd->args[cmd->nargs++] = arg;
    }
}

/*
 * Add a NULL terminated list of args
 */
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;
        arg = strdup(arg);
        if (!arg) {
            cmd->has_error = ENOMEM;
            va_end(list);
            return;
        }
        cmd->args[cmd->nargs++] = arg;
    }
    va_end(list);
}

/*
 * 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;
576
        VIR_DEBUG("cannot set directory twice");
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
    } else {
        cmd->pwd = strdup(pwd);
        if (!cmd->pwd)
            cmd->has_error = ENOMEM;
    }
}


/*
 * Feed the child's stdin from a string buffer
 */
void
virCommandSetInputBuffer(virCommandPtr cmd, const char *inbuf)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->infd != -1 || cmd->inbuf) {
        cmd->has_error = -1;
596
        VIR_DEBUG("cannot specify input twice");
597 598 599 600 601 602 603 604 605 606
        return;
    }

    cmd->inbuf = strdup(inbuf);
    if (!cmd->inbuf)
        cmd->has_error = ENOMEM;
}


/*
607 608 609 610
 * 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
 * virCommandRun; caller is responsible for freeing *outbuf.
611 612 613 614
 */
void
virCommandSetOutputBuffer(virCommandPtr cmd, char **outbuf)
{
615
    *outbuf = NULL;
616 617 618 619 620
    if (!cmd || cmd->has_error)
        return;

    if (cmd->outfdptr) {
        cmd->has_error = -1;
621
        VIR_DEBUG("cannot specify output twice");
622 623 624 625 626 627 628 629 630
        return;
    }

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


/*
631 632 633 634
 * 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
 * virCommandRun; caller is responsible for freeing *errbuf.
635 636 637 638
 */
void
virCommandSetErrorBuffer(virCommandPtr cmd, char **errbuf)
{
639
    *errbuf = NULL;
640 641 642 643 644
    if (!cmd || cmd->has_error)
        return;

    if (cmd->errfdptr) {
        cmd->has_error = -1;
645
        VIR_DEBUG("cannot specify stderr twice");
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
        return;
    }

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


/*
 * 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;
665
        VIR_DEBUG("cannot specify input twice");
666 667 668 669
        return;
    }
    if (infd < 0) {
        cmd->has_error = -1;
670
        VIR_DEBUG("cannot specify invalid input fd");
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
        return;
    }

    cmd->infd = infd;
}


/*
 * Attach a file descriptor to the child's stdout
 */
void
virCommandSetOutputFD(virCommandPtr cmd, int *outfd)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->outfdptr) {
        cmd->has_error = -1;
689
        VIR_DEBUG("cannot specify output twice");
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
        return;
    }

    cmd->outfdptr = outfd;
}


/*
 * Attach a file descriptor to the child's stderr
 */
void
virCommandSetErrorFD(virCommandPtr cmd, int *errfd)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->errfdptr) {
        cmd->has_error = -1;
708
        VIR_DEBUG("cannot specify stderr twice");
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        return;
    }

    cmd->errfdptr = errfd;
}


/*
 * 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.
 */
void
virCommandSetPreExecHook(virCommandPtr cmd, virExecHook hook, void *opaque)
{
    if (!cmd || cmd->has_error)
        return;

    if (cmd->hook) {
        cmd->has_error = -1;
729
        VIR_DEBUG("cannot specify hook twice");
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
        return;
    }
    cmd->hook = hook;
    cmd->opaque = opaque;
}


/*
 * 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;

    for (i = 0 ; i < cmd->nenv ; i++) {
        if (safewrite(logfd, cmd->env[i], strlen(cmd->env[i])) < 0)
            ioError = errno;
        if (safewrite(logfd, " ", 1) < 0)
            ioError = errno;
    }
    for (i = 0 ; i < cmd->nargs ; i++) {
        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",
                 cmd->args[0], virStrerror(ioError, ebuf, sizeof ebuf));
    }
}


/*
 * Call after adding all arguments and environment settings, but before
 * Run/RunAsync, to return a string representation of the environment and
 * arguments of cmd.  If virCommandRun cannot succeed (because of an
 * out-of-memory condition while building cmd), NULL will be returned.
 * Caller is responsible for freeing the resulting string.
 */
char *
virCommandToString(virCommandPtr cmd)
{
    size_t i;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    /* Cannot assume virCommandRun will be called; so report the error
     * now.  If virCommandRun is called, it will report the same error. */
790 791
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
792 793
        return NULL;
    }
794 795 796
    if (cmd->has_error) {
        virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("invalid use of command API"));
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
        return NULL;
    }

    for (i = 0; i < cmd->nenv; i++) {
        virBufferAdd(&buf, cmd->env[i], strlen(cmd->env[i]));
        virBufferAddChar(&buf, ' ');
    }
    virBufferAdd(&buf, cmd->args[0], strlen(cmd->args[0]));
    for (i = 1; i < cmd->nargs; i++) {
        virBufferAddChar(&buf, ' ');
        virBufferAdd(&buf, cmd->args[i], strlen(cmd->args[i]));
    }

    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        virReportOOMError();
        return NULL;
    }

    return virBufferContentAndReset(&buf);
}


820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
/*
 * Translate an exit status into a malloc'd string.  Generic helper
 * for virCommandRun and virCommandWait status argument, as well as
 * raw waitpid and older virRun status.
 */
char *
virCommandTranslateStatus(int status)
{
    char *buf;
    if (WIFEXITED(status)) {
        virAsprintf(&buf, _("exit status %d"), WEXITSTATUS(status));
    } else if (WIFSIGNALED(status)) {
        virAsprintf(&buf, _("fatal signal %d"), WTERMSIG(status));
    } else {
        virAsprintf(&buf, _("invalid value %d"), status);
    }
    return buf;
}


840 841 842 843 844 845 846 847 848
/*
 * Manage input and output to the child process.
 */
static int
virCommandProcessIO(virCommandPtr cmd)
{
    int infd = -1, outfd = -1, errfd = -1;
    size_t inlen = 0, outlen = 0, errlen = 0;
    size_t inoff = 0;
849
    int ret = 0;
850 851 852 853 854 855 856 857

    /* With an input buffer, feed data to child
     * via pipe */
    if (cmd->inbuf) {
        inlen = strlen(cmd->inbuf);
        infd = cmd->inpipe;
    }

858 859 860 861 862
    /* 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) {
863
        outfd = cmd->outfd;
864 865 866 867 868 869
        if (VIR_REALLOC_N(*cmd->outbuf, 1) < 0) {
            virReportOOMError();
            ret = -1;
        }
    }
    if (cmd->errbuf) {
870
        errfd = cmd->errfd;
871 872 873 874 875 876 877 878
        if (VIR_REALLOC_N(*cmd->errbuf, 1) < 0) {
            virReportOOMError();
            ret = -1;
        }
    }
    if (ret == -1)
        goto cleanup;
    ret = -1;
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908

    for (;;) {
        int i;
        struct pollfd fds[3];
        int nfds = 0;

        if (infd != -1) {
            fds[nfds].fd = infd;
            fds[nfds].events = POLLOUT;
            nfds++;
        }
        if (outfd != -1) {
            fds[nfds].fd = outfd;
            fds[nfds].events = POLLIN;
            nfds++;
        }
        if (errfd != -1) {
            fds[nfds].fd = errfd;
            fds[nfds].events = POLLIN;
            nfds++;
        }

        if (nfds == 0)
            break;

        if (poll(fds, nfds, -1) < 0) {
            if ((errno == EAGAIN) || (errno == EINTR))
                continue;
            virReportSystemError(errno, "%s",
                                 _("unable to poll on child"));
909
            goto cleanup;
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
        }

        for (i = 0; i < nfds ; i++) {
            if (fds[i].fd == errfd ||
                fds[i].fd == outfd) {
                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;
                }
926 927
                /* Silence a false positive from clang. */
                sa_assert(buf);
928 929 930 931 932 933 934

                done = read(fds[i].fd, data, sizeof(data));
                if (done < 0) {
                    if (errno != EINTR &&
                        errno != EAGAIN) {
                        virReportSystemError(errno, "%s",
                                             _("unable to write to child input"));
935
                        goto cleanup;
936 937 938 939 940 941 942 943 944
                    }
                } else if (done == 0) {
                    if (fds[i].fd == outfd)
                        outfd = -1;
                    else
                        errfd = -1;
                } else {
                    if (VIR_REALLOC_N(*buf, *len + done + 1) < 0) {
                        virReportOOMError();
945
                        goto cleanup;
946 947 948 949 950 951 952 953 954 955 956 957 958 959
                    }
                    memcpy(*buf + *len, data, done);
                    *len += done;
                }
            } else {
                int done;

                done = write(infd, cmd->inbuf + inoff,
                             inlen - inoff);
                if (done < 0) {
                    if (errno != EINTR &&
                        errno != EAGAIN) {
                        virReportSystemError(errno, "%s",
                                             _("unable to write to child input"));
960
                        goto cleanup;
961 962 963 964 965 966 967 968 969 970 971 972 973 974
                    }
                } else {
                    inoff += done;
                    if (inoff == inlen) {
                        int tmpfd = infd;
                        if (VIR_CLOSE(infd) < 0)
                            VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
                    }
                }
            }

        }
    }

975 976
    ret = 0;
cleanup:
977
    if (cmd->outbuf && *cmd->outbuf)
978
        (*cmd->outbuf)[outlen] = '\0';
979
    if (cmd->errbuf && *cmd->errbuf)
980 981
        (*cmd->errbuf)[errlen] = '\0';
    return ret;
982 983
}

984 985 986 987 988 989 990 991
/*
 * Exec the command, replacing the current process. Meant to be called
 * after already forking / cloning, so does not attempt to daemonize or
 * preserve any FDs.
 *
 * Returns -1 on any error executing the command.
 * Will not return on success.
 */
992
#ifndef WIN32
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
int virCommandExec(virCommandPtr cmd)
{
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
        return -1;
    }
    if (cmd->has_error) {
        virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("invalid use of command API"));
        return -1;
    }

    return execve(cmd->args[0], cmd->args, cmd->env);
}
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
#else
int virCommandExec(virCommandPtr cmd ATTRIBUTE_UNUSED)
{
    /* 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
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031

/*
 * Run the command and wait for completion.
 * Returns -1 on any error executing the
 * command. Returns 0 if the command executed,
 * with the exit status set
 */
int
virCommandRun(virCommandPtr cmd, int *exitstatus)
{
    int ret = 0;
    char *outbuf = NULL;
    char *errbuf = NULL;
1032
    int infd[2] = { -1, -1 };
1033 1034 1035
    struct stat st;
    bool string_io;
    bool async_io = false;
1036
    char *str;
1037

1038 1039
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
1040 1041
        return -1;
    }
1042 1043 1044
    if (cmd->has_error) {
        virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("invalid use of command API"));
1045 1046 1047
        return -1;
    }

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    /* 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) {
            virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("cannot mix caller fds with blocking execution"));
            return -1;
        }
    } else {
        if ((cmd->flags & VIR_EXEC_DAEMON) && string_io) {
            virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("cannot mix string I/O with daemon"));
            return -1;
        }
    }

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    /* If we have an input buffer, we need
     * a pipe to feed the data to the child */
    if (cmd->inbuf) {
        if (pipe(infd) < 0) {
            virReportSystemError(errno, "%s",
                                 _("unable to open pipe"));
            cmd->has_error = -1;
            return -1;
        }
        cmd->infd = infd[0];
        cmd->inpipe = infd[1];
    }

    /* If caller hasn't requested capture of stdout/err, then capture
1091 1092 1093
     * 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.
1094
     */
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
    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;
        }
1106 1107
    }

1108
    cmd->flags |= VIR_EXEC_RUN_SYNC;
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    if (virCommandRunAsync(cmd, NULL) < 0) {
        if (cmd->inbuf) {
            int tmpfd = infd[0];
            if (VIR_CLOSE(infd[0]) < 0)
                VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
            tmpfd = infd[1];
            if (VIR_CLOSE(infd[1]) < 0)
                VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
        }
        cmd->has_error = -1;
        return -1;
    }

1122
    if (string_io)
1123 1124 1125 1126 1127
        ret = virCommandProcessIO(cmd);

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

1128 1129 1130 1131
    str = (exitstatus ? virCommandTranslateStatus(*exitstatus)
           : (char *) "status 0");
    VIR_DEBUG("Result %s, stdout: '%s' stderr: '%s'",
              NULLSTR(str),
1132 1133
              cmd->outbuf ? NULLSTR(*cmd->outbuf) : "(null)",
              cmd->errbuf ? NULLSTR(*cmd->errbuf) : "(null)");
1134 1135
    if (exitstatus)
        VIR_FREE(str);
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152

    /* Reset any capturing, in case caller runs
     * this identical command again */
    if (cmd->inbuf) {
        int tmpfd = infd[0];
        if (VIR_CLOSE(infd[0]) < 0)
            VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
        tmpfd = infd[1];
        if (VIR_CLOSE(infd[1]) < 0)
            VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
    }
    if (cmd->outbuf == &outbuf) {
        int tmpfd = cmd->outfd;
        if (VIR_CLOSE(cmd->outfd) < 0)
            VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
        cmd->outfdptr = NULL;
        cmd->outbuf = NULL;
E
Eric Blake 已提交
1153
        VIR_FREE(outbuf);
1154 1155 1156 1157 1158 1159 1160
    }
    if (cmd->errbuf == &errbuf) {
        int tmpfd = cmd->errfd;
        if (VIR_CLOSE(cmd->errfd) < 0)
            VIR_DEBUG("ignoring failed close on fd %d", tmpfd);
        cmd->errfdptr = NULL;
        cmd->errbuf = NULL;
E
Eric Blake 已提交
1161
        VIR_FREE(errbuf);
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
    }

    return ret;
}


/*
 * Perform all virCommand-specific actions, along with the user hook.
 */
static int
virCommandHook(void *data)
{
    virCommandPtr cmd = data;
    int res = 0;

    if (cmd->hook)
        res = cmd->hook(cmd->opaque);
    if (res == 0 && cmd->pwd) {
        VIR_DEBUG("Running child in %s", cmd->pwd);
        res = chdir(cmd->pwd);
    }
    return res;
}


/*
 * Run the command asynchronously
 * Returns -1 on any error executing the
 * command. Returns 0 if the command executed.
 */
int
virCommandRunAsync(virCommandPtr cmd, pid_t *pid)
{
    int ret;
    char *str;
    int i;
1198
    bool synchronous = false;
1199

1200 1201
    if (!cmd || cmd->has_error == ENOMEM) {
        virReportOOMError();
1202 1203
        return -1;
    }
1204 1205 1206
    if (cmd->has_error) {
        virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("invalid use of command API"));
1207 1208 1209
        return -1;
    }

1210 1211 1212
    synchronous = cmd->flags & VIR_EXEC_RUN_SYNC;
    cmd->flags &= ~VIR_EXEC_RUN_SYNC;

1213 1214 1215 1216 1217 1218 1219 1220 1221
    /* Buffer management can only be requested via virCommandRun.  */
    if ((cmd->inbuf && cmd->infd == -1) ||
        (cmd->outbuf && cmd->outfdptr != &cmd->outfd) ||
        (cmd->errbuf && cmd->errfdptr != &cmd->errfd)) {
        virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cannot mix string I/O with asynchronous command"));
        return -1;
    }

1222 1223 1224 1225 1226 1227 1228
    if (cmd->pid != -1) {
        virCommandError(VIR_ERR_INTERNAL_ERROR,
                        _("command is already running as pid %d"),
                        cmd->pid);
        return -1;
    }

1229 1230 1231 1232 1233
    if (!synchronous && (cmd->flags & VIR_EXEC_DAEMON)) {
        virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("daemonized command cannot use virCommandRunAsync"));
        return -1;
    }
1234 1235 1236 1237 1238 1239
    if (cmd->pwd && (cmd->flags & VIR_EXEC_DAEMON)) {
        virCommandError(VIR_ERR_INTERNAL_ERROR,
                        _("daemonized command cannot set working directory %s"),
                        cmd->pwd);
        return -1;
    }
1240 1241 1242 1243 1244
    if (cmd->pidfile && !(cmd->flags & VIR_EXEC_DAEMON)) {
        virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("creation of pid file requires daemonized command"));
        return -1;
    }
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274

    str = virCommandToString(cmd);
    VIR_DEBUG("About to run %s", str ? str : cmd->args[0]);
    VIR_FREE(str);

    ret = virExecWithHook((const char *const *)cmd->args,
                          (const char *const *)cmd->env,
                          &cmd->preserve,
                          &cmd->pid,
                          cmd->infd,
                          cmd->outfdptr,
                          cmd->errfdptr,
                          cmd->flags,
                          virCommandHook,
                          cmd,
                          cmd->pidfile);

    VIR_DEBUG("Command result %d, with PID %d",
              ret, (int)cmd->pid);

    for (i = STDERR_FILENO + 1; i < FD_SETSIZE; i++) {
        if (FD_ISSET(i, &cmd->transfer)) {
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
            FD_CLR(i, &cmd->transfer);
        }
    }

    if (ret == 0 && pid)
        *pid = cmd->pid;
1275 1276
    else
        cmd->reap = true;
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293

    return ret;
}


/*
 * Wait for the async command to complete.
 * Return -1 on any error waiting for
 * completion. Returns 0 if the command
 * finished with the exit status set
 */
int
virCommandWait(virCommandPtr cmd, int *exitstatus)
{
    int ret;
    int status;

1294 1295
    if (!cmd ||cmd->has_error == ENOMEM) {
        virReportOOMError();
1296 1297
        return -1;
    }
1298 1299 1300
    if (cmd->has_error) {
        virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("invalid use of command API"));
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        return -1;
    }

    if (cmd->pid == -1) {
        virCommandError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("command is not yet running"));
        return -1;
    }


    /* Wait for intermediate process to exit */
    while ((ret = waitpid(cmd->pid, &status, 0)) == -1 &&
           errno == EINTR);

    if (ret == -1) {
        virReportSystemError(errno, _("unable to wait for process %d"),
                             cmd->pid);
        return -1;
    }

    cmd->pid = -1;
1322
    cmd->reap = false;
1323 1324 1325

    if (exitstatus == NULL) {
        if (status != 0) {
1326
            char *str = virCommandToString(cmd);
1327
            char *st = virCommandTranslateStatus(status);
1328
            virCommandError(VIR_ERR_INTERNAL_ERROR,
1329 1330
                            _("Child process (%s) status unexpected: %s"),
                            str ? str : cmd->args[0], NULLSTR(st));
1331
            VIR_FREE(str);
1332
            VIR_FREE(st);
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
            return -1;
        }
    } else {
        *exitstatus = status;
    }

    return 0;
}


E
Eric Blake 已提交
1343
#ifndef WIN32
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
/*
 * 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)
{
    int saved_errno;
    int ret;
    int status;
    char *tmp = NULL;

    if (!cmd || cmd->pid == -1)
        return;

    /* See if intermediate process has exited; if not, try a nice
     * SIGTERM followed by a more severe SIGKILL.
     */
    saved_errno = errno;
    VIR_DEBUG("aborting child process %d", cmd->pid);
    while ((ret = waitpid(cmd->pid, &status, WNOHANG)) == -1 &&
           errno == EINTR);
    if (ret == cmd->pid) {
        tmp = virCommandTranslateStatus(status);
        VIR_DEBUG("process has ended: %s", tmp);
        goto cleanup;
    } else if (ret == 0) {
        VIR_DEBUG("trying SIGTERM to child process %d", cmd->pid);
        kill(cmd->pid, SIGTERM);
        usleep(10 * 1000);
        while ((ret = waitpid(cmd->pid, &status, WNOHANG)) == -1 &&
               errno == EINTR);
        if (ret == cmd->pid) {
            tmp = virCommandTranslateStatus(status);
            VIR_DEBUG("process has ended: %s", tmp);
            goto cleanup;
        } else if (ret == 0) {
            VIR_DEBUG("trying SIGKILL to child process %d", cmd->pid);
            kill(cmd->pid, SIGKILL);
            while ((ret = waitpid(cmd->pid, &status, 0)) == -1 &&
                   errno == EINTR);
            if (ret == cmd->pid) {
                tmp = virCommandTranslateStatus(status);
                VIR_DEBUG("process has ended: %s", tmp);
                goto cleanup;
            }
        }
    }
    VIR_DEBUG("failed to reap child %d, abandoning it", cmd->pid);

cleanup:
    VIR_FREE(tmp);
    cmd->pid = -1;
    cmd->reap = false;
    errno = saved_errno;
}
E
Eric Blake 已提交
1402 1403 1404 1405 1406 1407 1408 1409 1410
#else /* WIN32 */
void
virCommandAbort(virCommandPtr cmd ATTRIBUTE_UNUSED)
{
    /* Mingw lacks WNOHANG and kill().  But since we haven't ported
     * virExecWithHook to mingw yet, there's no process to be killed,
     * making this implementation trivially correct for now :)  */
}
#endif
1411

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
/*
 * Release all resources
 */
void
virCommandFree(virCommandPtr cmd)
{
    int i;
    if (!cmd)
        return;

    for (i = STDERR_FILENO + 1; i < FD_SETSIZE; i++) {
        if (FD_ISSET(i, &cmd->transfer)) {
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
        }
    }

E
Eric Blake 已提交
1429
    VIR_FREE(cmd->inbuf);
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
    VIR_FORCE_CLOSE(cmd->outfd);
    VIR_FORCE_CLOSE(cmd->errfd);

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

    for (i = 0 ; i < cmd->nenv ; i++)
        VIR_FREE(cmd->env[i]);
    VIR_FREE(cmd->env);

    VIR_FREE(cmd->pwd);

    VIR_FREE(cmd->pidfile);

1445 1446 1447
    if (cmd->reap)
        virCommandAbort(cmd);

1448 1449
    VIR_FREE(cmd);
}