vsh.c 90.6 KB
Newer Older
1 2 3
/*
 * vsh.c: common data to be used by clients to exercise the libvirt API
 *
4
 * Copyright (C) 2005-2019 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>
#include "vsh.h"

#include <assert.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/time.h>
#include "c-ctype.h"
#include <fcntl.h>
#include <time.h>
#include <sys/stat.h>
#include <inttypes.h>
#include <signal.h>

#if WITH_READLINE
# include <readline/readline.h>
# include <readline/history.h>
#endif

#include "internal.h"
#include "virerror.h"
#include "virbuffer.h"
#include "viralloc.h"
#include "virfile.h"
#include "virthread.h"
#include "vircommand.h"
#include "virtypedparam.h"
#include "virstring.h"

/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

55 56
#ifdef WITH_READLINE
/* For autocompletion */
57
vshControl *autoCompleteOpaque;
58 59
#endif

60 61 62 63 64 65 66
/* NOTE: It would be much nicer to have these two as part of vshControl
 * structure, unfortunately readline doesn't support passing opaque data
 * and only relies on static data accessible from the user-side callback
 */
const vshCmdGrp *cmdGroups;
const vshCmdDef *cmdSet;

67 68 69 70 71 72 73 74 75 76 77 78

/* simple handler for oom conditions */
static void
vshErrorOOM(void)
{
    fflush(stdout);
    fputs(_("error: Out of memory\n"), stderr);
    fflush(stderr);
    exit(EXIT_FAILURE);
}


79 80 81 82 83 84 85 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
double
vshPrettyCapacity(unsigned long long val, const char **unit)
{
    double limit = 1024;

    if (val < limit) {
        *unit = "B";
        return val;
    }
    limit *= 1024;
    if (val < limit) {
        *unit = "KiB";
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
        *unit = "MiB";
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
        *unit = "GiB";
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
        *unit = "TiB";
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
        *unit = "PiB";
        return val / (limit / 1024);
    }
    limit *= 1024;
    *unit = "EiB";
    return val / (limit / 1024);
}


void *
_vshMalloc(vshControl *ctl, size_t size, const char *filename, int line)
{
    char *x;

    if (VIR_ALLOC_N(x, size) == 0)
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %d bytes"),
             filename, line, (int) size);
    exit(EXIT_FAILURE);
}

void *
_vshCalloc(vshControl *ctl, size_t nmemb, size_t size, const char *filename,
           int line)
{
    char *x;

    if (!xalloc_oversized(nmemb, size) &&
        VIR_ALLOC_N(x, nmemb * size) == 0)
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %d bytes"),
             filename, line, (int) (size*nmemb));
    exit(EXIT_FAILURE);
}

char *
_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line)
{
    char *x;

    if (VIR_STRDUP(x, s) >= 0)
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %lu bytes"),
             filename, line, (unsigned long)strlen(s));
    exit(EXIT_FAILURE);
}

int
vshNameSorter(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;

    return vshStrcasecmp(*sa, *sb);
}


/*
 * Convert the strings separated by ',' into array. The returned
 * array is a NULL terminated string list. The caller has to free
170
 * the array using virStringListFree or a similar method.
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
 *
 * Returns the length of the filled array on success, or -1
 * on error.
 */
int
vshStringToArray(const char *str,
                 char ***array)
{
    char *str_copied = vshStrdup(NULL, str);
    char *str_tok = NULL;
    char *tmp;
    unsigned int nstr_tokens = 0;
    char **arr = NULL;
    size_t len = strlen(str_copied);

    /* tokenize the string from user and save its parts into an array */
    nstr_tokens = 1;

    /* count the delimiters, recognizing ,, as an escape for a
     * literal comma */
    str_tok = str_copied;
    while ((str_tok = strchr(str_tok, ','))) {
        if (str_tok[1] == ',')
            str_tok++;
        else
            nstr_tokens++;
        str_tok++;
    }

    /* reserve the NULL element at the end */
    if (VIR_ALLOC_N(arr, nstr_tokens + 1) < 0) {
        VIR_FREE(str_copied);
        return -1;
    }

    /* tokenize the input string, while treating ,, as a literal comma */
    nstr_tokens = 0;
    tmp = str_tok = str_copied;
    while ((tmp = strchr(tmp, ','))) {
        if (tmp[1] == ',') {
            memmove(&tmp[1], &tmp[2], len - (tmp - str_copied) - 2 + 1);
            len--;
            tmp++;
            continue;
        }
        *tmp++ = '\0';
        arr[nstr_tokens++] = vshStrdup(NULL, str_tok);
        str_tok = tmp;
    }
    arr[nstr_tokens++] = vshStrdup(NULL, str_tok);

    *array = arr;
    VIR_FREE(str_copied);
    return nstr_tokens;
}

virErrorPtr last_error;

/*
 * Quieten libvirt until we're done with the command.
 */
void
J
Ján Tomko 已提交
233 234
vshErrorHandler(void *opaque G_GNUC_UNUSED,
                virErrorPtr error G_GNUC_UNUSED)
235 236 237 238 239 240 241 242 243 244 245 246 247 248
{
    virFreeError(last_error);
    last_error = virSaveLastError();
}

/* Store a libvirt error that is from a helper API that doesn't raise errors
 * so it doesn't get overwritten */
void
vshSaveLibvirtError(void)
{
    virFreeError(last_error);
    last_error = virSaveLastError();
}

249 250 251 252 253 254 255 256

/* Store libvirt error from helper API but don't overwrite existing errors */
void
vshSaveLibvirtHelperError(void)
{
    if (last_error)
        return;

257
    if (virGetLastErrorCode() == VIR_ERR_OK)
258 259 260 261 262 263
        return;

    vshSaveLibvirtError();
}


264 265 266 267 268 269 270 271
/*
 * Reset libvirt error on graceful fallback paths
 */
void
vshResetLibvirtError(void)
{
    virFreeError(last_error);
    last_error = NULL;
272
    virResetLastError();
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
}

/*
 * Report an error when a command finishes.  This is better than before
 * (when correct operation would report errors), but it has some
 * problems: we lose the smarter formatting of virDefaultErrorFunc(),
 * and it can become harder to debug problems, if errors get reported
 * twice during one command.  This case shouldn't really happen anyway,
 * and it's IMHO a bug that libvirt does that sometimes.
 */
void
vshReportError(vshControl *ctl)
{
    if (last_error == NULL) {
        /* Calling directly into libvirt util functions won't trigger the
         * error callback (which sets last_error), so check it ourselves.
         *
         * If the returned error has CODE_OK, this most likely means that
         * no error was ever raised, so just ignore */
        last_error = virSaveLastError();
        if (!last_error || last_error->code == VIR_ERR_OK)
            goto out;
    }

    if (last_error->code == VIR_ERR_OK) {
        vshError(ctl, "%s", _("unknown error"));
        goto out;
    }

    vshError(ctl, "%s", last_error->message);

 out:
    vshResetLibvirtError();
}

/*
 * Detection of disconnections and automatic reconnection support
 */
static int disconnected; /* we may have been disconnected */

/* ---------------
 * Utils for work with command definition
 * ---------------
 */
const char *
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
{
    const vshCmdInfo *info;

    for (info = cmd->info; info && info->name; info++) {
        if (STREQ(info->name, name))
            return info->data;
    }
    return NULL;
}

329
/* Check if the internal command definitions are correct */
330
static int
331 332
vshCmddefCheckInternals(vshControl *ctl,
                        const vshCmdDef *cmd)
333 334
{
    size_t i;
335 336
    const char *help = NULL;

337 338
    /* in order to perform the validation resolve the alias first */
    if (cmd->flags & VSH_CMD_FLAG_ALIAS) {
339 340
        if (!cmd->alias) {
            vshError(ctl, _("command '%s' has inconsistent alias"), cmd->name);
341
            return -1;
342
        }
343 344 345
        cmd = vshCmddefSearch(cmd->alias);
    }

346
    /* Each command has to provide a non-empty help string. */
347 348
    if (!(help = vshCmddefGetInfo(cmd, "help")) || !*help) {
        vshError(ctl, _("command '%s' lacks help"), cmd->name);
349
        return -1;
350
    }
351 352 353 354 355 356 357

    if (!cmd->opts)
        return 0;

    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];

358 359
        if (i > 63) {
            vshError(ctl, _("command '%s' has too many options"), cmd->name);
360
            return -1; /* too many options */
361
        }
M
Michal Privoznik 已提交
362 363 364 365

        switch (opt->type) {
        case VSH_OT_STRING:
        case VSH_OT_BOOL:
366 367 368 369 370
            if (opt->flags & VSH_OFLAG_REQ) {
                vshError(ctl, _("command '%s' misused VSH_OFLAG_REQ"),
                         cmd->name);
                return -1; /* neither bool nor string options can be mandatory */
            }
M
Michal Privoznik 已提交
371 372 373
            break;

        case VSH_OT_ALIAS: {
374 375 376 377
            size_t j;
            char *name = (char *)opt->help; /* cast away const */
            char *p;

378 379 380
            if (opt->flags || !opt->help) {
                vshError(ctl, _("command '%s' has incorrect alias option"),
                         cmd->name);
381
                return -1; /* alias options are tracked by the original name */
382
            }
383 384
            if ((p = strchr(name, '=')) &&
                VIR_STRNDUP(name, name, p - name) < 0)
P
Peter Krempa 已提交
385
                vshErrorOOM();
386 387 388 389 390 391 392 393
            for (j = i + 1; cmd->opts[j].name; j++) {
                if (STREQ(name, cmd->opts[j].name) &&
                    cmd->opts[j].type != VSH_OT_ALIAS)
                    break;
            }
            if (name != opt->help) {
                VIR_FREE(name);
                /* If alias comes with value, replacement must not be bool */
394 395 396
                if (cmd->opts[j].type == VSH_OT_BOOL) {
                    vshError(ctl, _("command '%s' has mismatched alias type"),
                             cmd->name);
397
                    return -1;
398
                }
399
            }
400 401 402
            if (!cmd->opts[j].name) {
                vshError(ctl, _("command '%s' has missing alias option"),
                         cmd->name);
403
                return -1; /* alias option must map to a later option name */
404
            }
405
        }
M
Michal Privoznik 已提交
406 407
            break;
        case VSH_OT_ARGV:
408 409 410
            if (cmd->opts[i + 1].name) {
                vshError(ctl, _("command '%s' does not list argv option last"),
                         cmd->name);
M
Michal Privoznik 已提交
411
                return -1; /* argv option must be listed last */
412
            }
M
Michal Privoznik 已提交
413 414 415
            break;

        case VSH_OT_DATA:
416 417 418
            if (!(opt->flags & VSH_OFLAG_REQ)) {
                vshError(ctl, _("command '%s' has non-required VSH_OT_DATA"),
                         cmd->name);
M
Michal Privoznik 已提交
419
                return -1; /* OT_DATA should always be required. */
420
            }
M
Michal Privoznik 已提交
421 422 423 424 425
            break;

        case VSH_OT_INT:
            break;
        }
426 427 428 429
    }
    return 0;
}

430 431 432 433 434 435
/* Parse the options associated with @cmd, i.e. test whether options are
 * required or need an argument.
 *
 * Returns -1 on error or 0 on success, filling the caller-provided bitmaps
 * which keep track of required options and options needing an argument.
 */
436
static int
437 438
vshCmddefOptParse(const vshCmdDef *cmd, uint64_t *opts_need_arg,
                  uint64_t *opts_required)
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
{
    size_t i;
    bool optional = false;

    *opts_need_arg = 0;
    *opts_required = 0;

    if (!cmd->opts)
        return 0;

    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];

        if (opt->type == VSH_OT_BOOL) {
            optional = true;
            continue;
        }

457 458
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
459
                *opts_required |= 1ULL << i;
460 461 462 463 464
            else
                optional = true;
            continue;
        }

465 466 467
        if (opt->type == VSH_OT_ALIAS)
            continue; /* skip the alias option */

468
        *opts_need_arg |= 1ULL << i;
469 470 471
        if (opt->flags & VSH_OFLAG_REQ) {
            if (optional && opt->type != VSH_OT_ARGV)
                return -1; /* mandatory options must be listed first */
472
            *opts_required |= 1ULL << i;
473 474 475 476
        } else {
            optional = true;
        }
    }
477 478 479 480

    return 0;
}

481 482 483 484 485 486 487
static vshCmdOptDef helpopt = {
    .name = "help",
    .type = VSH_OT_BOOL,
    .help = N_("print help for this function")
};
static const vshCmdOptDef *
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
488
                   uint64_t *opts_seen, size_t *opt_index, char **optstr,
489
                   bool report)
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
{
    size_t i;
    const vshCmdOptDef *ret = NULL;
    char *alias = NULL;

    if (STREQ(name, helpopt.name))
        return &helpopt;

    for (i = 0; cmd->opts && cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];

        if (STREQ(opt->name, name)) {
            if (opt->type == VSH_OT_ALIAS) {
                char *value;

                /* Two types of replacements:
                   opt->help = "string": straight replacement of name
                   opt->help = "string=value": treat boolean flag as
                   alias of option and its default value */
                sa_assert(!alias);
                if (VIR_STRDUP(alias, opt->help) < 0)
                    goto cleanup;
                name = alias;
                if ((value = strchr(name, '='))) {
                    *value = '\0';
                    if (*optstr) {
516 517 518
                        if (report)
                            vshError(ctl, _("invalid '=' after option --%s"),
                                     opt->name);
519 520 521 522 523 524 525
                        goto cleanup;
                    }
                    if (VIR_STRDUP(*optstr, value + 1) < 0)
                        goto cleanup;
                }
                continue;
            }
526
            if ((*opts_seen & (1ULL << i)) && opt->type != VSH_OT_ARGV) {
527 528
                if (report)
                    vshError(ctl, _("option --%s already seen"), name);
529 530
                goto cleanup;
            }
531
            *opts_seen |= 1ULL << i;
532 533 534 535 536 537
            *opt_index = i;
            ret = opt;
            goto cleanup;
        }
    }

538
    if (STRNEQ(cmd->name, "help") && report) {
539 540 541 542 543 544 545 546 547
        vshError(ctl, _("command '%s' doesn't support option --%s"),
                 cmd->name, name);
    }
 cleanup:
    VIR_FREE(alias);
    return ret;
}

static const vshCmdOptDef *
548 549
vshCmddefGetData(const vshCmdDef *cmd, uint64_t *opts_need_arg,
                 uint64_t *opts_seen)
550 551 552 553 554 555 556 557
{
    size_t i;
    const vshCmdOptDef *opt;

    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
558
    i = __builtin_ffsl(*opts_need_arg) - 1;
559 560
    opt = &cmd->opts[i];
    if (opt->type != VSH_OT_ARGV)
561 562
        *opts_need_arg &= ~(1ULL << i);
    *opts_seen |= 1ULL << i;
563 564 565 566 567 568 569
    return opt;
}

/*
 * Checks for required options
 */
static int
570 571
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint64_t opts_required,
                    uint64_t opts_seen)
572 573 574 575 576 577 578 579 580
{
    const vshCmdDef *def = cmd->def;
    size_t i;

    opts_required &= ~opts_seen;
    if (!opts_required)
        return 0;

    for (i = 0; def->opts[i].name; i++) {
581
        if (opts_required & (1ULL << i)) {
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
            const vshCmdOptDef *opt = &def->opts[i];

            vshError(ctl,
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
        }
    }
    return -1;
}

static const vshCmdDef *
vshCmdDefSearchGrp(const char *cmdname)
{
    const vshCmdGrp *g;
    const vshCmdDef *c;

    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
            if (STREQ(c->name, cmdname))
                return c;
        }
    }

    return NULL;
}

static const vshCmdDef *
vshCmdDefSearchSet(const char *cmdname)
{
    const vshCmdDef *s;

    for (s = cmdSet; s->name; s++) {
        if (STREQ(s->name, cmdname))
            return s;
        }

    return NULL;
}

const vshCmdDef *
vshCmddefSearch(const char *cmdname)
{
    if (cmdGroups)
        return vshCmdDefSearchGrp(cmdname);
    else
        return vshCmdDefSearchSet(cmdname);
}

const vshCmdGrp *
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
            return g;
    }

    return NULL;
}

bool
646
vshCmdGrpHelp(vshControl *ctl, const vshCmdGrp *grp)
647 648 649
{
    const vshCmdDef *cmd = NULL;

650 651
    vshPrint(ctl, _(" %s (help keyword '%s'):\n"), grp->name,
             grp->keyword);
652

653 654 655 656 657
    for (cmd = grp->commands; cmd->name; cmd++) {
        if (cmd->flags & VSH_CMD_FLAG_ALIAS)
            continue;
        vshPrint(ctl, "    %-30s %s\n", cmd->name,
                 _(vshCmddefGetInfo(cmd, "help")));
658 659 660 661 662 663
    }

    return true;
}

bool
664
vshCmddefHelp(vshControl *ctl, const vshCmdDef *def)
665
{
666 667 668 669 670
    const char *desc = NULL;
    char buf[256];
    uint64_t opts_need_arg;
    uint64_t opts_required;
    bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
671

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    if (vshCmddefOptParse(def, &opts_need_arg, &opts_required)) {
        vshError(ctl, _("internal error: bad options in command: '%s'"),
                 def->name);
        return false;
    }

    fputs(_("  NAME\n"), stdout);
    fprintf(stdout, "    %s - %s\n", def->name,
            _(vshCmddefGetInfo(def, "help")));

    fputs(_("\n  SYNOPSIS\n"), stdout);
    fprintf(stdout, "    %s", def->name);
    if (def->opts) {
        const vshCmdOptDef *opt;
        for (opt = def->opts; opt->name; opt++) {
            const char *fmt = "%s";
            switch (opt->type) {
            case VSH_OT_BOOL:
                fmt = "[--%s]";
                break;
            case VSH_OT_INT:
                /* xgettext:c-format */
                fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
                       : _("[--%s <number>]"));
                if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                    shortopt = true;
                break;
            case VSH_OT_STRING:
                /* xgettext:c-format */
                fmt = _("[--%s <string>]");
                if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                    shortopt = true;
                break;
            case VSH_OT_DATA:
                fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
                if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                    shortopt = true;
                break;
            case VSH_OT_ARGV:
                /* xgettext:c-format */
                if (shortopt) {
                    fmt = (opt->flags & VSH_OFLAG_REQ)
                        ? _("{[--%s] <string>}...")
                        : _("[[--%s] <string>]...");
                } else {
                    fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                        : _("[<%s>]...");
719
                }
720 721 722 723
                break;
            case VSH_OT_ALIAS:
                /* aliases are intentionally undocumented */
                continue;
724
            }
725 726
            fputc(' ', stdout);
            fprintf(stdout, fmt, opt->name);
727
        }
728 729
    }
    fputc('\n', stdout);
730

731 732 733 734 735 736
    desc = vshCmddefGetInfo(def, "desc");
    if (*desc) {
        /* Print the description only if it's not empty.  */
        fputs(_("\n  DESCRIPTION\n"), stdout);
        fprintf(stdout, "    %s\n", _(desc));
    }
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
    if (def->opts && def->opts->name) {
        const vshCmdOptDef *opt;
        fputs(_("\n  OPTIONS\n"), stdout);
        for (opt = def->opts; opt->name; opt++) {
            switch (opt->type) {
            case VSH_OT_BOOL:
                snprintf(buf, sizeof(buf), "--%s", opt->name);
                break;
            case VSH_OT_INT:
                snprintf(buf, sizeof(buf),
                         (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
                         : _("--%s <number>"), opt->name);
                break;
            case VSH_OT_STRING:
                snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
                break;
            case VSH_OT_DATA:
                snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                         opt->name);
                break;
            case VSH_OT_ARGV:
                snprintf(buf, sizeof(buf),
                         shortopt ? _("[--%s] <string>") : _("<%s>"),
                         opt->name);
                break;
            case VSH_OT_ALIAS:
                continue;
765
            }
766 767

            fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
768 769
        }
    }
770 771
    fputc('\n', stdout);

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
    return true;
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
static void
vshCommandOptFree(vshCmdOpt * arg)
{
    vshCmdOpt *a = arg;

    while (a) {
        vshCmdOpt *tmp = a;

        a = a->next;

        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
    }
}

static void
vshCommandFree(vshCmd *cmd)
{
    vshCmd *c = cmd;

    while (c) {
        vshCmd *tmp = c;

        c = c->next;

804
        vshCommandOptFree(tmp->opts);
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
        VIR_FREE(tmp);
    }
}

/**
 * vshCommandOpt:
 * @cmd: parsed command line to search
 * @name: option name to search for
 * @opt: result of the search
 * @needData: true if option must be non-boolean
 *
 * Look up an option passed to CMD by NAME.  Returns 1 with *OPT set
 * to the option if found, 0 with *OPT set to NULL if the name is
 * valid and the option is not required, -1 with *OPT set to NULL if
 * the option is required but not present, and assert if NAME is not
820 821
 * valid (which indicates a programming error) unless cmd->skipChecks
 * is set. No error messages are issued if a value is returned.
822 823 824 825 826 827 828 829 830 831 832
 */
static int
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt,
              bool needData)
{
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
    int ret = 0;

    /* See if option is valid and/or required.  */
    *opt = NULL;
833

834 835 836 837 838
    while (valid && valid->name) {
        if (STREQ(name, valid->name))
            break;
        valid++;
    }
839

840
    if (!cmd->skipChecks)
841 842
        assert(valid && (!needData || valid->type != VSH_OT_BOOL));

843 844
    if (valid && valid->flags & VSH_OFLAG_REQ)
        ret = -1;
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

    /* See if option is present on command line.  */
    while (candidate) {
        if (STREQ(candidate->def->name, name)) {
            *opt = candidate;
            ret = 1;
            break;
        }
        candidate = candidate->next;
    }
    return ret;
}

/**
 * vshCommandOptInt:
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to int.
 * On error, a message is displayed.
 *
 * Return value:
 * >0 if option found and valid (@value updated)
 * 0 if option not found and not required (@value untouched)
 * <0 in all other cases (@value untouched)
 */
int
vshCommandOptInt(vshControl *ctl, const vshCmd *cmd,
                 const char *name, int *value)
{
    vshCmdOpt *arg;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;

    if ((ret = virStrToLong_i(arg->data, NULL, 10, value)) < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;

    return ret;
}

static int
vshCommandOptUIntInternal(vshControl *ctl,
                          const vshCmd *cmd,
                          const char *name,
                          unsigned int *value,
                          bool wrap)
{
    vshCmdOpt *arg;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;

    if (wrap)
        ret = virStrToLong_ui(arg->data, NULL, 10, value);
    else
        ret = virStrToLong_uip(arg->data, NULL, 10, value);
    if (ret < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;

    return ret;
}

/**
 * vshCommandOptUInt:
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to unsigned int, reject negative numbers
 * See vshCommandOptInt()
 */
int
vshCommandOptUInt(vshControl *ctl, const vshCmd *cmd,
                  const char *name, unsigned int *value)
{
    return vshCommandOptUIntInternal(ctl, cmd, name, value, false);
}

/**
 * vshCommandOptUIntWrap:
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to unsigned int, wraps negative numbers to positive
 * See vshCommandOptInt()
 */
int
vshCommandOptUIntWrap(vshControl *ctl, const vshCmd *cmd,
                      const char *name, unsigned int *value)
{
    return vshCommandOptUIntInternal(ctl, cmd, name, value, true);
}

static int
vshCommandOptULInternal(vshControl *ctl,
                        const vshCmd *cmd,
                        const char *name,
                        unsigned long *value,
                        bool wrap)
{
    vshCmdOpt *arg;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;

    if (wrap)
        ret = virStrToLong_ul(arg->data, NULL, 10, value);
    else
        ret = virStrToLong_ulp(arg->data, NULL, 10, value);
    if (ret < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;

    return ret;
}

/*
 * vshCommandOptUL:
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
int
vshCommandOptUL(vshControl *ctl, const vshCmd *cmd,
                const char *name, unsigned long *value)
{
    return vshCommandOptULInternal(ctl, cmd, name, value, false);
}

/**
 * vshCommandOptULWrap:
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to unsigned long, wraps negative numbers to positive
 * See vshCommandOptInt()
 */
int
vshCommandOptULWrap(vshControl *ctl, const vshCmd *cmd,
                    const char *name, unsigned long *value)
{
    return vshCommandOptULInternal(ctl, cmd, name, value, true);
}

/**
1016
 * vshCommandOptStringQuiet:
1017 1018 1019 1020 1021
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 *
1022
 * Returns option as STRING. On error -1 is returned but no error is set.
1023 1024 1025 1026 1027 1028
 * Return value:
 * >0 if option found and valid (@value updated)
 * 0 if option not found and not required (@value untouched)
 * <0 in all other cases (@value untouched)
 */
int
J
Ján Tomko 已提交
1029
vshCommandOptStringQuiet(vshControl *ctl G_GNUC_UNUSED, const vshCmd *cmd,
1030
                         const char *name, const char **value)
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 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 1077 1078 1079 1080
{
    vshCmdOpt *arg;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;

    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK))
        return -1;
    *value = arg->data;
    return 1;
}

/**
 * vshCommandOptStringReq:
 * @ctl virtshell control structure
 * @cmd command structure
 * @name option name
 * @value result (updated to NULL or the option argument)
 *
 * Gets a option argument as string.
 *
 * Returns 0 on success or when the option is not present and not
 * required, *value is set to the option argument. On error -1 is
 * returned and error message printed.
 */
int
vshCommandOptStringReq(vshControl *ctl,
                       const vshCmd *cmd,
                       const char *name,
                       const char **value)
{
    vshCmdOpt *arg;
    int ret;
    const char *error = NULL;

    /* clear out the value */
    *value = NULL;

    ret = vshCommandOpt(cmd, name, &arg, true);
    /* option is not required and not present */
    if (ret == 0)
        return 0;
    /* this should not be propagated here, just to be sure */
    if (ret == -1)
        error = N_("Mandatory option not present");
    else if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK))
        error = N_("Option argument is empty");

    if (error) {
1081 1082
        if (!cmd->skipChecks)
            vshError(ctl, _("Failed to get option '%s': %s"), name, _(error));
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 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 1198 1199 1200 1201 1202 1203
        return -1;
    }

    *value = arg->data;
    return 0;
}

/**
 * vshCommandOptLongLong:
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long
 * See vshCommandOptInt()
 */
int
vshCommandOptLongLong(vshControl *ctl, const vshCmd *cmd,
                      const char *name, long long *value)
{
    vshCmdOpt *arg;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;

    if ((ret = virStrToLong_ll(arg->data, NULL, 10, value)) < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;

    return ret;
}

static int
vshCommandOptULongLongInternal(vshControl *ctl,
                               const vshCmd *cmd,
                               const char *name,
                               unsigned long long *value,
                               bool wrap)
{
    vshCmdOpt *arg;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;

    if (wrap)
        ret = virStrToLong_ull(arg->data, NULL, 10, value);
    else
        ret = virStrToLong_ullp(arg->data, NULL, 10, value);
    if (ret < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;

    return ret;
}

/**
 * vshCommandOptULongLong:
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long, rejects negative numbers
 * See vshCommandOptInt()
 */
int
vshCommandOptULongLong(vshControl *ctl, const vshCmd *cmd,
                       const char *name, unsigned long long *value)
{
    return vshCommandOptULongLongInternal(ctl, cmd, name, value, false);
}

/**
 * vshCommandOptULongLongWrap:
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long, wraps negative numbers to positive
 * See vshCommandOptInt()
 */
int
vshCommandOptULongLongWrap(vshControl *ctl, const vshCmd *cmd,
                           const char *name, unsigned long long *value)
{
    return vshCommandOptULongLongInternal(ctl, cmd, name, value, true);
}

/**
 * vshCommandOptScaledInt:
 * @ctl virtshell control structure
 * @cmd command reference
 * @name option name
 * @value result
 * @scale default of 1 or 1024, if no suffix is present
 * @max maximum value permitted
 *
 * Returns option as long long, scaled according to suffix
 * See vshCommandOptInt()
 */
int
vshCommandOptScaledInt(vshControl *ctl, const vshCmd *cmd,
                       const char *name, unsigned long long *value,
                       int scale, unsigned long long max)
{
    vshCmdOpt *arg;
    char *end;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;
1204

1205
    if (virStrToLong_ullp(arg->data, &end, 10, value) < 0 ||
1206
        virScaleInteger(value, end, scale, max) < 0) {
1207
        vshError(ctl,
1208 1209
                 _("Scaled numeric value '%s' for <%s> option is malformed or "
                   "out of range"), arg->data, name);
1210
        return -1;
1211 1212
    }

1213
    return 1;
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
}


/**
 * vshCommandOptBool:
 * @cmd command reference
 * @name option name
 *
 * Returns true/false if the option exists.  Note that this does NOT
 * validate whether the option is actually boolean, or even whether
 * name is legal; so that this can be used to probe whether a data
 * option is present without actually using that data.
 */
bool
vshCommandOptBool(const vshCmd *cmd, const char *name)
{
    vshCmdOpt *dummy;

    return vshCommandOpt(cmd, name, &dummy, false) == 1;
}

/**
 * vshCommandOptArgv:
 * @ctl virtshell control structure
 * @cmd command reference
 * @opt starting point for the search
 *
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
 *
 * Requires that a VSH_OT_ARGV option be last in the
 * list of supported options in CMD->def->opts.
 */
const vshCmdOpt *
J
Ján Tomko 已提交
1248
vshCommandOptArgv(vshControl *ctl G_GNUC_UNUSED, const vshCmd *cmd,
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
                  const vshCmdOpt *opt)
{
    opt = opt ? opt->next : cmd->opts;

    while (opt) {
        if (opt->def->type == VSH_OT_ARGV)
            return opt;
        opt = opt->next;
    }
    return NULL;
}


1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
/**
 * vshBlockJobOptionBandwidth:
 * @ctl: virsh control data
 * @cmd: virsh command description
 * @bytes: return bandwidth in bytes/s instead of MiB/s
 * @bandwidth: return value
 *
 * Extracts the value of --bandwidth either as a wrap-able number without scale
 * or as a scaled integer. The returned value is checked to fit into a unsigned
 * long data type. This is a legacy compatibility function and it should not
 * be used for things other the block job APIs.
 *
 * Returns 0 on success, -1 on error.
 */
int
vshBlockJobOptionBandwidth(vshControl *ctl,
                           const vshCmd *cmd,
                           bool bytes,
                           unsigned long *bandwidth)
{
    vshCmdOpt *arg;
    char *end;
    unsigned long long bw;
    int ret;

    if ((ret = vshCommandOpt(cmd, "bandwidth", &arg, true)) <= 0)
        return ret;

    /* due to historical reasons we declare to parse negative numbers and wrap
     * them to the unsigned data type. */
    if (virStrToLong_ul(arg->data, NULL, 10, bandwidth) < 0) {
        /* try to parse the number as scaled size in this case we don't accept
         * wrapping since it would be ridiculous. In case of a 32 bit host,
         * limit the value to ULONG_MAX */
        if (virStrToLong_ullp(arg->data, &end, 10, &bw) < 0 ||
            virScaleInteger(&bw, end, 1, ULONG_MAX) < 0) {
            vshError(ctl,
                     _("Scaled numeric value '%s' for <--bandwidth> option is "
                       "malformed or out of range"), arg->data);
            return -1;
        }

        if (!bytes)
            bw >>= 20;

        *bandwidth = bw;
    }

    return 0;
}


1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 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
/*
 * Executes command(s) and returns return code from last command
 */
bool
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
{
    const vshClientHooks *hooks = ctl->hooks;
    bool ret = true;

    while (cmd) {
        struct timeval before, after;
        bool enable_timing = ctl->timing;

        if (enable_timing)
            GETTIMEOFDAY(&before);

        if ((cmd->def->flags & VSH_CMD_FLAG_NOCONNECT) ||
            (hooks && hooks->connHandler && hooks->connHandler(ctl))) {
            ret = cmd->def->handler(ctl, cmd);
        } else {
            /* connection is not usable, return error */
            ret = false;
        }

        if (enable_timing)
            GETTIMEOFDAY(&after);

        /* try to automatically catch disconnections */
        if (!ret &&
            ((last_error != NULL) &&
             (((last_error->code == VIR_ERR_SYSTEM_ERROR) &&
               (last_error->domain == VIR_FROM_REMOTE)) ||
              (last_error->code == VIR_ERR_RPC) ||
              (last_error->code == VIR_ERR_NO_CONNECT) ||
              (last_error->code == VIR_ERR_INVALID_CONN))))
            disconnected++;

        if (!ret)
            vshReportError(ctl);

        if (STREQ(cmd->def->name, "quit") ||
            STREQ(cmd->def->name, "exit"))        /* hack ... */
            return ret;

        if (enable_timing) {
            double diff_ms = (((after.tv_sec - before.tv_sec) * 1000.0) +
                              ((after.tv_usec - before.tv_usec) / 1000.0));

            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"), diff_ms);
        } else {
            vshPrintExtra(ctl, "\n");
        }
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
 * Command parsing
 * ---------------
 */

typedef enum {
    VSH_TK_ERROR, /* Failed to parse a token */
    VSH_TK_ARG, /* Arbitrary argument, might be option or empty */
    VSH_TK_SUBCMD_END, /* Separation between commands */
    VSH_TK_END /* No more commands */
} vshCommandToken;

typedef struct _vshCommandParser vshCommandParser;
struct _vshCommandParser {
    vshCommandToken(*getNextArg)(vshControl *, vshCommandParser *,
1386
                                 char **, bool);
1387 1388 1389 1390 1391 1392 1393 1394
    /* vshCommandStringGetArg() */
    char *pos;
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
};

static bool
1395
vshCommandParse(vshControl *ctl, vshCommandParser *parser, vshCmd **partial)
1396 1397 1398 1399
{
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
1400
    const vshCmdDef *cmd = NULL;
1401

1402 1403 1404 1405
    if (!partial) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
1406 1407 1408 1409 1410

    while (1) {
        vshCmdOpt *last = NULL;
        vshCommandToken tk;
        bool data_only = false;
1411 1412 1413
        uint64_t opts_need_arg = 0;
        uint64_t opts_required = 0;
        uint64_t opts_seen = 0;
1414

1415
        cmd = NULL;
1416 1417
        first = NULL;

1418 1419 1420 1421 1422
        if (partial) {
            vshCommandFree(*partial);
            *partial = NULL;
        }

1423 1424 1425 1426
        while (1) {
            const vshCmdOptDef *opt = NULL;

            tkdata = NULL;
1427
            tk = parser->getNextArg(ctl, parser, &tkdata, true);
1428 1429 1430 1431 1432 1433 1434 1435 1436

            if (tk == VSH_TK_ERROR)
                goto syntaxError;
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
                break;
            }

            if (cmd == NULL) {
1437 1438 1439 1440 1441 1442 1443 1444 1445
                /* first token must be command name or comment */
                if (*tkdata == '#') {
                    do {
                        VIR_FREE(tkdata);
                        tk = parser->getNextArg(ctl, parser, &tkdata, false);
                    } while (tk == VSH_TK_ARG);
                    VIR_FREE(tkdata);
                    break;
                } else if (!(cmd = vshCmddefSearch(tkdata))) {
1446 1447
                    if (!partial)
                        vshError(ctl, _("unknown command: '%s'"), tkdata);
1448 1449
                    goto syntaxError;   /* ... or ignore this command only? */
                }
1450 1451 1452 1453 1454 1455 1456

                /* aliases need to be resolved to the actual commands */
                if (cmd->flags & VSH_CMD_FLAG_ALIAS) {
                    VIR_FREE(tkdata);
                    tkdata = vshStrdup(ctl, cmd->alias);
                    cmd = vshCmddefSearch(tkdata);
                }
1457 1458
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
1459 1460 1461 1462
                    if (!partial)
                        vshError(ctl,
                                 _("internal error: bad options in command: '%s'"),
                                 tkdata);
1463 1464 1465 1466 1467 1468 1469 1470
                    goto syntaxError;
                }
                VIR_FREE(tkdata);
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
                char *optstr = strchr(tkdata + 2, '=');
1471
                size_t opt_index = 0;
1472 1473 1474 1475 1476 1477 1478 1479

                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
                /* Special case 'help' to ignore all spurious options */
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
                                               &opts_seen, &opt_index,
1480
                                               &optstr, partial == NULL))) {
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
                    VIR_FREE(optstr);
                    if (STREQ(cmd->name, "help"))
                        continue;
                    goto syntaxError;
                }
                VIR_FREE(tkdata);

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
                    if (optstr)
                        tkdata = optstr;
                    else
1493
                        tk = parser->getNextArg(ctl, parser, &tkdata, true);
1494 1495 1496
                    if (tk == VSH_TK_ERROR)
                        goto syntaxError;
                    if (tk != VSH_TK_ARG) {
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
                        if (partial) {
                            vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
                            arg->def = opt;
                            arg->data = tkdata;
                            tkdata = NULL;
                            arg->next = NULL;
                            if (!first)
                                first = arg;
                            if (last)
                                last->next = arg;
                            last = arg;
                        } else {
                            vshError(ctl,
                                     _("expected syntax: --%s <%s>"),
                                     opt->name,
                                     opt->type ==
                                     VSH_OT_INT ? _("number") : _("string"));
                        }
1515 1516 1517
                        goto syntaxError;
                    }
                    if (opt->type != VSH_OT_ARGV)
1518
                        opts_need_arg &= ~(1ULL << opt_index);
1519 1520 1521
                } else {
                    tkdata = NULL;
                    if (optstr) {
1522 1523 1524
                        if (!partial)
                            vshError(ctl, _("invalid '=' after option --%s"),
                                     opt->name);
1525 1526 1527 1528 1529 1530
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
                }
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
1531
                VIR_FREE(tkdata);
1532 1533 1534 1535 1536 1537 1538 1539
                data_only = true;
                continue;
            } else {
 get_data:
                /* Special case 'help' to ignore spurious data */
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
                                             &opts_seen)) &&
                     STRNEQ(cmd->name, "help")) {
1540 1541
                    if (!partial)
                        vshError(ctl, _("unexpected data '%s'"), tkdata);
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));

                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;

                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;

1560 1561 1562 1563 1564 1565
                if (!partial)
                    vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
                             cmd->name,
                             opt->name,
                             opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                             opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
            }
        }

        /* command parsed -- allocate new struct for the command */
        if (cmd) {
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
            vshCmdOpt *tmpopt = first;

            /* if we encountered --help, replace parsed command with
             * 'help <cmdname>' */
            for (tmpopt = first; tmpopt; tmpopt = tmpopt->next) {
1577
                const vshCmdDef *help;
1578 1579 1580
                if (STRNEQ(tmpopt->def->name, "help"))
                    continue;

1581
                help = vshCmddefSearch("help");
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
                vshCommandOptFree(first);
                first = vshMalloc(ctl, sizeof(vshCmdOpt));
                first->def = help->opts;
                first->data = vshStrdup(ctl, cmd->name);
                first->next = NULL;

                cmd = help;
                opts_required = 0;
                opts_seen = 0;
                break;
            }

            c->opts = first;
            c->def = cmd;
            c->next = NULL;
1597
            first = NULL;
1598

1599 1600
            if (!partial &&
                vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
1601 1602 1603 1604
                VIR_FREE(c);
                goto syntaxError;
            }

1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
            if (partial) {
                vshCommandFree(*partial);
                *partial = c;
            } else {
                if (!ctl->cmd)
                    ctl->cmd = c;
                if (clast)
                    clast->next = c;
                clast = c;
            }
1615 1616 1617 1618 1619 1620 1621 1622 1623
        }

        if (tk == VSH_TK_END)
            break;
    }

    return true;

 syntaxError:
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
    if (partial) {
        vshCmd *tmp;

        tmp = vshMalloc(ctl, sizeof(*tmp));
        tmp->opts = first;
        tmp->def = cmd;

        *partial = tmp;
    } else {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
        vshCommandOptFree(first);
    }
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
    VIR_FREE(tkdata);
    return false;
}

/* --------------------
 * Command argv parsing
 * --------------------
 */

static vshCommandToken ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
1647
vshCommandArgvGetArg(vshControl *ctl, vshCommandParser *parser, char **res,
J
Ján Tomko 已提交
1648
                     bool report G_GNUC_UNUSED)
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
{
    if (parser->arg_pos == parser->arg_end) {
        *res = NULL;
        return VSH_TK_END;
    }

    *res = vshStrdup(ctl, *parser->arg_pos);
    parser->arg_pos++;
    return VSH_TK_ARG;
}

bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
{
    vshCommandParser parser;

    if (nargs <= 0)
        return false;

    parser.arg_pos = argv;
    parser.arg_end = argv + nargs;
    parser.getNextArg = vshCommandArgvGetArg;
1671
    return vshCommandParse(ctl, &parser, NULL);
1672 1673 1674 1675 1676 1677 1678 1679
}

/* ----------------------
 * Command string parsing
 * ----------------------
 */

static vshCommandToken ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
1680 1681
vshCommandStringGetArg(vshControl *ctl, vshCommandParser *parser, char **res,
                       bool report)
1682 1683 1684 1685 1686 1687 1688 1689 1690
{
    bool single_quote = false;
    bool double_quote = false;
    int sz = 0;
    char *p = parser->pos;
    char *q = vshStrdup(ctl, p);

    *res = q;

1691 1692
    while (*p == ' ' || *p == '\t' || (*p == '\\' && p[1] == '\n'))
        p += 1 + (*p == '\\');
1693 1694 1695

    if (*p == '\0')
        return VSH_TK_END;
1696
    if (*p == ';' || *p == '\n') {
1697 1698 1699
        parser->pos = ++p;             /* = \0 or begin of next command */
        return VSH_TK_SUBCMD_END;
    }
1700 1701 1702 1703 1704 1705
    if (*p == '#') { /* Argument starting with # is comment to end of line */
        while (*p && *p != '\n')
            p++;
        parser->pos = p + !!*p;
        return VSH_TK_SUBCMD_END;
    }
1706 1707 1708 1709

    while (*p) {
        /* end of token is blank space or ';' */
        if (!double_quote && !single_quote &&
1710
            (*p == ' ' || *p == '\t' || *p == ';' || *p == '\n'))
1711 1712 1713 1714 1715 1716 1717 1718
            break;

        if (!double_quote && *p == '\'') { /* single quote */
            single_quote = !single_quote;
            p++;
            continue;
        } else if (!single_quote && *p == '\\') { /* escape */
            /*
1719
             * The same as in shell, a \ in "" is an escaper,
1720 1721 1722 1723
             * but a \ in '' is not an escaper.
             */
            p++;
            if (*p == '\0') {
1724 1725
                if (report)
                    vshError(ctl, "%s", _("dangling \\"));
1726
                return VSH_TK_ERROR;
1727 1728 1729 1730
            } else if (*p == '\n') {
                /* Elide backslash-newline entirely */
                p++;
                continue;
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
            }
        } else if (!single_quote && *p == '"') { /* double quote */
            double_quote = !double_quote;
            p++;
            continue;
        }

        *q++ = *p++;
        sz++;
    }
    if (double_quote) {
1742 1743
        if (report)
            vshError(ctl, "%s", _("missing \""));
1744 1745 1746 1747 1748 1749 1750 1751 1752
        return VSH_TK_ERROR;
    }

    *q = '\0';
    parser->pos = p;
    return VSH_TK_ARG;
}

bool
1753
vshCommandStringParse(vshControl *ctl, char *cmdstr, vshCmd **partial)
1754 1755 1756 1757 1758 1759 1760 1761
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
        return false;

    parser.pos = cmdstr;
    parser.getNextArg = vshCommandStringGetArg;
1762
    return vshCommandParse(ctl, &parser, partial);
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
}

/**
 * virshCommandOptTimeoutToMs:
 * @ctl virsh control structure
 * @cmd command reference
 * @timeout result
 *
 * Parse an optional --timeout parameter in seconds, but store the
 * value of the timeout in milliseconds.
 * See vshCommandOptInt()
 */
int
vshCommandOptTimeoutToMs(vshControl *ctl, const vshCmd *cmd, int *timeout)
{
    int ret;
    unsigned int utimeout;

    if ((ret = vshCommandOptUInt(ctl, cmd, "timeout", &utimeout)) <= 0)
        return ret;

    /* Ensure that the timeout is not zero and that we can convert
     * it from seconds to milliseconds without overflowing. */
    if (utimeout == 0 || utimeout > INT_MAX / 1000) {
        vshError(ctl,
                 _("Numeric value '%u' for <%s> option is malformed or out of range"),
                 utimeout,
                 "timeout");
        ret = -1;
    } else {
        *timeout = ((int) utimeout) * 1000;
    }

    return ret;
}


/* ---------------
 * Misc utils
 * ---------------
 */

/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
char *
vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
{
    int ret = 0;
    char *str = NULL;

    switch (item->type) {
    case VIR_TYPED_PARAM_INT:
        ret = virAsprintf(&str, "%d", item->value.i);
        break;

    case VIR_TYPED_PARAM_UINT:
        ret = virAsprintf(&str, "%u", item->value.ui);
        break;

    case VIR_TYPED_PARAM_LLONG:
        ret = virAsprintf(&str, "%lld", item->value.l);
        break;

    case VIR_TYPED_PARAM_ULLONG:
        ret = virAsprintf(&str, "%llu", item->value.ul);
        break;

    case VIR_TYPED_PARAM_DOUBLE:
        ret = virAsprintf(&str, "%f", item->value.d);
        break;

    case VIR_TYPED_PARAM_BOOLEAN:
        str = vshStrdup(ctl, item->value.b ? _("yes") : _("no"));
        break;

    case VIR_TYPED_PARAM_STRING:
        str = vshStrdup(ctl, item->value.s);
        break;

    default:
        vshError(ctl, _("unimplemented parameter type %d"), item->type);
    }

    if (ret < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        exit(EXIT_FAILURE);
    }
    return str;
}

void
vshDebug(vshControl *ctl, int level, const char *format, ...)
{
    va_list ap;
    char *str;

    /* Aligning log levels to that of libvirt.
     * Traces with levels >=  user-specified-level
     * gets logged into file
     */
    if (level < ctl->debug)
        return;

    va_start(ap, format);
    vshOutputLogFile(ctl, level, format, ap);
    va_end(ap);

    va_start(ap, format);
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
    va_end(ap);
    fputs(str, stdout);
    VIR_FREE(str);
}

void
vshPrintExtra(vshControl *ctl, const char *format, ...)
{
    va_list ap;
    char *str;

    if (ctl && ctl->quiet)
        return;

    va_start(ap, format);
1891 1892
    if (virVasprintfQuiet(&str, format, ap) < 0)
        vshErrorOOM();
1893 1894 1895 1896 1897 1898
    va_end(ap);
    fputs(str, stdout);
    VIR_FREE(str);
}


1899
void
J
Ján Tomko 已提交
1900
vshPrint(vshControl *ctl G_GNUC_UNUSED, const char *format, ...)
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
{
    va_list ap;
    char *str;

    va_start(ap, format);
    if (virVasprintfQuiet(&str, format, ap) < 0)
        vshErrorOOM();
    va_end(ap);
    fputs(str, stdout);
    VIR_FREE(str);
}


1914
bool
J
Ján Tomko 已提交
1915 1916
vshTTYIsInterruptCharacter(vshControl *ctl G_GNUC_UNUSED,
                           const char chr G_GNUC_UNUSED)
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
{
#ifndef WIN32
    if (ctl->istty &&
        ctl->termattr.c_cc[VINTR] == chr)
        return true;
#endif

    return false;
}


bool
vshTTYAvailable(vshControl *ctl)
{
    return ctl->istty;
}


int
J
Ján Tomko 已提交
1936
vshTTYDisableInterrupt(vshControl *ctl G_GNUC_UNUSED)
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
{
#ifndef WIN32
    struct termios termset = ctl->termattr;

    if (!ctl->istty)
        return -1;

    /* check if we need to set the terminal */
    if (termset.c_cc[VINTR] == _POSIX_VDISABLE)
        return 0;

    termset.c_cc[VINTR] = _POSIX_VDISABLE;
    termset.c_lflag &= ~ICANON;

    if (tcsetattr(STDIN_FILENO, TCSANOW, &termset) < 0)
        return -1;
#endif

    return 0;
}


int
J
Ján Tomko 已提交
1960
vshTTYRestore(vshControl *ctl G_GNUC_UNUSED)
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
{
#ifndef WIN32
    if (!ctl->istty)
        return 0;

    if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &ctl->termattr) < 0)
        return -1;
#endif

    return 0;
}


#if !defined(WIN32) && !defined(HAVE_CFMAKERAW)
/* provide fallback in case cfmakeraw isn't available */
static void
cfmakeraw(struct termios *attr)
{
    attr->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
                         | INLCR | IGNCR | ICRNL | IXON);
    attr->c_oflag &= ~OPOST;
    attr->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    attr->c_cflag &= ~(CSIZE | PARENB);
    attr->c_cflag |= CS8;
}
#endif /* !WIN32 && !HAVE_CFMAKERAW */


int
J
Ján Tomko 已提交
1990 1991
vshTTYMakeRaw(vshControl *ctl G_GNUC_UNUSED,
              bool report_errors G_GNUC_UNUSED)
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
{
#ifndef WIN32
    struct termios rawattr = ctl->termattr;
    char ebuf[1024];

    if (!ctl->istty) {
        if (report_errors) {
            vshError(ctl, "%s",
                     _("unable to make terminal raw: console isn't a tty"));
        }

        return -1;
    }

    cfmakeraw(&rawattr);

    if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &rawattr) < 0) {
        if (report_errors)
            vshError(ctl, _("unable to set tty attributes: %s"),
                     virStrerror(errno, ebuf, sizeof(ebuf)));
        return -1;
    }
#endif

    return 0;
}


void
vshError(vshControl *ctl, const char *format, ...)
{
    va_list ap;
    char *str;

    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }

    /* Most output is to stdout, but if someone ran virsh 2>&1, then
     * printing to stderr will not interleave correctly with stdout
     * unless we flush between every transition between streams.  */
    fflush(stdout);
    fputs(_("error: "), stderr);

    va_start(ap, format);
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
    va_end(ap);

    fprintf(stderr, "%s\n", NULLSTR(str));
    fflush(stderr);
    VIR_FREE(str);
}


void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
            vshReportError(ctl);
    }
}


/*
 * Helpers for waiting for a libvirt event.
 */

/* We want to use SIGINT to cancel a wait; but as signal handlers
 * don't have an opaque argument, we have to use static storage.  */
static int vshEventFd = -1;
static struct sigaction vshEventOldAction;


/* Signal handler installed in vshEventStart, removed in vshEventCleanup.  */
static void
J
Ján Tomko 已提交
2082 2083 2084
vshEventInt(int sig G_GNUC_UNUSED,
            siginfo_t *siginfo G_GNUC_UNUSED,
            void *context G_GNUC_UNUSED)
2085 2086 2087 2088 2089 2090 2091 2092 2093
{
    char reason = VSH_EVENT_INTERRUPT;
    if (vshEventFd >= 0)
        ignore_value(safewrite(vshEventFd, &reason, 1));
}


/* Event loop handler used to limit length of waiting for any other event. */
void
J
Ján Tomko 已提交
2094
vshEventTimeout(int timer G_GNUC_UNUSED,
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
                void *opaque)
{
    vshControl *ctl = opaque;
    char reason = VSH_EVENT_TIMEOUT;

    if (ctl->eventPipe[1] >= 0)
        ignore_value(safewrite(ctl->eventPipe[1], &reason, 1));
}


/**
 * vshEventStart:
 * @ctl vsh command struct
 * @timeout_ms max wait time in milliseconds, or 0 for indefinite
 *
 * Set up a wait for a libvirt event.  The wait can be canceled by
 * SIGINT or by calling vshEventDone() in your event handler.  If
 * @timeout_ms is positive, the wait will also end if the timeout
 * expires.  Call vshEventWait() to block the main thread (the event
 * handler runs in the event loop thread).  When done (including if
 * there was an error registering for an event), use vshEventCleanup()
 * to quit waiting.  Returns 0 on success, -1 on failure.  */
int
vshEventStart(vshControl *ctl, int timeout_ms)
{
    struct sigaction action;

    assert(ctl->eventPipe[0] == -1 && ctl->eventPipe[1] == -1 &&
           vshEventFd == -1 && ctl->eventTimerId >= 0);
    if (pipe2(ctl->eventPipe, O_CLOEXEC) < 0) {
        char ebuf[1024];

        vshError(ctl, _("failed to create pipe: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)));
        return -1;
    }
    vshEventFd = ctl->eventPipe[1];

    action.sa_sigaction = vshEventInt;
    action.sa_flags = SA_SIGINFO;
    sigemptyset(&action.sa_mask);
    sigaction(SIGINT, &action, &vshEventOldAction);

    if (timeout_ms)
        virEventUpdateTimeout(ctl->eventTimerId, timeout_ms);

    return 0;
}


/**
 * vshEventDone:
 * @ctl vsh command struct
 *
 * Call this from an event callback to let the main thread quit
 * blocking on further events.
 */
void
vshEventDone(vshControl *ctl)
{
    char reason = VSH_EVENT_DONE;

    if (ctl->eventPipe[1] >= 0)
        ignore_value(safewrite(ctl->eventPipe[1], &reason, 1));
}


/**
 * vshEventWait:
 * @ctl vsh command struct
 *
 * Call this in the main thread after calling vshEventStart() then
 * registering for one or more events.  This call will block until
 * SIGINT, the timeout registered at the start, or until one of your
 * event handlers calls vshEventDone().  Returns an enum VSH_EVENT_*
 * stating how the wait concluded, or -1 on error.
 */
int
vshEventWait(vshControl *ctl)
{
    char buf;
    int rv;

    assert(ctl->eventPipe[0] >= 0);
    while ((rv = read(ctl->eventPipe[0], &buf, 1)) < 0 && errno == EINTR);
    if (rv != 1) {
        char ebuf[1024];

        if (!rv)
            errno = EPIPE;
        vshError(ctl, _("failed to determine loop exit status: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)));
        return -1;
    }
    return buf;
}


/**
 * vshEventCleanup:
 * @ctl vsh control struct
 *
 * Call at the end of any function that has used vshEventStart(), to
 * tear down any remaining SIGINT or timeout handlers.
 */
void
vshEventCleanup(vshControl *ctl)
{
    if (vshEventFd >= 0) {
        sigaction(SIGINT, &vshEventOldAction, NULL);
        vshEventFd = -1;
    }
    VIR_FORCE_CLOSE(ctl->eventPipe[0]);
    VIR_FORCE_CLOSE(ctl->eventPipe[1]);
    virEventUpdateTimeout(ctl->eventTimerId, -1);
}

#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
void
vshOpenLogFile(vshControl *ctl)
{
    if (ctl->logfile == NULL)
        return;

    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
        vshError(ctl, "%s",
                 _("failed to open the log file. check the log file path"));
        exit(EXIT_FAILURE);
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
void
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *str = NULL;
    size_t len;
    const char *lvl = "";
    time_t stTime;
    struct tm stTm;

    if (ctl->log_fd == -1)
        return;

    /**
     * create log format
     *
     * [YYYY.MM.DD HH:MM:SS SIGNATURE PID] LOG_LEVEL message
    */
    time(&stTime);
    localtime_r(&stTime, &stTm);
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
                      (1900 + stTm.tm_year),
                      (1 + stTm.tm_mon),
                      stTm.tm_mday,
                      stTm.tm_hour,
                      stTm.tm_min,
                      stTm.tm_sec,
                      ctl->progname,
                      (int) getpid());
    switch (log_level) {
        case VSH_ERR_DEBUG:
            lvl = LVL_DEBUG;
            break;
        case VSH_ERR_INFO:
            lvl = LVL_INFO;
            break;
        case VSH_ERR_NOTICE:
            lvl = LVL_INFO;
            break;
        case VSH_ERR_WARNING:
            lvl = LVL_WARNING;
            break;
        case VSH_ERR_ERROR:
            lvl = LVL_ERROR;
            break;
        default:
            lvl = LVL_DEBUG;
            break;
    }
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
2289
    virBufferTrim(&buf, "\n", -1);
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
    virBufferAddChar(&buf, '\n');

    if (virBufferError(&buf))
        goto error;

    str = virBufferContentAndReset(&buf);
    len = strlen(str);

    /* write log */
    if (safewrite(ctl->log_fd, str, len) < 0)
        goto error;

    VIR_FREE(str);
    return;

 error:
    vshCloseLogFile(ctl);
    vshError(ctl, "%s", _("failed to write the log file"));
    virBufferFreeAndReset(&buf);
    VIR_FREE(str);
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
void
vshCloseLogFile(vshControl *ctl)
{
    char ebuf[1024];

    /* log file close */
    if (VIR_CLOSE(ctl->log_fd) < 0) {
        vshError(ctl, _("%s: failed to write log file: %s"),
                 ctl->logfile ? ctl->logfile : "?",
                 virStrerror(errno, ebuf, sizeof(ebuf)));
    }

    if (ctl->logfile) {
        VIR_FREE(ctl->logfile);
        ctl->logfile = NULL;
    }
}

#ifndef WIN32
static void
vshPrintRaw(vshControl *ctl, ...)
{
    va_list ap;
    char *key;

    va_start(ap, ctl);
    while ((key = va_arg(ap, char *)) != NULL)
        vshPrint(ctl, "%s\r\n", key);
    va_end(ap);
}

/**
 * vshAskReedit:
 * @msg: Question to ask user
 *
 * Ask user if he wants to return to previously
 * edited file.
 *
 * Returns 'y' if he wants to
 *         'n' if he doesn't want to
 *         'i' if he wants to try defining it again while ignoring validation
 *         'f' if he forcibly wants to
 *         -1  on error
 *          0  otherwise
 */
int
vshAskReedit(vshControl *ctl, const char *msg, bool relax_avail)
{
    int c = -1;

    if (!isatty(STDIN_FILENO))
        return -1;

    vshReportError(ctl);

    if (vshTTYMakeRaw(ctl, false) < 0)
        return -1;

    while (true) {
        vshPrint(ctl, "\r%s %s %s: ", msg, _("Try again?"),
                 relax_avail ? "[y,n,i,f,?]" : "[y,n,f,?]");
        c = c_tolower(getchar());

        if (c == '?') {
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
                        NULL);

            if (relax_avail) {
                vshPrintRaw(ctl,
                            _("i - turn off validation and try to redefine "
                              "again"),
                            NULL);
            }

            vshPrintRaw(ctl,
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
            continue;
        } else if (c == 'y' || c == 'n' || c == 'f' ||
                   (relax_avail && c == 'i')) {
            break;
        }
    }

    vshTTYRestore(ctl);

    vshPrint(ctl, "\r\n");
    return c;
}
#else /* WIN32 */
int
vshAskReedit(vshControl *ctl,
J
Ján Tomko 已提交
2413 2414
             const char *msg G_GNUC_UNUSED,
             bool relax_avail G_GNUC_UNUSED)
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
{
    vshDebug(ctl, VSH_ERR_WARNING, "%s", _("This function is not "
                                           "supported on WIN32 platform"));
    return 0;
}
#endif /* WIN32 */


/* Common code for the edit / net-edit / pool-edit functions which follow. */
char *
vshEditWriteToTempFile(vshControl *ctl, const char *doc)
{
    char *ret;
    const char *tmpdir;
    int fd;
    char ebuf[1024];

2432
    tmpdir = getenv("TMPDIR");
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
    if (!tmpdir) tmpdir = "/tmp";
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
    fd = mkostemps(ret, 4, O_CLOEXEC);
    if (fd == -1) {
        vshError(ctl, _("mkostemps: failed to create temporary file: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)));
        VIR_FREE(ret);
        return NULL;
    }

    if (safewrite(fd, doc, strlen(doc)) == -1) {
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
        VIR_FORCE_CLOSE(fd);
        unlink(ret);
        VIR_FREE(ret);
        return NULL;
    }
    if (VIR_CLOSE(fd) < 0) {
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
        unlink(ret);
        VIR_FREE(ret);
        return NULL;
    }

    /* Temporary filename: caller frees. */
    return ret;
}

/* Characters permitted in $EDITOR environment variable and temp filename. */
#define ACCEPTED_CHARS \
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-/_.:@"

int
vshEditFile(vshControl *ctl, const char *filename)
{
    const char *editor;
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;

2479
    editor = getenv("VISUAL");
2480
    if (!editor)
2481
        editor = getenv("EDITOR");
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
    if (!editor)
        editor = DEFAULT_EDITOR;

    /* Check that filename doesn't contain shell meta-characters, and
     * if it does, refuse to run.  Follow the Unix conventions for
     * EDITOR: the user can intentionally specify command options, so
     * we don't protect any shell metacharacters there.  Lots more
     * than virsh will misbehave if EDITOR has bogus contents (which
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
     */
    if (strspn(editor, ACCEPTED_CHARS) != strlen(editor)) {
        if (strspn(filename, ACCEPTED_CHARS) != strlen(filename)) {
            vshError(ctl,
                     _("%s: temporary filename contains shell meta or other "
                       "unacceptable characters (is $TMPDIR wrong?)"),
                     filename);
            return -1;
        }
        cmd = virCommandNewArgList("sh", "-c", NULL);
        virCommandAddArgFormat(cmd, "%s %s", editor, filename);
    } else {
        cmd = virCommandNewArgList(editor, filename, NULL);
    }

    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
        vshReportError(ctl);
        goto cleanup;
    }
    ret = 0;

 cleanup:
    virCommandFree(cmd);
    return ret;
}

char *
vshEditReadBackFile(vshControl *ctl, const char *filename)
{
    char *ret;
    char ebuf[1024];

    if (virFileReadAll(filename, VSH_MAX_XML_FILE, &ret) == -1) {
        vshError(ctl,
                 _("%s: failed to read temporary file: %s"),
                 filename, virStrerror(errno, ebuf, sizeof(ebuf)));
        return NULL;
    }
    return ret;
}


/* Tree listing helpers.  */

static int
vshTreePrintInternal(vshControl *ctl,
                     vshTreeLookup lookup,
                     void *opaque,
                     int num_devices,
                     int devid,
                     int lastdev,
                     bool root,
                     virBufferPtr indent)
{
    size_t i;
    int nextlastdev = -1;
    int ret = -1;
    const char *dev = (lookup)(devid, false, opaque);

    if (virBufferError(indent))
        goto cleanup;

    /* Print this device, with indent if not at root */
    vshPrint(ctl, "%s%s%s\n", virBufferCurrentContent(indent),
             root ? "" : "+- ", dev);

    /* Update indent to show '|' or ' ' for child devices */
    if (!root) {
        virBufferAddChar(indent, devid == lastdev ? ' ' : '|');
        virBufferAddChar(indent, ' ');
        if (virBufferError(indent))
            goto cleanup;
    }

    /* Determine the index of the last child device */
    for (i = 0; i < num_devices; i++) {
        const char *parent = (lookup)(i, true, opaque);

        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }

    /* If there is a child device, then print another blank line */
    if (nextlastdev != -1)
        vshPrint(ctl, "%s  |\n", virBufferCurrentContent(indent));

    /* Finally print all children */
    virBufferAddLit(indent, "  ");
    if (virBufferError(indent))
        goto cleanup;
    for (i = 0; i < num_devices; i++) {
        const char *parent = (lookup)(i, true, opaque);

        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
    }
    virBufferTrim(indent, "  ", -1);

    /* If there was no child device, and we're the last in
     * a list of devices, then print another blank line */
    if (nextlastdev == -1 && devid == lastdev)
        vshPrint(ctl, "%s\n", virBufferCurrentContent(indent));

    if (!root)
        virBufferTrim(indent, NULL, 2);
    ret = 0;
 cleanup:
    return ret;
}

int
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
{
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;

    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
    return ret;
}

#if WITH_READLINE

/* -----------------
 * Readline stuff
 * -----------------
 */

2631 2632 2633 2634 2635 2636 2637 2638
/**
 * vshReadlineCommandGenerator:
 * @text: optional command prefix
 *
 * Generator function for command completion.
 *
 * Returns a string list of commands with @text prefix,
 * NULL if there's no such command.
2639
 */
2640 2641
static char **
vshReadlineCommandGenerator(const char *text)
2642
{
2643 2644
    size_t grp_list_index = 0, cmd_list_index = 0;
    size_t len = strlen(text);
2645 2646 2647
    const char *name;
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
2648 2649
    size_t ret_size = 0;
    char **ret = NULL;
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660

    grp = cmdGroups;

    /* Return the next name which partially matches from the
     * command list.
     */
    while (grp[grp_list_index].name) {
        cmds = grp[grp_list_index].commands;

        if (cmds[cmd_list_index].name) {
            while ((name = cmds[cmd_list_index].name)) {
2661 2662
                if (cmds[cmd_list_index++].flags & VSH_CMD_FLAG_ALIAS)
                    continue;
2663

2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
                if (STREQLEN(name, text, len)) {
                    if (VIR_REALLOC_N(ret, ret_size + 2) < 0) {
                        virStringListFree(ret);
                        return NULL;
                    }
                    ret[ret_size] = vshStrdup(NULL, name);
                    ret_size++;
                    /* Terminate the string list properly. */
                    ret[ret_size] = NULL;
                }
2674 2675 2676 2677 2678 2679 2680
            }
        } else {
            cmd_list_index = 0;
            grp_list_index++;
        }
    }

2681
    return ret;
2682 2683
}

2684
static char **
2685 2686 2687
vshReadlineOptionsGenerator(const char *text,
                            const vshCmdDef *cmd,
                            vshCmd *last)
2688
{
2689 2690
    size_t list_index = 0;
    size_t len = strlen(text);
2691
    const char *name;
2692 2693
    size_t ret_size = 0;
    char **ret = NULL;
2694 2695 2696 2697 2698 2699 2700 2701

    if (!cmd)
        return NULL;

    if (!cmd->opts)
        return NULL;

    while ((name = cmd->opts[list_index].name)) {
2702 2703
        bool exists = false;
        vshCmdOpt *opt =  last->opts;
2704
        size_t name_len;
2705 2706 2707 2708

        list_index++;

        if (len > 2) {
2709 2710 2711
            /* provide auto-complete only when the text starts with -- */
            if (STRNEQLEN(text, "--", 2))
                return NULL;
2712 2713
            if (STRNEQLEN(name, text + 2, len - 2))
                continue;
2714 2715
        } else if (STRNEQLEN(text, "--", len)) {
            return NULL;
2716
        }
2717

2718
        while (opt) {
2719
            if (STREQ(opt->def->name, name) && opt->def->type != VSH_OT_ARGV) {
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
                exists = true;
                break;
            }

            opt = opt->next;
        }

        if (exists)
            continue;

2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740
        if (VIR_REALLOC_N(ret, ret_size + 2) < 0) {
            virStringListFree(ret);
            return NULL;
        }

        name_len = strlen(name);
        ret[ret_size] = vshMalloc(NULL, name_len + 3);
        snprintf(ret[ret_size], name_len + 3,  "--%s", name);
        ret_size++;
        /* Terminate the string list properly. */
        ret[ret_size] = NULL;
2741 2742
    }

2743
    return ret;
2744 2745
}

2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775

static const vshCmdOptDef *
vshReadlineCommandFindOpt(const vshCmd *partial,
                          const char *text)
{
    const vshCmd *tmp = partial;

    while (tmp && tmp->next) {
        if (tmp->def == tmp->next->def &&
            !tmp->next->opts)
            break;
        tmp = tmp->next;
    }

    if (tmp && tmp->opts) {
        const vshCmdOpt *opt = tmp->opts;

        while (opt) {
            if (STREQ_NULLABLE(opt->data, text) ||
                STREQ_NULLABLE(opt->data, " "))
                return opt->def;

            opt = opt->next;
        }
    }

    return NULL;
}


2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
static int
vshCompleterFilter(char ***list,
                   const char *text)
{
    char **newList = NULL;
    size_t newList_len = 0;
    size_t list_len;
    size_t i;

    if (!list || !*list)
        return -1;

    list_len = virStringListLength((const char **) *list);

    if (VIR_ALLOC_N(newList, list_len + 1) < 0)
        return -1;

    for (i = 0; i < list_len; i++) {
        if (!STRPREFIX((*list)[i], text)) {
            VIR_FREE((*list)[i]);
            continue;
        }

2799
        newList[newList_len] = g_steal_pointer(&(*list)[i]);
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809
        newList_len++;
    }

    ignore_value(VIR_REALLOC_N_QUIET(newList, newList_len + 1));
    VIR_FREE(*list);
    *list = newList;
    return 0;
}


2810 2811 2812
static char *
vshReadlineParse(const char *text, int state)
{
2813
    static vshCmd *partial;
2814 2815 2816
    static char **list;
    static size_t list_index;
    const vshCmdDef *cmd = NULL;
2817
    const vshCmdOptDef *opt = NULL;
2818
    char *ret = NULL;
2819 2820

    if (!state) {
2821
        char *buf = vshStrdup(NULL, rl_line_buffer);
2822

2823 2824
        vshCommandFree(partial);
        partial = NULL;
2825 2826 2827
        virStringListFree(list);
        list = NULL;
        list_index = 0;
2828

2829
        *(buf + rl_point) = '\0';
2830

2831
        vshCommandStringParse(NULL, buf, &partial);
2832

2833
        VIR_FREE(buf);
2834

2835
        if (partial) {
2836
            cmd = partial->def;
2837 2838
            partial->skipChecks = true;
        }
2839

2840 2841 2842 2843 2844 2845 2846 2847 2848
        if (cmd && STREQ(cmd->name, text)) {
            /* Corner case - some commands share prefix (e.g.
             * dump and dumpxml). If user typed 'dump<TAB><TAB>',
             * then @text = "dump" and we want to offer command
             * completion. If they typed 'dump <TAB><TAB>' then
             * @text = "" (the space after the command) and we
             * want to offer options completion for dump command.
             */
            cmd = NULL;
2849
        }
2850 2851

        opt = vshReadlineCommandFindOpt(partial, text);
2852
    }
2853

2854 2855 2856 2857
    if (!list) {
        if (!cmd) {
            list = vshReadlineCommandGenerator(text);
        } else {
2858 2859 2860
            if (!opt || (opt->type != VSH_OT_DATA &&
                         opt->type != VSH_OT_STRING &&
                         opt->type != VSH_OT_ARGV))
2861
                list = vshReadlineOptionsGenerator(text, cmd, partial);
M
Michal Privoznik 已提交
2862

2863 2864 2865 2866
            if (opt && opt->completer) {
                char **completer_list = opt->completer(autoCompleteOpaque,
                                                       partial,
                                                       opt->completer_flags);
2867 2868 2869 2870 2871 2872 2873 2874

                /* For string list returned by completer we have to do
                 * filtering based on @text because completer returns all
                 * possible strings. */

                if (completer_list &&
                    (vshCompleterFilter(&completer_list, text) < 0 ||
                     virStringListMerge(&list, &completer_list) < 0)) {
2875 2876 2877 2878
                    virStringListFree(completer_list);
                    goto cleanup;
                }
            }
2879 2880 2881 2882 2883 2884
        }
    }

    if (list) {
        ret = vshStrdup(NULL, list[list_index]);
        list_index++;
2885 2886
    }

2887
    if (ret &&
2888 2889
        !rl_completion_quote_character) {
        virBuffer buf = VIR_BUFFER_INITIALIZER;
2890 2891 2892
        virBufferEscapeShell(&buf, ret);
        VIR_FREE(ret);
        ret = virBufferContentAndReset(&buf);
2893 2894
    }

2895
 cleanup:
2896
    if (!ret) {
2897 2898
        vshCommandFree(partial);
        partial = NULL;
2899 2900 2901
        virStringListFree(list);
        list = NULL;
        list_index = 0;
2902 2903
    }

2904 2905
    return ret;

2906 2907
}

2908
static char **
2909
vshReadlineCompletion(const char *text,
J
Ján Tomko 已提交
2910 2911
                      int start G_GNUC_UNUSED,
                      int end G_GNUC_UNUSED)
2912 2913 2914
{
    char **matches = (char **) NULL;

2915
    matches = rl_completion_matches(text, vshReadlineParse);
2916 2917 2918
    return matches;
}

2919 2920 2921 2922 2923 2924 2925 2926 2927 2928

static int
vshReadlineCharIsQuoted(char *line, int idx)
{
    return idx > 0 &&
           line[idx - 1] == '\\' &&
           !vshReadlineCharIsQuoted(line, idx - 1);
}


2929 2930 2931 2932 2933 2934 2935 2936
# define HISTSIZE_MAX 500000

static int
vshReadlineInit(vshControl *ctl)
{
    char *userdir = NULL;
    int max_history = 500;
    int ret = -1;
2937
    char *histsize_env = NULL;
2938
    const char *histsize_str = NULL;
2939
    const char *break_characters = " \t\n\\`@$><=;|&{(";
2940
    const char *quote_characters = "\"'";
2941

2942 2943 2944
    /* Opaque data for autocomplete callbacks. */
    autoCompleteOpaque = ctl;

2945 2946 2947 2948 2949
    rl_readline_name = ctl->name;

    /* Tell the completer that we want a crack first. */
    rl_attempted_completion_function = vshReadlineCompletion;

2950
    rl_basic_word_break_characters = break_characters;
2951

2952 2953 2954
    rl_completer_quote_characters = quote_characters;
    rl_char_is_quoted_p = vshReadlineCharIsQuoted;

2955
    if (virAsprintf(&histsize_env, "%s_HISTSIZE", ctl->env_prefix) < 0)
2956 2957 2958
        goto cleanup;

    /* Limit the total size of the history buffer */
2959
    if ((histsize_str = getenv(histsize_env))) {
2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996
        if (virStrToLong_i(histsize_str, NULL, 10, &max_history) < 0) {
            vshError(ctl, _("Bad $%s value."), histsize_env);
            goto cleanup;
        } else if (max_history > HISTSIZE_MAX || max_history < 0) {
            vshError(ctl, _("$%s value should be between 0 "
                            "and %d"),
                     histsize_env, HISTSIZE_MAX);
            goto cleanup;
        }
    }
    stifle_history(max_history);

    /* Prepare to read/write history from/to the
     * $XDG_CACHE_HOME/virtshell/history file
     */
    userdir = virGetUserCacheDirectory();

    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
        goto cleanup;
    }

    if (virAsprintf(&ctl->historydir, "%s/%s", userdir, ctl->name) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        goto cleanup;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        goto cleanup;
    }

    read_history(ctl->historyfile);
    ret = 0;

 cleanup:
    VIR_FREE(userdir);
2997
    VIR_FREE(histsize_env);
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019
    return ret;
}

static void
vshReadlineDeinit(vshControl *ctl)
{
    if (ctl->historyfile != NULL) {
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
        } else {
            write_history(ctl->historyfile);
        }
    }

    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
}

char *
J
Ján Tomko 已提交
3020
vshReadline(vshControl *ctl G_GNUC_UNUSED, const char *prompt)
3021 3022 3023 3024 3025 3026 3027
{
    return readline(prompt);
}

#else /* !WITH_READLINE */

static int
J
Ján Tomko 已提交
3028
vshReadlineInit(vshControl *ctl G_GNUC_UNUSED)
3029 3030 3031 3032 3033 3034
{
    /* empty */
    return 0;
}

static void
J
Ján Tomko 已提交
3035
vshReadlineDeinit(vshControl *ctl G_GNUC_UNUSED)
3036 3037 3038 3039
{
    /* empty */
}

3040
char *
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
vshReadline(vshControl *ctl, const char *prompt)
{
    char line[1024];
    char *r;
    int len;

    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
    if (r == NULL) return NULL; /* EOF */

    /* Chomp trailing \n */
    len = strlen(r);
    if (len > 0 && r[len-1] == '\n')
        r[len-1] = '\0';

    return vshStrdup(ctl, r);
}

#endif /* !WITH_READLINE */

/*
 * Initialize debug settings.
 */
3064
static int
3065 3066 3067
vshInitDebug(vshControl *ctl)
{
    const char *debugEnv;
3068
    char *env = NULL;
3069 3070

    if (ctl->debug == VSH_DEBUG_DEFAULT) {
3071 3072 3073
        if (virAsprintf(&env, "%s_DEBUG", ctl->env_prefix) < 0)
            return -1;

3074
        /* log level not set from commandline, check env variable */
3075
        debugEnv = getenv(env);
3076 3077 3078 3079
        if (debugEnv) {
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
3080 3081
                vshError(ctl, _("%s_DEBUG not set with a valid numeric value"),
                         ctl->env_prefix);
3082 3083 3084 3085
            } else {
                ctl->debug = debug;
            }
        }
3086
        VIR_FREE(env);
3087 3088 3089
    }

    if (ctl->logfile == NULL) {
3090 3091 3092
        if (virAsprintf(&env, "%s_LOG_FILE", ctl->env_prefix) < 0)
            return -1;

3093
        /* log file not set from cmdline */
3094
        debugEnv = getenv(env);
3095 3096 3097 3098
        if (debugEnv && *debugEnv) {
            ctl->logfile = vshStrdup(ctl, debugEnv);
            vshOpenLogFile(ctl);
        }
3099
        VIR_FREE(env);
3100
    }
3101 3102

    return 0;
3103 3104 3105 3106 3107 3108
}


/*
 * Initialize global data
 */
3109
bool
3110 3111 3112 3113
vshInit(vshControl *ctl, const vshCmdGrp *groups, const vshCmdDef *set)
{
    if (!ctl->hooks) {
        vshError(ctl, "%s", _("client hooks cannot be NULL"));
3114
        return false;
3115 3116 3117 3118 3119
    }

    if (!groups && !set) {
        vshError(ctl, "%s", _("command groups and command set "
                              "cannot both be NULL"));
3120
        return false;
3121 3122 3123 3124 3125
    }

    cmdGroups = groups;
    cmdSet = set;

3126 3127
    if (vshInitDebug(ctl) < 0 ||
        (ctl->imode && vshReadlineInit(ctl) < 0))
3128
        return false;
3129

3130
    return true;
3131 3132
}

E
Erik Skultety 已提交
3133 3134 3135 3136 3137 3138 3139 3140 3141
bool
vshInitReload(vshControl *ctl)
{
    if (!cmdGroups && !cmdSet) {
        vshError(ctl, "%s", _("command groups and command are both NULL "
                              "run vshInit before reloading"));
        return false;
    }

3142 3143
    if (vshInitDebug(ctl) < 0)
        return false;
E
Erik Skultety 已提交
3144 3145 3146 3147 3148 3149 3150 3151 3152

    if (ctl->imode)
        vshReadlineDeinit(ctl);
    if (ctl->imode && vshReadlineInit(ctl) < 0)
        return false;

    return true;
}

3153 3154 3155
void
vshDeinit(vshControl *ctl)
{
3156 3157 3158
    /* NB: Don't make calling of vshReadlineDeinit conditional on active
     * interactive mode. */
    vshReadlineDeinit(ctl);
3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
    vshCloseLogFile(ctl);
}

/* -----------------------------------------------
 * Generic commands available to use by any client
 * -----------------------------------------------
 */
const vshCmdOptDef opts_help[] = {
    {.name = "command",
     .type = VSH_OT_STRING,
     .help = N_("Prints global help, command specific help, or help for a group of related commands")
    },
    {.name = NULL}
};

const vshCmdInfo info_help[] = {
    {.name = "help",
     .data = N_("print help")
    },
    {.name = "desc",
     .data = N_("Prints global help, command specific help, or help for a\n"
                "    group of related commands")
    },
    {.name = NULL}
};

bool
cmdHelp(vshControl *ctl, const vshCmd *cmd)
J
Ján Tomko 已提交
3187
{
3188 3189
    const vshCmdDef *def = NULL;
    const vshCmdGrp *grp = NULL;
3190 3191
    const char *name = NULL;

3192
    if (vshCommandOptStringQuiet(ctl, cmd, "command", &name) <= 0) {
3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

        for (grp = cmdGroups; grp->name; grp++) {
            vshPrint(ctl, _(" %s (help keyword '%s'):\n"), grp->name,
                     grp->keyword);

            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
            }

            vshPrint(ctl, "\n");
        }

        return true;
    }

3212
    if ((def = vshCmddefSearch(name))) {
3213 3214
        if (def->flags & VSH_CMD_FLAG_ALIAS)
            def = vshCmddefSearch(def->alias);
3215 3216 3217
        return vshCmddefHelp(ctl, def);
    } else if ((grp = vshCmdGrpSearch(name))) {
        return vshCmdGrpHelp(ctl, grp);
3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
        return false;
    }
}

const vshCmdOptDef opts_cd[] = {
    {.name = "dir",
     .type = VSH_OT_STRING,
     .help = N_("directory to switch to (default: home or else root)")
    },
    {.name = NULL}
};

const vshCmdInfo info_cd[] = {
    {.name = "help",
     .data = N_("change the current directory")
    },
    {.name = "desc",
     .data = N_("Change the current directory.")
    },
    {.name = NULL}
};

bool
cmdCd(vshControl *ctl, const vshCmd *cmd)
{
    const char *dir = NULL;
    char *dir_malloced = NULL;
    bool ret = true;
    char ebuf[1024];

    if (!ctl->imode) {
        vshError(ctl, "%s", _("cd: command valid only in interactive mode"));
        return false;
    }

3255
    if (vshCommandOptStringQuiet(ctl, cmd, "dir", &dir) <= 0)
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
        dir = dir_malloced = virGetUserDirectory();
    if (!dir)
        dir = "/";

    if (chdir(dir) == -1) {
        vshError(ctl, _("cd: %s: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)), dir);
        ret = false;
    }

    VIR_FREE(dir_malloced);
    return ret;
}

const vshCmdOptDef opts_echo[] = {
    {.name = "shell",
     .type = VSH_OT_BOOL,
     .help = N_("escape for shell use")
    },
    {.name = "xml",
     .type = VSH_OT_BOOL,
     .help = N_("escape for XML use")
    },
E
Eric Blake 已提交
3279 3280 3281 3282
    {.name = "err",
     .type = VSH_OT_BOOL,
     .help = N_("output to stderr"),
    },
3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
    {.name = "str",
     .type = VSH_OT_ALIAS,
     .help = "string"
    },
    {.name = "hi",
     .type = VSH_OT_ALIAS,
     .help = "string=hello"
    },
    {.name = "string",
     .type = VSH_OT_ARGV,
     .help = N_("arguments to echo")
    },
    {.name = NULL}
};

const vshCmdInfo info_echo[] = {
    {.name = "help",
     .data = N_("echo arguments")
    },
    {.name = "desc",
     .data = N_("Echo back arguments, possibly with quoting.")
    },
    {.name = NULL}
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
bool
cmdEcho(vshControl *ctl, const vshCmd *cmd)
{
    bool shell = false;
    bool xml = false;
E
Eric Blake 已提交
3316
    bool err = false;
3317 3318 3319 3320 3321 3322 3323 3324 3325
    int count = 0;
    const vshCmdOpt *opt = NULL;
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    if (vshCommandOptBool(cmd, "shell"))
        shell = true;
    if (vshCommandOptBool(cmd, "xml"))
        xml = true;
E
Eric Blake 已提交
3326 3327
    if (vshCommandOptBool(cmd, "err"))
        err = true;
3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340

    while ((opt = vshCommandOptArgv(ctl, cmd, opt))) {
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;

        arg = opt->data;

        if (count)
            virBufferAddChar(&buf, ' ');

        if (xml) {
            virBufferEscapeString(&xmlbuf, "%s", arg);
            if (virBufferError(&xmlbuf)) {
3341
                vshError(ctl, "%s", _("Failed to allocate XML buffer"));
3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
                return false;
            }
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
        }

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
        count++;
        VIR_FREE(str);
    }

    if (virBufferError(&buf)) {
3358
        vshError(ctl, "%s", _("Failed to allocate XML buffer"));
3359 3360 3361
        return false;
    }
    arg = virBufferContentAndReset(&buf);
E
Eric Blake 已提交
3362 3363 3364 3365 3366 3367
    if (arg) {
        if (err)
            vshError(ctl, "%s", arg);
        else
            vshPrint(ctl, "%s", arg);
    }
3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382
    VIR_FREE(arg);
    return true;
}

const vshCmdInfo info_pwd[] = {
    {.name = "help",
     .data = N_("print the current directory")
    },
    {.name = "desc",
     .data = N_("Print the current directory.")
    },
    {.name = NULL}
};

bool
J
Ján Tomko 已提交
3383
cmdPwd(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412
{
    char *cwd;
    bool ret = true;
    char ebuf[1024];

    cwd = getcwd(NULL, 0);
    if (!cwd) {
        vshError(ctl, _("pwd: cannot get current directory: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)));
        ret = false;
    } else {
        vshPrint(ctl, _("%s\n"), cwd);
        VIR_FREE(cwd);
    }

    return ret;
}

const vshCmdInfo info_quit[] = {
    {.name = "help",
     .data = N_("quit this interactive terminal")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
};

bool
J
Ján Tomko 已提交
3413
cmdQuit(vshControl *ctl, const vshCmd *cmd G_GNUC_UNUSED)
3414 3415 3416 3417
{
    ctl->imode = false;
    return true;
}
3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436

/* -----------------
 * Command self-test
 * ----------------- */

const vshCmdInfo info_selftest[] = {
    {.name = "help",
     .data = N_("internal command for testing virt shells")
    },
    {.name = "desc",
     .data = N_("internal use only")
    },
    {.name = NULL}
};

/* Prints help for every command.
 * That runs vshCmddefOptParse which validates
 * the per-command options structure. */
bool
3437
cmdSelfTest(vshControl *ctl,
J
Ján Tomko 已提交
3438
            const vshCmd *cmd G_GNUC_UNUSED)
3439 3440 3441 3442 3443 3444
{
    const vshCmdGrp *grp;
    const vshCmdDef *def;

    for (grp = cmdGroups; grp->name; grp++) {
        for (def = grp->commands; def->name; def++) {
3445
            if (vshCmddefCheckInternals(ctl, def) < 0)
3446 3447 3448 3449 3450 3451
                return false;
        }
    }

    return true;
}
3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475

/* ----------------------
 * Autocompletion command
 * ---------------------- */

const vshCmdOptDef opts_complete[] = {
    {.name = "string",
     .type = VSH_OT_ARGV,
     .flags = VSH_OFLAG_EMPTY_OK,
     .help = N_("partial string to autocomplete")
    },
    {.name = NULL}
};

const vshCmdInfo info_complete[] = {
    {.name = "help",
     .data = N_("internal command for autocompletion")
    },
    {.name = "desc",
     .data = N_("internal use only")
    },
    {.name = NULL}
};

3476 3477

#ifdef WITH_READLINE
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522
bool
cmdComplete(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    const vshClientHooks *hooks = ctl->hooks;
    int stdin_fileno = STDIN_FILENO;
    const char *arg = "";
    const vshCmdOpt *opt = NULL;
    char **matches = NULL, **iter;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    if (vshCommandOptStringQuiet(ctl, cmd, "string", &arg) <= 0)
        goto cleanup;

    /* This command is flagged VSH_CMD_FLAG_NOCONNECT because we
     * need to prevent auth hooks reading any input. Therefore, we
     * have to close stdin and then connect ourselves. */
    VIR_FORCE_CLOSE(stdin_fileno);

    if (!(hooks && hooks->connHandler && hooks->connHandler(ctl)))
        goto cleanup;

    while ((opt = vshCommandOptArgv(ctl, cmd, opt))) {
        if (virBufferUse(&buf) != 0)
            virBufferAddChar(&buf, ' ');
        virBufferAddStr(&buf, opt->data);
        arg = opt->data;
    }

    if (virBufferCheckError(&buf) < 0)
        goto cleanup;

    vshReadlineInit(ctl);

    if (!(rl_line_buffer = virBufferContentAndReset(&buf)) &&
        VIR_STRDUP(rl_line_buffer, "") < 0)
        goto cleanup;

    /* rl_point is current cursor position in rl_line_buffer.
     * In our case it's at the end of the whole line. */
    rl_point = strlen(rl_line_buffer);

    if (!(matches = vshReadlineCompletion(arg, 0, 0)))
        goto cleanup;

3523 3524 3525
    for (iter = matches; *iter; iter++) {
        if (iter == matches && matches[1])
            continue;
3526
        printf("%s\n", *iter);
3527
    }
3528 3529 3530 3531 3532 3533 3534

    ret = true;
 cleanup:
    virBufferFreeAndReset(&buf);
    virStringListFree(matches);
    return ret;
}
3535 3536 3537 3538 3539 3540


#else /* !WITH_READLINE */


bool
J
Ján Tomko 已提交
3541 3542
cmdComplete(vshControl *ctl G_GNUC_UNUSED,
            const vshCmd *cmd G_GNUC_UNUSED)
3543 3544 3545 3546
{
    return false;
}
#endif /* !WITH_READLINE */