virsh.c 83.4 KB
Newer Older
1
/*
2
 * virsh.c: a shell to exercise the libvirt API
3
 *
4
 * Copyright (C) 2005, 2007-2013 Red Hat, Inc.
5
 *
O
Osier Yang 已提交
6 7 8 9 10 11 12 13 14 15 16
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20
 *
 * Daniel Veillard <veillard@redhat.com>
K
Karel Zak 已提交
21
 * Karel Zak <kzak@redhat.com>
K
Karel Zak 已提交
22
 * Daniel P. Berrange <berrange@redhat.com>
23 24
 */

25
#include <config.h>
E
Eric Blake 已提交
26
#include "virsh.h"
27

28
#include <stdio.h>
K
Karel Zak 已提交
29 30 31
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
32
#include <unistd.h>
33
#include <errno.h>
K
Karel Zak 已提交
34
#include <getopt.h>
K
Karel Zak 已提交
35
#include <sys/time.h>
J
Jim Meyering 已提交
36
#include "c-ctype.h"
37
#include <fcntl.h>
38
#include <locale.h>
39
#include <time.h>
40
#include <limits.h>
41
#include <sys/stat.h>
42
#include <inttypes.h>
E
Eric Blake 已提交
43
#include <strings.h>
K
Karel Zak 已提交
44

45 46 47
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
48
#include <libxml/xmlsave.h>
49

50
#ifdef HAVE_READLINE_READLINE_H
51 52
# include <readline/readline.h>
# include <readline/history.h>
53
#endif
K
Karel Zak 已提交
54

55
#include "internal.h"
56
#include "virerror.h"
57
#include "base64.h"
58
#include "virbuffer.h"
59
#include "console.h"
60
#include "viralloc.h"
61
#include "virxml.h"
62 63
#include <libvirt/libvirt-qemu.h>
#include <libvirt/libvirt-lxc.h>
E
Eric Blake 已提交
64
#include "virfile.h"
65
#include "configmake.h"
66
#include "virthread.h"
67
#include "vircommand.h"
68
#include "virkeycode.h"
69
#include "virnetdevbandwidth.h"
70
#include "virbitmap.h"
H
Hu Tao 已提交
71
#include "conf/domain_conf.h"
72
#include "virtypedparam.h"
73
#include "virstring.h"
K
Karel Zak 已提交
74

E
Eric Blake 已提交
75
#include "virsh-domain.h"
76
#include "virsh-domain-monitor.h"
E
Eric Blake 已提交
77
#include "virsh-host.h"
E
Eric Blake 已提交
78
#include "virsh-interface.h"
E
Eric Blake 已提交
79
#include "virsh-network.h"
E
Eric Blake 已提交
80
#include "virsh-nodedev.h"
E
Eric Blake 已提交
81
#include "virsh-nwfilter.h"
E
Eric Blake 已提交
82
#include "virsh-pool.h"
E
Eric Blake 已提交
83
#include "virsh-secret.h"
E
Eric Blake 已提交
84
#include "virsh-snapshot.h"
E
Eric Blake 已提交
85
#include "virsh-volume.h"
E
Eric Blake 已提交
86

K
Karel Zak 已提交
87 88
static char *progname;

89
static const vshCmdGrp cmdGroups[];
K
Karel Zak 已提交
90

E
Eric Blake 已提交
91 92
/* Bypass header poison */
#undef strdup
93

E
Eric Blake 已提交
94
void *
E
Eric Blake 已提交
95 96
_vshMalloc(vshControl *ctl, size_t size, const char *filename, int line)
{
E
Eric Blake 已提交
97
    char *x;
E
Eric Blake 已提交
98

E
Eric Blake 已提交
99
    if (VIR_ALLOC_N(x, size) == 0)
E
Eric Blake 已提交
100 101 102 103 104 105
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %d bytes"),
             filename, line, (int) size);
    exit(EXIT_FAILURE);
}

E
Eric Blake 已提交
106 107 108
void *
_vshCalloc(vshControl *ctl, size_t nmemb, size_t size, const char *filename,
           int line)
E
Eric Blake 已提交
109
{
E
Eric Blake 已提交
110
    char *x;
E
Eric Blake 已提交
111

E
Eric Blake 已提交
112 113
    if (!xalloc_oversized(nmemb, size) &&
        VIR_ALLOC_N(x, nmemb * size) == 0)
E
Eric Blake 已提交
114 115 116 117 118 119
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %d bytes"),
             filename, line, (int) (size*nmemb));
    exit(EXIT_FAILURE);
}

E
Eric Blake 已提交
120
char *
E
Eric Blake 已提交
121 122 123 124 125
_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line)
{
    char *x;

    if (s == NULL)
126
        return NULL;
E
Eric Blake 已提交
127 128 129 130 131 132 133 134 135
    if ((x = strdup(s)))
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %lu bytes"),
             filename, line, (unsigned long)strlen(s));
    exit(EXIT_FAILURE);
}

/* Poison the raw allocating identifiers in favor of our vsh variants.  */
#define strdup use_vshStrdup_instead_of_strdup
136

137
int
138 139 140 141
vshNameSorter(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;
142

143
    return vshStrcasecmp(*sa, *sb);
144 145
}

E
Eric Blake 已提交
146
double
E
Eric Blake 已提交
147
vshPrettyCapacity(unsigned long long val, const char **unit)
E
Eric Blake 已提交
148
{
149
    if (val < 1024) {
150
        *unit = "B";
151 152
        return (double)val;
    } else if (val < (1024.0l * 1024.0l)) {
153
        *unit = "KiB";
154 155
        return (((double)val / 1024.0l));
    } else if (val < (1024.0l * 1024.0l * 1024.0l)) {
156
        *unit = "MiB";
157
        return (double)val / (1024.0l * 1024.0l);
158
    } else if (val < (1024.0l * 1024.0l * 1024.0l * 1024.0l)) {
159
        *unit = "GiB";
160
        return (double)val / (1024.0l * 1024.0l * 1024.0l);
161
    } else {
162
        *unit = "TiB";
163
        return (double)val / (1024.0l * 1024.0l * 1024.0l * 1024.0l);
164 165 166
    }
}

167 168
/*
 * Convert the strings separated by ',' into array. The caller
E
Eric Blake 已提交
169 170 171
 * must free the first array element and the returned array after
 * use (all other array elements belong to the memory allocated
 * for the first array element).
172 173 174 175 176
 *
 * Returns the length of the filled array on success, or -1
 * on error.
 */
int
177
vshStringToArray(const char *str,
178 179
                 char ***array)
{
180
    char *str_copied = vshStrdup(NULL, str);
181
    char *str_tok = NULL;
E
Eric Blake 已提交
182
    char *tmp;
183 184
    unsigned int nstr_tokens = 0;
    char **arr = NULL;
E
Eric Blake 已提交
185
    size_t len = strlen(str_copied);
186

E
Eric Blake 已提交
187 188
    /* tokenize the string from user and save its parts into an array */
    nstr_tokens = 1;
189

E
Eric Blake 已提交
190 191 192 193 194
    /* 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] == ',')
195
            str_tok++;
E
Eric Blake 已提交
196 197 198 199
        else
            nstr_tokens++;
        str_tok++;
    }
200

E
Eric Blake 已提交
201 202 203 204 205
    if (VIR_ALLOC_N(arr, nstr_tokens) < 0) {
        virReportOOMError();
        VIR_FREE(str_copied);
        return -1;
    }
206

E
Eric Blake 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219
    /* 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++] = str_tok;
        str_tok = tmp;
220
    }
E
Eric Blake 已提交
221
    arr[nstr_tokens++] = str_tok;
222 223 224 225

    *array = arr;
    return nstr_tokens;
}
226

E
Eric Blake 已提交
227
virErrorPtr last_error;
J
John Levon 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240

/*
 * Quieten libvirt until we're done with the command.
 */
static void
virshErrorHandler(void *unused ATTRIBUTE_UNUSED, virErrorPtr error)
{
    virFreeError(last_error);
    last_error = virSaveLastError();
    if (getenv("VIRSH_DEBUG") != NULL)
        virDefaultErrorFunc(error);
}

241 242 243 244 245 246 247 248 249
/* 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();
}

250 251 252
/*
 * Reset libvirt error on graceful fallback paths
 */
E
Eric Blake 已提交
253
void
254 255 256 257 258 259
vshResetLibvirtError(void)
{
    virFreeError(last_error);
    last_error = NULL;
}

J
John Levon 已提交
260 261 262 263 264 265 266 267
/*
 * 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.
 */
E
Eric Blake 已提交
268
void
E
Eric Blake 已提交
269
vshReportError(vshControl *ctl)
J
John Levon 已提交
270
{
271 272 273 274 275 276 277 278
    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)
279
            goto out;
280
    }
J
John Levon 已提交
281 282

    if (last_error->code == VIR_ERR_OK) {
283
        vshError(ctl, "%s", _("unknown error"));
J
John Levon 已提交
284 285 286
        goto out;
    }

287
    vshError(ctl, "%s", last_error->message);
J
John Levon 已提交
288 289

out:
290
    vshResetLibvirtError();
J
John Levon 已提交
291 292
}

293 294 295 296 297 298 299 300
/*
 * Detection of disconnections and automatic reconnection support
 */
static int disconnected = 0; /* we may have been disconnected */

/*
 * vshCatchDisconnect:
 *
301 302
 * We get here when the connection was closed.  We can't do much in the
 * handler, just save the fact it was raised.
303
 */
L
Laine Stump 已提交
304
static void
305 306 307 308 309 310
vshCatchDisconnect(virConnectPtr conn ATTRIBUTE_UNUSED,
                   int reason,
                   void *opaque ATTRIBUTE_UNUSED)
{
    if (reason != VIR_CONNECT_CLOSE_REASON_CLIENT)
        disconnected++;
311 312 313 314 315
}

/*
 * vshReconnect:
 *
L
Laine Stump 已提交
316
 * Reconnect after a disconnect from libvirtd
317 318
 *
 */
L
Laine Stump 已提交
319
static void
320 321 322 323
vshReconnect(vshControl *ctl)
{
    bool connected = false;

324 325 326
    if (ctl->conn) {
        int ret;

327
        connected = true;
328 329 330 331 332 333 334 335

        virConnectUnregisterCloseCallback(ctl->conn, vshCatchDisconnect);
        ret = virConnectClose(ctl->conn);
        if (ret < 0)
            vshError(ctl, "%s", _("Failed to disconnect from the hypervisor"));
        else if (ret > 0)
            vshError(ctl, "%s", _("One or more references were leaked after "
                                  "disconnect from the hypervisor"));
336
    }
337 338 339 340

    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);
341
    if (!ctl->conn) {
342 343 344 345
        if (disconnected)
            vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
        else
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
346 347 348 349 350 351 352
    } else {
        if (virConnectRegisterCloseCallback(ctl->conn, vshCatchDisconnect,
                                            NULL, NULL) < 0)
            vshError(ctl, "%s", _("Unable to register disconnect callback"));
        if (connected)
            vshError(ctl, "%s", _("Reconnected to the hypervisor"));
    }
353
    disconnected = 0;
354
    ctl->useGetInfo = false;
355
    ctl->useSnapshotOld = false;
356
}
357

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

/*
 * "connect" command
 */
static const vshCmdInfo info_connect[] = {
    {.name = "help",
     .data = N_("(re)connect to hypervisor")
    },
    {.name = "desc",
     .data = N_("Connect to local hypervisor. This is built-in "
                "command after shell start up.")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_connect[] = {
    {.name = "name",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_EMPTY_OK,
     .help = N_("hypervisor connection URI")
    },
    {.name = "readonly",
     .type = VSH_OT_BOOL,
     .help = N_("read-only connection")
    },
    {.name = NULL}
};

static bool
cmdConnect(vshControl *ctl, const vshCmd *cmd)
{
    bool ro = vshCommandOptBool(cmd, "readonly");
    const char *name = NULL;

    if (ctl->conn) {
        int ret;
394 395 396 397 398 399 400 401

        virConnectUnregisterCloseCallback(ctl->conn, vshCatchDisconnect);
        ret = virConnectClose(ctl->conn);
        if (ret < 0)
            vshError(ctl, "%s", _("Failed to disconnect from the hypervisor"));
        else if (ret > 0)
            vshError(ctl, "%s", _("One or more references were leaked after "
                                  "disconnect from the hypervisor"));
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
        ctl->conn = NULL;
    }

    VIR_FREE(ctl->name);
    if (vshCommandOptStringReq(ctl, cmd, "name", &name) < 0)
        return false;

    ctl->name = vshStrdup(ctl, name);

    ctl->useGetInfo = false;
    ctl->useSnapshotOld = false;
    ctl->readonly = ro;

    ctl->conn = virConnectOpenAuth(ctl->name, virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);

418
    if (!ctl->conn) {
419
        vshError(ctl, "%s", _("Failed to connect to the hypervisor"));
420 421 422 423 424 425
        return false;
    }

    if (virConnectRegisterCloseCallback(ctl->conn, vshCatchDisconnect,
                                        NULL, NULL) < 0)
        vshError(ctl, "%s", _("Unable to register disconnect callback"));
426

427
    return true;
428 429 430
}


431
#ifndef WIN32
432 433 434 435 436 437 438 439 440 441 442 443 444
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);
}

445 446 447 448 449 450 451 452 453 454 455 456 457
/**
 * vshAskReedit:
 * @msg: Question to ask user
 *
 * Ask user if he wants to return to previously
 * edited file.
 *
 * Returns 'y' if he wants to
 *         'f' if he forcibly wants to
 *         'n' if he doesn't want to
 *         -1  on error
 *          0  otherwise
 */
E
Eric Blake 已提交
458
int
459 460 461 462 463 464 465 466
vshAskReedit(vshControl *ctl, const char *msg)
{
    int c = -1;
    struct termios ttyattr;

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

E
Eric Blake 已提交
467
    vshReportError(ctl);
468 469 470 471 472 473 474 475 476 477 478

    if (vshMakeStdinRaw(&ttyattr, false) < 0)
        return -1;

    while (true) {
        /* TRANSLATORS: For now, we aren't using LC_MESSAGES, and the user
         * choices really are limited to just 'y', 'n', 'f' and '?'  */
        vshPrint(ctl, "\r%s %s", msg, _("Try again? [y,n,f,?]:"));
        c = c_tolower(getchar());

        if (c == '?') {
479 480 481 482 483 484 485
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
486 487 488 489 490 491 492 493 494 495
            continue;
        } else if (c == 'y' || c == 'n' || c == 'f') {
            break;
        }
    }

    tcsetattr(STDIN_FILENO, TCSAFLUSH, &ttyattr);

    vshPrint(ctl, "\r\n");
    return c;
496 497
}
#else /* WIN32 */
498
int
499 500
vshAskReedit(vshControl *ctl, const char *msg ATTRIBUTE_UNUSED)
{
501 502 503 504
    vshDebug(ctl, VSH_ERR_WARNING, "%s", _("This function is not "
                                           "supported on WIN32 platform"));
    return 0;
}
505
#endif /* WIN32 */
506

E
Eric Blake 已提交
507 508
int vshStreamSink(virStreamPtr st ATTRIBUTE_UNUSED,
                  const char *bytes, size_t nbytes, void *opaque)
509 510 511 512 513 514
{
    int *fd = opaque;

    return safewrite(*fd, bytes, nbytes);
}

K
Karel Zak 已提交
515 516 517 518 519 520
/* ---------------
 * Commands
 * ---------------
 */

/*
521
 * "help" command
K
Karel Zak 已提交
522
 */
523
static const vshCmdInfo info_help[] = {
524 525 526 527 528 529 530 531
    {.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}
K
Karel Zak 已提交
532 533
};

534
static const vshCmdOptDef opts_help[] = {
535 536 537 538 539
    {.name = "command",
     .type = VSH_OT_DATA,
     .help = N_("Prints global help, command specific help, or help for a group of related commands")
    },
    {.name = NULL}
K
Karel Zak 已提交
540 541
};

E
Eric Blake 已提交
542
static bool
543
cmdHelp(vshControl *ctl, const vshCmd *cmd)
544
 {
545
    const char *name = NULL;
546

547
    if (vshCommandOptString(cmd, "command", &name) <= 0) {
548
        const vshCmdGrp *grp;
549
        const vshCmdDef *def;
550

551 552 553 554 555 556
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

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

557 558 559
            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
560 561
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
562
            }
563 564 565 566

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
567
        return true;
568
    }
569

E
Eric Blake 已提交
570
    if (vshCmddefSearch(name)) {
571
        return vshCmddefHelp(ctl, name);
E
Eric Blake 已提交
572
    } else if (vshCmdGrpSearch(name)) {
573 574 575
        return vshCmdGrpHelp(ctl, name);
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
E
Eric Blake 已提交
576
        return false;
K
Karel Zak 已提交
577 578 579
    }
}

580 581 582 583 584 585 586 587 588 589 590
/* Tree listing helpers.  */

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

597
    if (virBufferError(indent))
598 599
        goto cleanup;

600 601 602 603 604 605 606 607 608 609
    /* 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;
610 611
    }

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

616 617 618
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
619

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

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

631 632 633 634 635
        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
636
    }
637 638
    if (virBufferTrim(indent, "  ", -1) < 0)
        goto cleanup;
639

640 641 642 643
    /* 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));
644

645 646 647 648
    if (!root) {
        if (virBufferTrim(indent, NULL, 2) < 0)
            goto cleanup;
    }
649
    ret = 0;
650 651 652 653
cleanup:
    return ret;
}

E
Eric Blake 已提交
654
int
655 656
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
657
{
658 659
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;
660

661 662 663 664 665
    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
666
    return ret;
667
}
668

669
/* Common code for the edit / net-edit / pool-edit functions which follow. */
E
Eric Blake 已提交
670
char *
E
Eric Blake 已提交
671
vshEditWriteToTempFile(vshControl *ctl, const char *doc)
672 673 674 675
{
    char *ret;
    const char *tmpdir;
    int fd;
676
    char ebuf[1024];
677

678
    tmpdir = getenv("TMPDIR");
679
    if (!tmpdir) tmpdir = "/tmp";
680 681 682 683
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
684
    fd = mkostemps(ret, 4, O_CLOEXEC);
685
    if (fd == -1) {
686
        vshError(ctl, _("mkostemps: failed to create temporary file: %s"),
687
                 virStrerror(errno, ebuf, sizeof(ebuf)));
688
        VIR_FREE(ret);
689 690 691
        return NULL;
    }

692
    if (safewrite(fd, doc, strlen(doc)) == -1) {
693
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
694
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
S
Stefan Berger 已提交
695
        VIR_FORCE_CLOSE(fd);
696
        unlink(ret);
697
        VIR_FREE(ret);
698 699
        return NULL;
    }
S
Stefan Berger 已提交
700
    if (VIR_CLOSE(fd) < 0) {
701
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
702
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
703
        unlink(ret);
704
        VIR_FREE(ret);
705 706 707 708 709 710 711 712 713 714 715
        return NULL;
    }

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

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

E
Eric Blake 已提交
716
int
E
Eric Blake 已提交
717
vshEditFile(vshControl *ctl, const char *filename)
718 719
{
    const char *editor;
E
Eric Blake 已提交
720 721 722 723
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;
724

725
    editor = getenv("VISUAL");
E
Eric Blake 已提交
726
    if (!editor)
727
        editor = getenv("EDITOR");
E
Eric Blake 已提交
728 729
    if (!editor)
        editor = "vi"; /* could be cruel & default to ed(1) here */
730

731 732 733 734 735
    /* 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
E
Eric Blake 已提交
736 737
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
738
     */
739 740
    if (strspn(editor, ACCEPTED_CHARS) != strlen(editor)) {
        if (strspn(filename, ACCEPTED_CHARS) != strlen(filename)) {
E
Eric Blake 已提交
741 742 743 744 745 746 747 748 749 750
            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);
751 752
    }

E
Eric Blake 已提交
753 754 755 756 757
    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
E
Eric Blake 已提交
758
        vshReportError(ctl);
E
Eric Blake 已提交
759
        goto cleanup;
760
    }
E
Eric Blake 已提交
761
    ret = 0;
762

E
Eric Blake 已提交
763 764 765
cleanup:
    virCommandFree(cmd);
    return ret;
766 767
}

E
Eric Blake 已提交
768
char *
E
Eric Blake 已提交
769
vshEditReadBackFile(vshControl *ctl, const char *filename)
770 771
{
    char *ret;
772
    char ebuf[1024];
773

E
Eric Blake 已提交
774
    if (virFileReadAll(filename, VSH_MAX_XML_FILE, &ret) == -1) {
775
        vshError(ctl,
776
                 _("%s: failed to read temporary file: %s"),
777
                 filename, virStrerror(errno, ebuf, sizeof(ebuf)));
778 779 780 781 782
        return NULL;
    }
    return ret;
}

783

P
Paolo Bonzini 已提交
784 785 786 787
/*
 * "cd" command
 */
static const vshCmdInfo info_cd[] = {
788 789 790 791 792 793 794
    {.name = "help",
     .data = N_("change the current directory")
    },
    {.name = "desc",
     .data = N_("Change the current directory.")
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
795 796 797
};

static const vshCmdOptDef opts_cd[] = {
798 799 800 801 802
    {.name = "dir",
     .type = VSH_OT_DATA,
     .help = N_("directory to switch to (default: home or else root)")
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
803 804
};

E
Eric Blake 已提交
805
static bool
806
cmdCd(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
807
{
808
    const char *dir = NULL;
809
    char *dir_malloced = NULL;
E
Eric Blake 已提交
810
    bool ret = true;
811
    char ebuf[1024];
P
Paolo Bonzini 已提交
812 813

    if (!ctl->imode) {
814
        vshError(ctl, "%s", _("cd: command valid only in interactive mode"));
E
Eric Blake 已提交
815
        return false;
P
Paolo Bonzini 已提交
816 817
    }

818
    if (vshCommandOptString(cmd, "dir", &dir) <= 0) {
819
        dir = dir_malloced = virGetUserDirectory();
P
Paolo Bonzini 已提交
820 821 822 823
    }
    if (!dir)
        dir = "/";

P
Phil Petty 已提交
824
    if (chdir(dir) == -1) {
825 826
        vshError(ctl, _("cd: %s: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)), dir);
E
Eric Blake 已提交
827
        ret = false;
P
Paolo Bonzini 已提交
828 829
    }

830
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
831
    return ret;
P
Paolo Bonzini 已提交
832 833 834 835 836 837
}

/*
 * "pwd" command
 */
static const vshCmdInfo info_pwd[] = {
838 839 840 841 842 843 844
    {.name = "help",
     .data = N_("print the current directory")
    },
    {.name = "desc",
     .data = N_("Print the current directory.")
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
845 846
};

E
Eric Blake 已提交
847
static bool
P
Paolo Bonzini 已提交
848 849 850
cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cwd;
851
    bool ret = true;
852
    char ebuf[1024];
P
Paolo Bonzini 已提交
853

854 855
    cwd = getcwd(NULL, 0);
    if (!cwd) {
856
        vshError(ctl, _("pwd: cannot get current directory: %s"),
857
                 virStrerror(errno, ebuf, sizeof(ebuf)));
858 859
        ret = false;
    } else {
860
        vshPrint(ctl, _("%s\n"), cwd);
861 862
        VIR_FREE(cwd);
    }
P
Paolo Bonzini 已提交
863

864
    return ret;
P
Paolo Bonzini 已提交
865 866
}

E
Eric Blake 已提交
867 868 869 870
/*
 * "echo" command
 */
static const vshCmdInfo info_echo[] = {
871 872 873 874 875 876 877
    {.name = "help",
     .data = N_("echo arguments")
    },
    {.name = "desc",
     .data = N_("Echo back arguments, possibly with quoting.")
    },
    {.name = NULL}
E
Eric Blake 已提交
878 879 880
};

static const vshCmdOptDef opts_echo[] = {
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
    {.name = "shell",
     .type = VSH_OT_BOOL,
     .help = N_("escape for shell use")
    },
    {.name = "xml",
     .type = VSH_OT_BOOL,
     .help = N_("escape for XML use")
    },
    {.name = "str",
     .type = VSH_OT_ALIAS,
     .help = "string"
    },
    {.name = "string",
     .type = VSH_OT_ARGV,
     .help = N_("arguments to echo")
    },
    {.name = NULL}
E
Eric Blake 已提交
898 899 900 901 902
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
E
Eric Blake 已提交
903
static bool
904
cmdEcho(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
905 906 907 908
{
    bool shell = false;
    bool xml = false;
    int count = 0;
909
    const vshCmdOpt *opt = NULL;
E
Eric Blake 已提交
910 911 912 913 914 915 916 917
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    if (vshCommandOptBool(cmd, "shell"))
        shell = true;
    if (vshCommandOptBool(cmd, "xml"))
        xml = true;

918
    while ((opt = vshCommandOptArgv(cmd, opt))) {
919 920
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
921

922
        arg = opt->data;
923

E
Eric Blake 已提交
924 925
        if (count)
            virBufferAddChar(&buf, ' ');
926

E
Eric Blake 已提交
927
        if (xml) {
928 929 930 931
            virBufferEscapeString(&xmlbuf, "%s", arg);
            if (virBufferError(&buf)) {
                vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
                return false;
E
Eric Blake 已提交
932
            }
933 934 935
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
E
Eric Blake 已提交
936
        }
937 938 939 940 941

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
E
Eric Blake 已提交
942
        count++;
943
        VIR_FREE(str);
E
Eric Blake 已提交
944 945 946 947
    }

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
948
        return false;
E
Eric Blake 已提交
949 950 951 952 953
    }
    arg = virBufferContentAndReset(&buf);
    if (arg)
        vshPrint(ctl, "%s", arg);
    VIR_FREE(arg);
E
Eric Blake 已提交
954
    return true;
E
Eric Blake 已提交
955 956
}

K
Karel Zak 已提交
957 958 959
/*
 * "quit" command
 */
960
static const vshCmdInfo info_quit[] = {
961 962 963 964 965 966 967
    {.name = "help",
     .data = N_("quit this interactive terminal")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
K
Karel Zak 已提交
968 969
};

E
Eric Blake 已提交
970
static bool
971
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
972
{
E
Eric Blake 已提交
973 974
    ctl->imode = false;
    return true;
K
Karel Zak 已提交
975 976
}

977 978 979 980
/* ---------------
 * Utils for work with command definition
 * ---------------
 */
E
Eric Blake 已提交
981
const char *
982 983 984
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
{
    const vshCmdInfo *info;
985

986 987 988 989 990 991
    for (info = cmd->info; info && info->name; info++) {
        if (STREQ(info->name, name))
            return info->data;
    }
    return NULL;
}
992

993 994 995 996 997 998 999
/* Validate that the options associated with cmd can be parsed.  */
static int
vshCmddefOptParse(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                  uint32_t *opts_required)
{
    int i;
    bool optional = false;
1000

1001 1002
    *opts_need_arg = 0;
    *opts_required = 0;
1003

1004 1005
    if (!cmd->opts)
        return 0;
1006

1007 1008
    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
1009 1010 1011 1012

        if (i > 31)
            return -1; /* too many options */
        if (opt->type == VSH_OT_BOOL) {
E
Eric Blake 已提交
1013
            if (opt->flags & VSH_OFLAG_REQ)
1014 1015 1016
                return -1; /* bool options can't be mandatory */
            continue;
        }
E
Eric Blake 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
        if (opt->type == VSH_OT_ALIAS) {
            int j;
            if (opt->flags || !opt->help)
                return -1; /* alias options are tracked by the original name */
            for (j = i + 1; cmd->opts[j].name; j++) {
                if (STREQ(opt->help, cmd->opts[j].name))
                    break;
            }
            if (!cmd->opts[j].name)
                return -1; /* alias option must map to a later option name */
            continue;
        }
E
Eric Blake 已提交
1029 1030
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
L
Lai Jiangshan 已提交
1031 1032 1033 1034
                *opts_required |= 1 << i;
            continue;
        }

1035
        *opts_need_arg |= 1 << i;
E
Eric Blake 已提交
1036
        if (opt->flags & VSH_OFLAG_REQ) {
1037 1038 1039 1040 1041 1042
            if (optional)
                return -1; /* mandatory options must be listed first */
            *opts_required |= 1 << i;
        } else {
            optional = true;
        }
1043 1044 1045

        if (opt->type == VSH_OT_ARGV && cmd->opts[i + 1].name)
            return -1; /* argv option must be listed last */
1046 1047 1048 1049
    }
    return 0;
}

1050 1051 1052 1053 1054
static vshCmdOptDef helpopt = {
    .name = "help",
    .type = VSH_OT_BOOL,
    .help = N_("print help for this function")
};
1055
static const vshCmdOptDef *
1056
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
1057
                   uint32_t *opts_seen, int *opt_index)
1058
{
1059 1060
    int i;

1061 1062 1063 1064
    if (STREQ(name, helpopt.name)) {
        return &helpopt;
    }

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

1068
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
1069 1070 1071 1072
            if (opt->type == VSH_OT_ALIAS) {
                name = opt->help;
                continue;
            }
1073
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
1074 1075 1076
                vshError(ctl, _("option --%s already seen"), name);
                return NULL;
            }
1077 1078
            *opts_seen |= 1 << i;
            *opt_index = i;
K
Karel Zak 已提交
1079
            return opt;
1080 1081 1082
        }
    }

1083 1084 1085 1086
    if (STRNEQ(cmd->name, "help")) {
        vshError(ctl, _("command '%s' doesn't support option --%s"),
                 cmd->name, name);
    }
K
Karel Zak 已提交
1087 1088 1089
    return NULL;
}

1090
static const vshCmdOptDef *
1091 1092
vshCmddefGetData(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                 uint32_t *opts_seen)
1093
{
1094
    int i;
1095
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
1096

1097 1098 1099 1100
    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
E
Eric Blake 已提交
1101
    i = ffs(*opts_need_arg) - 1;
1102
    opt = &cmd->opts[i];
1103
    if (opt->type != VSH_OT_ARGV)
1104
        *opts_need_arg &= ~(1 << i);
1105
    *opts_seen |= 1 << i;
1106
    return opt;
K
Karel Zak 已提交
1107 1108
}

1109 1110 1111
/*
 * Checks for required options
 */
1112
static int
1113 1114
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint32_t opts_required,
                    uint32_t opts_seen)
1115
{
1116
    const vshCmdDef *def = cmd->def;
1117 1118 1119 1120 1121 1122 1123 1124 1125
    int i;

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

    for (i = 0; def->opts[i].name; i++) {
        if (opts_required & (1 << i)) {
            const vshCmdOptDef *opt = &def->opts[i];
1126

1127
            vshError(ctl,
1128
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
1129 1130 1131
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
1132 1133
        }
    }
1134
    return -1;
1135 1136
}

E
Eric Blake 已提交
1137
const vshCmdDef *
1138 1139
vshCmddefSearch(const char *cmdname)
{
1140
    const vshCmdGrp *g;
1141
    const vshCmdDef *c;
1142

1143 1144
    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
1145
            if (STREQ(c->name, cmdname))
1146 1147 1148 1149
                return c;
        }
    }

K
Karel Zak 已提交
1150 1151 1152
    return NULL;
}

E
Eric Blake 已提交
1153
const vshCmdGrp *
1154 1155 1156 1157 1158
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
1159
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
1160 1161 1162 1163 1164 1165
            return g;
    }

    return NULL;
}

E
Eric Blake 已提交
1166
bool
1167 1168 1169 1170 1171 1172 1173
vshCmdGrpHelp(vshControl *ctl, const char *grpname)
{
    const vshCmdGrp *grp = vshCmdGrpSearch(grpname);
    const vshCmdDef *cmd = NULL;

    if (!grp) {
        vshError(ctl, _("command group '%s' doesn't exist"), grpname);
E
Eric Blake 已提交
1174
        return false;
1175 1176 1177 1178 1179
    } else {
        vshPrint(ctl, _(" %s (help keyword '%s'):\n"), grp->name,
                 grp->keyword);

        for (cmd = grp->commands; cmd->name; cmd++) {
1180 1181
            if (cmd->flags & VSH_CMD_FLAG_ALIAS)
                continue;
1182 1183 1184 1185 1186
            vshPrint(ctl, "    %-30s %s\n", cmd->name,
                     _(vshCmddefGetInfo(cmd, "help")));
        }
    }

E
Eric Blake 已提交
1187
    return true;
1188 1189
}

E
Eric Blake 已提交
1190
bool
1191
vshCmddefHelp(vshControl *ctl, const char *cmdname)
1192
{
1193
    const vshCmdDef *def = vshCmddefSearch(cmdname);
1194

K
Karel Zak 已提交
1195
    if (!def) {
1196
        vshError(ctl, _("command '%s' doesn't exist"), cmdname);
E
Eric Blake 已提交
1197
        return false;
1198
    } else {
E
Eric Blake 已提交
1199 1200
        /* Don't translate desc if it is "".  */
        const char *desc = vshCmddefGetInfo(def, "desc");
E
Eric Blake 已提交
1201
        const char *help = _(vshCmddefGetInfo(def, "help"));
1202
        char buf[256];
1203 1204
        uint32_t opts_need_arg;
        uint32_t opts_required;
1205
        bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
1206 1207 1208 1209

        if (vshCmddefOptParse(def, &opts_need_arg, &opts_required)) {
            vshError(ctl, _("internal error: bad options in command: '%s'"),
                     def->name);
E
Eric Blake 已提交
1210
            return false;
1211
        }
K
Karel Zak 已提交
1212

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

1216 1217 1218 1219 1220
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
1221
                const char *fmt = "%s";
1222 1223
                switch (opt->type) {
                case VSH_OT_BOOL:
1224
                    fmt = "[--%s]";
1225 1226
                    break;
                case VSH_OT_INT:
E
Eric Blake 已提交
1227
                    /* xgettext:c-format */
E
Eric Blake 已提交
1228
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
1229
                           : _("[--%s <number>]"));
1230 1231
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1232 1233
                    break;
                case VSH_OT_STRING:
E
Eric Blake 已提交
1234 1235
                    /* xgettext:c-format */
                    fmt = _("[--%s <string>]");
1236 1237
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1238 1239
                    break;
                case VSH_OT_DATA:
E
Eric Blake 已提交
1240
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
1241 1242
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1243 1244 1245
                    break;
                case VSH_OT_ARGV:
                    /* xgettext:c-format */
1246 1247 1248 1249 1250 1251 1252 1253
                    if (shortopt) {
                        fmt = (opt->flags & VSH_OFLAG_REQ)
                            ? _("{[--%s] <string>}...")
                            : _("[[--%s] <string>]...");
                    } else {
                        fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                            : _("[<%s>]...");
                    }
1254
                    break;
E
Eric Blake 已提交
1255 1256 1257
                case VSH_OT_ALIAS:
                    /* aliases are intentionally undocumented */
                    continue;
1258
                }
1259
                fputc(' ', stdout);
E
Eric Blake 已提交
1260
                fprintf(stdout, fmt, opt->name);
1261
            }
K
Karel Zak 已提交
1262
        }
1263 1264 1265
        fputc('\n', stdout);

        if (desc[0]) {
1266
            /* Print the description only if it's not empty.  */
1267
            fputs(_("\n  DESCRIPTION\n"), stdout);
E
Eric Blake 已提交
1268
            fprintf(stdout, "    %s\n", _(desc));
K
Karel Zak 已提交
1269
        }
1270

1271
        if (def->opts && def->opts->name) {
1272
            const vshCmdOptDef *opt;
1273
            fputs(_("\n  OPTIONS\n"), stdout);
1274
            for (opt = def->opts; opt->name; opt++) {
1275 1276
                switch (opt->type) {
                case VSH_OT_BOOL:
K
Karel Zak 已提交
1277
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1278 1279
                    break;
                case VSH_OT_INT:
1280
                    snprintf(buf, sizeof(buf),
E
Eric Blake 已提交
1281
                             (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
1282
                             : _("--%s <number>"), opt->name);
1283 1284
                    break;
                case VSH_OT_STRING:
1285
                    /* OT_STRING should never be VSH_OFLAG_REQ */
1286
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
1287 1288
                    break;
                case VSH_OT_DATA:
1289 1290
                    snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                             opt->name);
1291 1292
                    break;
                case VSH_OT_ARGV:
1293 1294 1295
                    snprintf(buf, sizeof(buf),
                             shortopt ? _("[--%s] <string>") : _("<%s>"),
                             opt->name);
1296
                    break;
E
Eric Blake 已提交
1297 1298
                case VSH_OT_ALIAS:
                    continue;
1299
                }
1300

E
Eric Blake 已提交
1301
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
1302
            }
K
Karel Zak 已提交
1303 1304 1305
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
1306
    return true;
K
Karel Zak 已提交
1307 1308 1309 1310 1311 1312
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1313 1314 1315
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1316 1317
    vshCmdOpt *a = arg;

1318
    while (a) {
K
Karel Zak 已提交
1319
        vshCmdOpt *tmp = a;
1320

K
Karel Zak 已提交
1321 1322
        a = a->next;

1323 1324
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
1325 1326 1327 1328
    }
}

static void
1329
vshCommandFree(vshCmd *cmd)
1330
{
K
Karel Zak 已提交
1331 1332
    vshCmd *c = cmd;

1333
    while (c) {
K
Karel Zak 已提交
1334
        vshCmd *tmp = c;
1335

K
Karel Zak 已提交
1336 1337 1338 1339
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
1340
        VIR_FREE(tmp);
K
Karel Zak 已提交
1341 1342 1343
    }
}

E
Eric Blake 已提交
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
/**
 * vshCommandOpt:
 * @cmd: parsed command line to search
 * @name: option name to search for
 * @opt: result of the search
 *
 * 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 -2 if NAME is not valid
 * (-2 indicates a programming error).  No error messages are issued.
K
Karel Zak 已提交
1355
 */
E
Eric Blake 已提交
1356
int
E
Eric Blake 已提交
1357
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
1358
{
E
Eric Blake 已提交
1359 1360
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
1361

E
Eric Blake 已提交
1362 1363 1364 1365 1366 1367 1368
    /* See if option is present on command line.  */
    while (candidate) {
        if (STREQ(candidate->def->name, name)) {
            *opt = candidate;
            return 1;
        }
        candidate = candidate->next;
K
Karel Zak 已提交
1369
    }
E
Eric Blake 已提交
1370 1371 1372 1373 1374 1375 1376

    /* Option not present, see if command requires it.  */
    *opt = NULL;
    while (valid) {
        if (!valid->name)
            break;
        if (STREQ(name, valid->name))
E
Eric Blake 已提交
1377
            return (valid->flags & VSH_OFLAG_REQ) == 0 ? 0 : -1;
E
Eric Blake 已提交
1378 1379 1380 1381
        valid++;
    }
    /* If we got here, the name is unknown.  */
    return -2;
K
Karel Zak 已提交
1382 1383
}

E
Eric Blake 已提交
1384 1385
/**
 * vshCommandOptInt:
1386 1387 1388 1389 1390 1391 1392
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to int
 * Return value:
 * >0 if option found and valid (@value updated)
E
Eric Blake 已提交
1393
 * 0 if option not found and not required (@value untouched)
1394
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
1395
 */
E
Eric Blake 已提交
1396
int
1397
vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
1398
{
E
Eric Blake 已提交
1399 1400
    vshCmdOpt *arg;
    int ret;
1401

E
Eric Blake 已提交
1402 1403 1404 1405 1406 1407 1408
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1409
    }
E
Eric Blake 已提交
1410

E
Eric Blake 已提交
1411 1412 1413
    if (virStrToLong_i(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
K
Karel Zak 已提交
1414 1415
}

1416

E
Eric Blake 已提交
1417 1418 1419 1420 1421 1422
/**
 * vshCommandOptUInt:
 * @cmd command reference
 * @name option name
 * @value result
 *
1423 1424 1425
 * Convert option to unsigned int
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1426
int
1427 1428
vshCommandOptUInt(const vshCmd *cmd, const char *name, unsigned int *value)
{
E
Eric Blake 已提交
1429 1430
    vshCmdOpt *arg;
    int ret;
1431

E
Eric Blake 已提交
1432 1433 1434 1435 1436 1437 1438
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1439
    }
E
Eric Blake 已提交
1440

E
Eric Blake 已提交
1441 1442 1443
    if (virStrToLong_ui(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1444 1445 1446
}


1447
/*
E
Eric Blake 已提交
1448 1449 1450 1451 1452
 * vshCommandOptUL:
 * @cmd command reference
 * @name option name
 * @value result
 *
1453 1454 1455
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1456
int
1457
vshCommandOptUL(const vshCmd *cmd, const char *name, unsigned long *value)
1458
{
E
Eric Blake 已提交
1459 1460
    vshCmdOpt *arg;
    int ret;
1461

E
Eric Blake 已提交
1462 1463 1464 1465 1466 1467 1468
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1469
    }
E
Eric Blake 已提交
1470

E
Eric Blake 已提交
1471 1472 1473
    if (virStrToLong_ul(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1474 1475
}

E
Eric Blake 已提交
1476 1477 1478 1479 1480 1481
/**
 * vshCommandOptString:
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
1482
 * Returns option as STRING
E
Eric Blake 已提交
1483 1484 1485 1486
 * 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)
K
Karel Zak 已提交
1487
 */
E
Eric Blake 已提交
1488
int
1489
vshCommandOptString(const vshCmd *cmd, const char *name, const char **value)
1490
{
E
Eric Blake 已提交
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
    vshCmdOpt *arg;
    int ret;

    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1501
    }
1502

E
Eric Blake 已提交
1503
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK)) {
E
Eric Blake 已提交
1504 1505 1506 1507
        return -1;
    }
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
1508 1509
}

1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
/**
 * vshCommandOptStringReq:
 * @ctl virsh 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);
    /* 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");

    if (ret == -2)
        error = N_("Programming error: Invalid option name");

    if (!arg->data)
        error = N_("Programming error: Requested option is a boolean");

1550
    if (arg->data && !*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK))
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
        error = N_("Option argument is empty");

    if (error) {
        vshError(ctl, _("Failed to get option '%s': %s"), name, _(error));
        return -1;
    }

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

E
Eric Blake 已提交
1562 1563 1564 1565 1566 1567
/**
 * vshCommandOptLongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
1568
 * Returns option as long long
1569
 * See vshCommandOptInt()
1570
 */
E
Eric Blake 已提交
1571
int
1572 1573
vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                      long long *value)
1574
{
E
Eric Blake 已提交
1575 1576
    vshCmdOpt *arg;
    int ret;
1577

E
Eric Blake 已提交
1578 1579 1580 1581 1582 1583 1584
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1585
    }
E
Eric Blake 已提交
1586

E
Eric Blake 已提交
1587 1588 1589
    if (virStrToLong_ll(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1590 1591
}

E
Eric Blake 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600
/**
 * vshCommandOptULongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1601
int
1602 1603 1604
vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                       unsigned long long *value)
{
E
Eric Blake 已提交
1605 1606
    vshCmdOpt *arg;
    int ret;
1607

E
Eric Blake 已提交
1608 1609 1610 1611 1612 1613 1614
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1615
    }
E
Eric Blake 已提交
1616

E
Eric Blake 已提交
1617 1618 1619
    if (virStrToLong_ull(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1620 1621 1622
}


E
Eric Blake 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
/**
 * vshCommandOptScaledInt:
 * @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()
 */
E
Eric Blake 已提交
1634
int
E
Eric Blake 已提交
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
vshCommandOptScaledInt(const vshCmd *cmd, const char *name,
                       unsigned long long *value, int scale,
                       unsigned long long max)
{
    const char *str;
    int ret;
    char *end;

    ret = vshCommandOptString(cmd, name, &str);
    if (ret <= 0)
        return ret;
    if (virStrToLong_ull(str, &end, 10, value) < 0 ||
        virScaleInteger(value, end, scale, max) < 0)
        return -1;
    return 1;
}


E
Eric Blake 已提交
1653 1654 1655 1656 1657 1658 1659 1660 1661
/**
 * 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.
K
Karel Zak 已提交
1662
 */
E
Eric Blake 已提交
1663
bool
1664
vshCommandOptBool(const vshCmd *cmd, const char *name)
1665
{
E
Eric Blake 已提交
1666 1667 1668
    vshCmdOpt *dummy;

    return vshCommandOpt(cmd, name, &dummy) == 1;
K
Karel Zak 已提交
1669 1670
}

E
Eric Blake 已提交
1671 1672 1673 1674 1675
/**
 * vshCommandOptArgv:
 * @cmd command reference
 * @opt starting point for the search
 *
1676 1677
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
1678
 *
1679
 * Requires that a VSH_OT_ARGV option be last in the
1680 1681
 * list of supported options in CMD->def->opts.
 */
E
Eric Blake 已提交
1682
const vshCmdOpt *
1683
vshCommandOptArgv(const vshCmd *cmd, const vshCmdOpt *opt)
1684
{
1685
    opt = opt ? opt->next : cmd->opts;
1686 1687

    while (opt) {
E
Eric Blake 已提交
1688
        if (opt->def->type == VSH_OT_ARGV) {
1689
            return opt;
1690 1691 1692 1693 1694 1695
        }
        opt = opt->next;
    }
    return NULL;
}

J
Jim Meyering 已提交
1696 1697 1698
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
1699 1700
bool
vshCmdHasOption(vshControl *ctl, const vshCmd *cmd, const char *optname)
J
Jim Meyering 已提交
1701 1702 1703 1704 1705 1706
{
    /* Iterate through cmd->opts, to ensure that there is an entry
       with name OPTNAME and type VSH_OT_DATA. */
    bool found = false;
    const vshCmdOpt *opt;
    for (opt = cmd->opts; opt; opt = opt->next) {
1707
        if (STREQ(opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
J
Jim Meyering 已提交
1708 1709 1710 1711 1712 1713
            found = true;
            break;
        }
    }

    if (!found)
1714
        vshError(ctl, _("internal error: virsh %s: no %s VSH_OT_DATA option"),
J
Jim Meyering 已提交
1715 1716 1717
                 cmd->def->name, optname);
    return found;
}
1718

1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
static bool
vshConnectionUsability(vshControl *ctl, virConnectPtr conn)
{
    if (!conn ||
        virConnectIsAlive(conn) == 0) {
        vshError(ctl, "%s", _("no valid connection"));
        return false;
    }

    /* The connection is considered dead only if
     * virConnectIsAlive() successfuly says so.
     */
    vshResetLibvirtError();

    return true;
}

K
Karel Zak 已提交
1736 1737 1738
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
1739
static bool
1740
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
1741
{
E
Eric Blake 已提交
1742
    bool ret = true;
1743 1744

    while (cmd) {
K
Karel Zak 已提交
1745
        struct timeval before, after;
1746
        bool enable_timing = ctl->timing;
1747

1748 1749
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
1750 1751
            vshReconnect(ctl);

1752 1753 1754
        if (enable_timing)
            GETTIMEOFDAY(&before);

1755 1756 1757 1758 1759 1760 1761
        if ((cmd->def->flags & VSH_CMD_FLAG_NOCONNECT) ||
            vshConnectionUsability(ctl, ctl->conn)) {
            ret = cmd->def->handler(ctl, cmd);
        } else {
            /* connection is not usable, return error */
            ret = false;
        }
1762

1763 1764 1765
        if (enable_timing)
            GETTIMEOFDAY(&after);

1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
        /* 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++;

1776
        if (!ret)
E
Eric Blake 已提交
1777
            vshReportError(ctl);
J
John Levon 已提交
1778

1779
        if (!ret && disconnected != 0)
1780 1781
            vshReconnect(ctl);

1782
        if (STREQ(cmd->def->name, "quit"))        /* hack ... */
K
Karel Zak 已提交
1783 1784
            return ret;

E
Eric Blake 已提交
1785
        if (enable_timing) {
1786
            double diff_ms = (((after.tv_sec - before.tv_sec) * 1000.0) +
E
Eric Blake 已提交
1787 1788 1789 1790
                              ((after.tv_usec - before.tv_usec) / 1000.0));

            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"), diff_ms);
        } else {
K
Karel Zak 已提交
1791
            vshPrintExtra(ctl, "\n");
E
Eric Blake 已提交
1792
        }
K
Karel Zak 已提交
1793 1794 1795 1796 1797 1798
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
1799
 * Command parsing
K
Karel Zak 已提交
1800 1801 1802
 * ---------------
 */

1803 1804 1805 1806 1807 1808 1809
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;

E
Eric Blake 已提交
1810 1811 1812 1813
typedef struct _vshCommandParser vshCommandParser;
struct _vshCommandParser {
    vshCommandToken(*getNextArg)(vshControl *, vshCommandParser *,
                                 char **);
L
Lai Jiangshan 已提交
1814
    /* vshCommandStringGetArg() */
1815
    char *pos;
L
Lai Jiangshan 已提交
1816 1817 1818
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
E
Eric Blake 已提交
1819
};
1820

E
Eric Blake 已提交
1821
static bool
1822
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
1823
{
K
Karel Zak 已提交
1824 1825 1826
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
1827

K
Karel Zak 已提交
1828 1829 1830 1831
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
1832

1833
    while (1) {
K
Karel Zak 已提交
1834
        vshCmdOpt *last = NULL;
1835
        const vshCmdDef *cmd = NULL;
1836
        vshCommandToken tk;
L
Lai Jiangshan 已提交
1837
        bool data_only = false;
1838 1839 1840
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
1841

K
Karel Zak 已提交
1842
        first = NULL;
1843

1844
        while (1) {
1845
            const vshCmdOptDef *opt = NULL;
1846

K
Karel Zak 已提交
1847
            tkdata = NULL;
1848
            tk = parser->getNextArg(ctl, parser, &tkdata);
1849 1850

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1851
                goto syntaxError;
H
Hu Tao 已提交
1852 1853
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
1854
                break;
H
Hu Tao 已提交
1855
            }
1856 1857

            if (cmd == NULL) {
K
Karel Zak 已提交
1858 1859
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
1860
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
1861
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
1862
                }
1863 1864 1865 1866 1867 1868 1869
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
1870
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
1871 1872 1873 1874
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
1875
                char *optstr = strchr(tkdata + 2, '=');
C
Cole Robinson 已提交
1876
                int opt_index = 0;
1877

1878 1879 1880 1881
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
1882
                /* Special case 'help' to ignore all spurious options */
1883
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
1884
                                               &opts_seen, &opt_index))) {
1885
                    VIR_FREE(optstr);
1886 1887
                    if (STREQ(cmd->name, "help"))
                        continue;
K
Karel Zak 已提交
1888 1889
                    goto syntaxError;
                }
1890
                VIR_FREE(tkdata);
K
Karel Zak 已提交
1891 1892 1893

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
1894 1895 1896
                    if (optstr)
                        tkdata = optstr;
                    else
1897
                        tk = parser->getNextArg(ctl, parser, &tkdata);
1898
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1899
                        goto syntaxError;
1900
                    if (tk != VSH_TK_ARG) {
1901
                        vshError(ctl,
1902
                                 _("expected syntax: --%s <%s>"),
1903 1904
                                 opt->name,
                                 opt->type ==
1905
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
1906 1907
                        goto syntaxError;
                    }
1908 1909
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
1910 1911 1912 1913 1914 1915 1916 1917
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                opt->name);
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
1918
                }
L
Lai Jiangshan 已提交
1919 1920 1921 1922
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
1923
            } else {
L
Lai Jiangshan 已提交
1924
get_data:
1925
                /* Special case 'help' to ignore spurious data */
1926
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
1927 1928
                                             &opts_seen)) &&
                     STRNEQ(cmd->name, "help")) {
1929
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
1930 1931 1932 1933 1934
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
1935
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
1936

K
Karel Zak 已提交
1937 1938 1939 1940
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
1941

K
Karel Zak 已提交
1942 1943 1944 1945 1946
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
1947

1948
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
1949 1950
                         cmd->name,
                         opt->name,
1951 1952
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
1953 1954
            }
        }
1955

D
Daniel Veillard 已提交
1956
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
1957
        if (cmd) {
1958
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
            vshCmdOpt *tmpopt = first;

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

                vshCommandOptFree(first);
                first = vshMalloc(ctl, sizeof(vshCmdOpt));
                first->def = &(opts_help[0]);
                first->data = vshStrdup(ctl, cmd->name);
                first->next = NULL;

                cmd = vshCmddefSearch("help");
                opts_required = 0;
                opts_seen = 0;
                break;
            }
1978

K
Karel Zak 已提交
1979 1980 1981 1982
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

1983
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
1984
                VIR_FREE(c);
1985
                goto syntaxError;
1986
            }
1987

K
Karel Zak 已提交
1988 1989 1990 1991 1992 1993
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
1994 1995 1996

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
1997
    }
1998

E
Eric Blake 已提交
1999
    return true;
K
Karel Zak 已提交
2000

2001
 syntaxError:
2002
    if (ctl->cmd) {
K
Karel Zak 已提交
2003
        vshCommandFree(ctl->cmd);
2004 2005
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
2006 2007
    if (first)
        vshCommandOptFree(first);
2008
    VIR_FREE(tkdata);
E
Eric Blake 已提交
2009
    return false;
K
Karel Zak 已提交
2010 2011
}

2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
/* --------------------
 * Command argv parsing
 * --------------------
 */

static vshCommandToken ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
vshCommandArgvGetArg(vshControl *ctl, vshCommandParser *parser, char **res)
{
    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;
}

E
Eric Blake 已提交
2030 2031
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
2032 2033 2034 2035
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
2036
        return false;
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 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108

    parser.arg_pos = argv;
    parser.arg_end = argv + nargs;
    parser.getNextArg = vshCommandArgvGetArg;
    return vshCommandParse(ctl, &parser);
}

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

static vshCommandToken ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
vshCommandStringGetArg(vshControl *ctl, vshCommandParser *parser, char **res)
{
    bool single_quote = false;
    bool double_quote = false;
    int sz = 0;
    char *p = parser->pos;
    char *q = vshStrdup(ctl, p);

    *res = q;

    while (*p && (*p == ' ' || *p == '\t'))
        p++;

    if (*p == '\0')
        return VSH_TK_END;
    if (*p == ';') {
        parser->pos = ++p;             /* = \0 or begin of next command */
        return VSH_TK_SUBCMD_END;
    }

    while (*p) {
        /* end of token is blank space or ';' */
        if (!double_quote && !single_quote &&
            (*p == ' ' || *p == '\t' || *p == ';'))
            break;

        if (!double_quote && *p == '\'') { /* single quote */
            single_quote = !single_quote;
            p++;
            continue;
        } else if (!single_quote && *p == '\\') { /* escape */
            /*
             * The same as the bash, a \ in "" is an escaper,
             * but a \ in '' is not an escaper.
             */
            p++;
            if (*p == '\0') {
                vshError(ctl, "%s", _("dangling \\"));
                return VSH_TK_ERROR;
            }
        } else if (!single_quote && *p == '"') { /* double quote */
            double_quote = !double_quote;
            p++;
            continue;
        }

        *q++ = *p++;
        sz++;
    }
    if (double_quote) {
        vshError(ctl, "%s", _("missing \""));
        return VSH_TK_ERROR;
    }

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

E
Eric Blake 已提交
2109 2110
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
2111 2112 2113 2114
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
2115
        return false;
2116 2117 2118 2119 2120 2121

    parser.pos = cmdstr;
    parser.getNextArg = vshCommandStringGetArg;
    return vshCommandParse(ctl, &parser);
}

K
Karel Zak 已提交
2122
/* ---------------
2123
 * Misc utils
K
Karel Zak 已提交
2124 2125
 * ---------------
 */
E
Eric Blake 已提交
2126
int
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
vshDomainState(vshControl *ctl, virDomainPtr dom, int *reason)
{
    virDomainInfo info;

    if (reason)
        *reason = -1;

    if (!ctl->useGetInfo) {
        int state;
        if (virDomainGetState(dom, &state, reason, 0) < 0) {
            virErrorPtr err = virGetLastError();
            if (err && err->code == VIR_ERR_NO_SUPPORT)
                ctl->useGetInfo = true;
            else
                return -1;
        } else {
            return state;
        }
    }

    /* fall back to virDomainGetInfo if virDomainGetState is not supported */
    if (virDomainGetInfo(dom, &info) < 0)
        return -1;
    else
        return info.state;
}

2154 2155
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
E
Eric Blake 已提交
2156
char *
2157 2158 2159 2160 2161
vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
{
    int ret = 0;
    char *str = NULL;

2162
    switch (item->type) {
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
    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:
E
Eric Blake 已提交
2184
        str = vshStrdup(ctl, item->value.b ? _("yes") : _("no"));
2185 2186
        break;

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

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

2195
    if (ret < 0) {
2196
        vshError(ctl, "%s", _("Out of memory"));
2197 2198
        exit(EXIT_FAILURE);
    }
2199 2200 2201
    return str;
}

E
Eric Blake 已提交
2202
void
2203
vshDebug(vshControl *ctl, int level, const char *format, ...)
2204
{
K
Karel Zak 已提交
2205
    va_list ap;
2206
    char *str;
K
Karel Zak 已提交
2207

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

2215
    va_start(ap, format);
2216
    vshOutputLogFile(ctl, level, format, ap);
2217 2218
    va_end(ap);

K
Karel Zak 已提交
2219
    va_start(ap, format);
2220 2221 2222 2223 2224
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2225
    va_end(ap);
2226 2227
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
2228 2229
}

E
Eric Blake 已提交
2230
void
2231
vshPrintExtra(vshControl *ctl, const char *format, ...)
2232
{
K
Karel Zak 已提交
2233
    va_list ap;
2234
    char *str;
2235

2236
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
2237
        return;
2238

K
Karel Zak 已提交
2239
    va_start(ap, format);
2240 2241 2242 2243 2244
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2245
    va_end(ap);
2246
    fputs(str, stdout);
2247
    VIR_FREE(str);
K
Karel Zak 已提交
2248 2249
}

K
Karel Zak 已提交
2250

E
Eric Blake 已提交
2251
void
2252
vshError(vshControl *ctl, const char *format, ...)
2253
{
K
Karel Zak 已提交
2254
    va_list ap;
2255
    char *str;
2256

2257 2258 2259 2260 2261
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
2262

2263 2264 2265 2266
    /* 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);
2267
    fputs(_("error: "), stderr);
2268

K
Karel Zak 已提交
2269
    va_start(ap, format);
2270 2271 2272
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
2273 2274
    va_end(ap);

2275
    fprintf(stderr, "%s\n", NULLSTR(str));
2276
    fflush(stderr);
2277
    VIR_FREE(str);
K
Karel Zak 已提交
2278 2279
}

2280

J
Jiri Denemark 已提交
2281 2282 2283 2284 2285
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
E
Eric Blake 已提交
2296
            vshReportError(ctl);
J
Jiri Denemark 已提交
2297 2298 2299 2300
    }
}


K
Karel Zak 已提交
2301
/*
2302
 * Initialize connection.
K
Karel Zak 已提交
2303
 */
E
Eric Blake 已提交
2304
static bool
2305
vshInit(vshControl *ctl)
2306
{
2307 2308
    char *debugEnv;

K
Karel Zak 已提交
2309
    if (ctl->conn)
E
Eric Blake 已提交
2310
        return false;
K
Karel Zak 已提交
2311

J
Jiri Denemark 已提交
2312
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
2313 2314 2315
        /* log level not set from commandline, check env variable */
        debugEnv = getenv("VIRSH_DEBUG");
        if (debugEnv) {
J
Jiri Denemark 已提交
2316 2317 2318
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
2319 2320
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
2321 2322
            } else {
                ctl->debug = debug;
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
            }
        }
    }

    if (ctl->logfile == NULL) {
        /* log file not set from cmdline */
        debugEnv = getenv("VIRSH_LOG_FILE");
        if (debugEnv && *debugEnv) {
            ctl->logfile = vshStrdup(ctl, debugEnv);
        }
    }

2335 2336
    vshOpenLogFile(ctl);

2337 2338
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2339

2340
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
2341
        return false;
2342

J
Jiri Denemark 已提交
2343 2344 2345 2346
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

2347
    if (ctl->name) {
2348
        vshReconnect(ctl);
2349 2350 2351 2352 2353 2354 2355
        /* Connecting to a named connection must succeed, but we delay
         * connecting to the default connection until we need it
         * (since the first command might be 'connect' which allows a
         * non-default connection, or might be 'help' which needs no
         * connection).
         */
        if (!ctl->conn) {
E
Eric Blake 已提交
2356
            vshReportError(ctl);
2357 2358
            return false;
        }
2359
    }
K
Karel Zak 已提交
2360

E
Eric Blake 已提交
2361
    return true;
K
Karel Zak 已提交
2362 2363
}

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

2366 2367 2368 2369 2370
/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
E
Eric Blake 已提交
2371
void
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
vshOpenLogFile(vshControl *ctl)
{
    struct stat st;

    if (ctl->logfile == NULL)
        return;

    /* check log file */
    if (stat(ctl->logfile, &st) == -1) {
        switch (errno) {
            case ENOENT:
                break;
            default:
2385
                vshError(ctl, "%s",
J
Jim Meyering 已提交
2386
                         _("failed to get the log file information"));
2387
                exit(EXIT_FAILURE);
2388 2389 2390
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
2391 2392
            vshError(ctl, "%s", _("the log path is not a file"));
            exit(EXIT_FAILURE);
2393 2394 2395 2396
        }
    }

    /* log file open */
2397
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
2398
        vshError(ctl, "%s",
J
Jim Meyering 已提交
2399
                 _("failed to open the log file. check the log file path"));
2400
        exit(EXIT_FAILURE);
2401 2402 2403 2404 2405 2406 2407 2408
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
E
Eric Blake 已提交
2409
void
2410 2411
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
2412
{
2413
    virBuffer buf = VIR_BUFFER_INITIALIZER;
J
John Ferlan 已提交
2414
    char *str = NULL;
2415
    size_t len;
2416
    const char *lvl = "";
2417
    time_t stTime;
2418
    struct tm stTm;
2419 2420 2421 2422 2423 2424 2425 2426 2427

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

    /**
     * create log format
     *
     * [YYYY.MM.DD HH:MM:SS SIGNATURE PID] LOG_LEVEL message
    */
2428 2429
    time(&stTime);
    localtime_r(&stTime, &stTm);
2430
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
2431 2432 2433 2434 2435 2436
                      (1900 + stTm.tm_year),
                      (1 + stTm.tm_mon),
                      stTm.tm_mday,
                      stTm.tm_hour,
                      stTm.tm_min,
                      stTm.tm_sec,
2437 2438
                      SIGN_NAME,
                      (int) getpid());
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
    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;
    }
2459 2460 2461
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
2462

2463 2464
    if (virBufferError(&buf))
        goto error;
2465

2466 2467 2468 2469 2470
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
2471
    }
2472

2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
    /* write log */
    if (safewrite(ctl->log_fd, str, len) < 0)
        goto error;

    return;

error:
    vshCloseLogFile(ctl);
    vshError(ctl, "%s", _("failed to write the log file"));
    virBufferFreeAndReset(&buf);
    VIR_FREE(str);
2484 2485 2486 2487 2488 2489 2490
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
E
Eric Blake 已提交
2491
void
2492 2493
vshCloseLogFile(vshControl *ctl)
{
2494 2495
    char ebuf[1024];

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

    if (ctl->logfile) {
2504
        VIR_FREE(ctl->logfile);
2505 2506 2507 2508
        ctl->logfile = NULL;
    }
}

2509
#ifdef USE_READLINE
2510

K
Karel Zak 已提交
2511 2512 2513 2514 2515
/* -----------------
 * Readline stuff
 * -----------------
 */

2516
/*
K
Karel Zak 已提交
2517 2518
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
2519
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
2520 2521
 */
static char *
2522 2523
vshReadlineCommandGenerator(const char *text, int state)
{
2524
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
2525
    const char *name;
2526 2527
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
2528 2529

    if (!state) {
2530 2531
        grp_list_index = 0;
        cmd_list_index = 0;
2532
        len = strlen(text);
K
Karel Zak 已提交
2533 2534
    }

2535 2536
    grp = cmdGroups;

K
Karel Zak 已提交
2537
    /* Return the next name which partially matches from the
2538
     * command list.
K
Karel Zak 已提交
2539
     */
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
    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)) {
                cmd_list_index++;

                if (STREQLEN(name, text, len))
                    return vshStrdup(NULL, name);
            }
        } else {
            cmd_list_index = 0;
            grp_list_index++;
        }
K
Karel Zak 已提交
2554 2555 2556 2557 2558 2559 2560
    }

    /* If no names matched, then return NULL. */
    return NULL;
}

static char *
2561 2562
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2563
    static int list_index, len;
2564
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
2565
    const char *name;
K
Karel Zak 已提交
2566 2567 2568 2569 2570 2571 2572 2573 2574

    if (!state) {
        /* determine command name */
        char *p;
        char *cmdname;

        if (!(p = strchr(rl_line_buffer, ' ')))
            return NULL;

2575
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
2576
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
2577 2578 2579

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
2580
        len = strlen(text);
2581
        VIR_FREE(cmdname);
K
Karel Zak 已提交
2582 2583 2584 2585
    }

    if (!cmd)
        return NULL;
2586

2587 2588 2589
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
2590
    while ((name = cmd->opts[list_index].name)) {
2591
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
2592
        char *res;
2593

K
Karel Zak 已提交
2594
        list_index++;
2595

2596
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
2597 2598
            /* ignore non --option */
            continue;
2599

K
Karel Zak 已提交
2600
        if (len > 2) {
2601
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
2602 2603
                continue;
        }
2604
        res = vshMalloc(NULL, strlen(name) + 3);
2605
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
2606 2607 2608 2609 2610 2611 2612 2613
        return res;
    }

    /* If no names matched, then return NULL. */
    return NULL;
}

static char **
2614 2615 2616
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2617 2618
    char **matches = (char **) NULL;

2619
    if (start == 0)
K
Karel Zak 已提交
2620
        /* command name generator */
2621
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
2622 2623
    else
        /* commands options */
2624
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
2625 2626 2627 2628
    return matches;
}


2629 2630
static int
vshReadlineInit(vshControl *ctl)
2631
{
2632 2633
    char *userdir = NULL;

K
Karel Zak 已提交
2634 2635 2636 2637 2638
    /* Allow conditional parsing of the ~/.inputrc file. */
    rl_readline_name = "virsh";

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

    /* Limit the total size of the history buffer */
    stifle_history(500);
2642

2643
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
2644
    userdir = virGetUserCacheDirectory();
2645

2646 2647
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
2648
        return -1;
2649
    }
2650

2651
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
2652
        vshError(ctl, "%s", _("Out of memory"));
2653
        VIR_FREE(userdir);
2654 2655 2656 2657 2658
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
2659
        VIR_FREE(userdir);
2660 2661 2662
        return -1;
    }

2663
    VIR_FREE(userdir);
2664 2665 2666 2667 2668 2669 2670

    read_history(ctl->historyfile);

    return 0;
}

static void
2671
vshReadlineDeinit(vshControl *ctl)
2672 2673
{
    if (ctl->historyfile != NULL) {
2674 2675
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
2676 2677
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
2678
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
2679
        } else {
2680
            write_history(ctl->historyfile);
E
Eric Blake 已提交
2681
        }
2682 2683
    }

2684 2685
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
2686 2687
}

2688
static char *
2689
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
2690
{
2691
    return readline(prompt);
2692 2693
}

2694
#else /* !USE_READLINE */
2695

2696
static int
2697
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
2698 2699 2700 2701 2702
{
    /* empty */
    return 0;
}

2703
static void
2704
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
2705 2706 2707 2708 2709
{
    /* empty */
}

static char *
2710
vshReadline(vshControl *ctl, const char *prompt)
2711 2712 2713 2714 2715
{
    char line[1024];
    char *r;
    int len;

2716 2717
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
2718 2719 2720
    if (r == NULL) return NULL; /* EOF */

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

2725
    return vshStrdup(ctl, r);
2726 2727
}

2728
#endif /* !USE_READLINE */
2729

2730 2731 2732 2733 2734 2735
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
2736
/*
J
Jim Meyering 已提交
2737
 * Deinitialize virsh
K
Karel Zak 已提交
2738
 */
E
Eric Blake 已提交
2739
static bool
2740
vshDeinit(vshControl *ctl)
2741
{
2742
    vshReadlineDeinit(ctl);
2743
    vshCloseLogFile(ctl);
2744
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
2745
    if (ctl->conn) {
2746
        int ret;
2747 2748 2749 2750 2751 2752 2753
        virConnectUnregisterCloseCallback(ctl->conn, vshCatchDisconnect);
        ret = virConnectClose(ctl->conn);
        if (ret < 0)
            vshError(ctl, "%s", _("Failed to disconnect from the hypervisor"));
        else if (ret > 0)
            vshError(ctl, "%s", _("One or more references were leaked after "
                                  "disconnect from the hypervisor"));
K
Karel Zak 已提交
2754
    }
D
Daniel P. Berrange 已提交
2755 2756
    virResetLastError();

J
Jiri Denemark 已提交
2757
    if (ctl->eventLoopStarted) {
2758 2759 2760 2761
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
2762
        /* HACK: Add a dummy timeout to break event loop */
2763 2764 2765 2766 2767
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
2768 2769 2770 2771 2772 2773
        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

2774 2775
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
2776
    return true;
K
Karel Zak 已提交
2777
}
2778

K
Karel Zak 已提交
2779 2780 2781
/*
 * Print usage
 */
E
Eric Blake 已提交
2782
static void
2783
vshUsage(void)
2784
{
2785
    const vshCmdGrp *grp;
2786
    const vshCmdDef *cmd;
2787

L
Lai Jiangshan 已提交
2788 2789
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
2790
                      "  options:\n"
2791
                      "    -c | --connect=URI      hypervisor connection URI\n"
2792
                      "    -r | --readonly         connect readonly\n"
2793
                      "    -d | --debug=NUM        debug level [0-4]\n"
2794 2795 2796
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
2797 2798 2799 2800 2801
                      "    -l | --log=FILE         output logging to file\n"
                      "    -v                      short version\n"
                      "    -V                      long version\n"
                      "         --version[=TYPE]   version, TYPE is short or long (default short)\n"
                      "    -e | --escape <char>    set escape sequence for console\n\n"
2802
                      "  commands (non interactive mode):\n\n"), progname, progname);
2803

2804
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
2805 2806 2807 2808 2809
        fprintf(stdout, _(" %s (help keyword '%s')\n"),
                grp->name, grp->keyword);
        for (cmd = grp->commands; cmd->name; cmd++) {
            if (cmd->flags & VSH_CMD_FLAG_ALIAS)
                continue;
2810
            fprintf(stdout,
E
Eric Blake 已提交
2811 2812 2813
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
2814 2815 2816 2817 2818
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
2819 2820 2821
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
2822 2823
}

2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
/*
 * Show version and options compiled in
 */
static void
vshShowVersion(vshControl *ctl ATTRIBUTE_UNUSED)
{
    /* FIXME - list a copyright blurb, as in GNU programs?  */
    vshPrint(ctl, _("Virsh command line tool of libvirt %s\n"), VERSION);
    vshPrint(ctl, _("See web site at %s\n\n"), "http://libvirt.org/");

L
Laine Stump 已提交
2834 2835
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
2836
#ifdef WITH_QEMU
2837
    vshPrint(ctl, " QEMU/KVM");
2838
#endif
D
Doug Goldstein 已提交
2839 2840 2841
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
2842 2843 2844
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
2845 2846 2847 2848 2849 2850
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
2851 2852 2853
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
2854 2855
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
2856
#endif
D
Doug Goldstein 已提交
2857 2858
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
2859
#endif
D
Doug Goldstein 已提交
2860 2861
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
2862 2863 2864 2865
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
2866 2867
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
2868
#endif
D
Doug Goldstein 已提交
2869 2870
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
2871 2872 2873 2874 2875 2876
#endif
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2877
    vshPrint(ctl, "%s", _(" Networking:"));
2878 2879 2880 2881 2882 2883 2884 2885 2886
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
2887
#if defined(WITH_INTERFACE)
D
Doug Goldstein 已提交
2888
    vshPrint(ctl, " Interface");
2889 2890
# if defined(WITH_NETCF)
    vshPrint(ctl, " netcf");
2891
# elif defined(WITH_UDEV)
2892
    vshPrint(ctl, " udev");
2893
# endif
2894 2895 2896 2897 2898 2899 2900 2901 2902
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2903
    vshPrint(ctl, "%s", _(" Storage:"));
2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
#ifdef WITH_STORAGE_DIR
    vshPrint(ctl, " Dir");
#endif
#ifdef WITH_STORAGE_DISK
    vshPrint(ctl, " Disk");
#endif
#ifdef WITH_STORAGE_FS
    vshPrint(ctl, " Filesystem");
#endif
#ifdef WITH_STORAGE_SCSI
    vshPrint(ctl, " SCSI");
#endif
#ifdef WITH_STORAGE_MPATH
    vshPrint(ctl, " Multipath");
#endif
#ifdef WITH_STORAGE_ISCSI
    vshPrint(ctl, " iSCSI");
#endif
#ifdef WITH_STORAGE_LVM
    vshPrint(ctl, " LVM");
2924 2925 2926
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
2927 2928 2929
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
2930 2931 2932
#endif
    vshPrint(ctl, "\n");

2933
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
2934 2935 2936
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977
#ifdef WITH_NODE_DEVICES
    vshPrint(ctl, " Nodedev");
#endif
#ifdef WITH_SECDRIVER_APPARMOR
    vshPrint(ctl, " AppArmor");
#endif
#ifdef WITH_SECDRIVER_SELINUX
    vshPrint(ctl, " SELinux");
#endif
#ifdef WITH_SECRETS
    vshPrint(ctl, " Secrets");
#endif
#ifdef ENABLE_DEBUG
    vshPrint(ctl, " Debug");
#endif
#ifdef WITH_DTRACE_PROBES
    vshPrint(ctl, " DTrace");
#endif
#ifdef USE_READLINE
    vshPrint(ctl, " Readline");
#endif
#ifdef WITH_DRIVER_MODULES
    vshPrint(ctl, " Modular");
#endif
    vshPrint(ctl, "\n");
}

static bool
vshAllowedEscapeChar(char c)
{
    /* Allowed escape characters:
     * a-z A-Z @ [ \ ] ^ _
     */
    return ('a' <= c && c <= 'z') ||
        ('@' <= c && c <= '_');
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
E
Eric Blake 已提交
2978
static bool
2979 2980
vshParseArgv(vshControl *ctl, int argc, char **argv)
{
2981 2982
    int arg, len, debug, i;
    int longindex = -1;
2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998
    struct option opt[] = {
        {"debug", required_argument, NULL, 'd'},
        {"help", no_argument, NULL, 'h'},
        {"quiet", no_argument, NULL, 'q'},
        {"timing", no_argument, NULL, 't'},
        {"version", optional_argument, NULL, 'v'},
        {"connect", required_argument, NULL, 'c'},
        {"readonly", no_argument, NULL, 'r'},
        {"log", required_argument, NULL, 'l'},
        {"escape", required_argument, NULL, 'e'},
        {NULL, 0, NULL, 0}
    };

    /* Standard (non-command) options. The leading + ensures that no
     * argument reordering takes place, so that command options are
     * not confused with top-level virsh options. */
2999
    while ((arg = getopt_long(argc, argv, "+:d:hqtc:vVrl:e:", opt, &longindex)) != -1) {
3000 3001
        switch (arg) {
        case 'd':
3002
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
3003 3004
                vshError(ctl, _("option %s takes a numeric argument"),
                         longindex == -1 ? "-d" : "--debug");
3005 3006
                exit(EXIT_FAILURE);
            }
3007 3008 3009 3010 3011
            if (debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR)
                vshError(ctl, _("ignoring debug level %d out of range [%d-%d]"),
                         debug, VSH_ERR_DEBUG, VSH_ERR_ERROR);
            else
                ctl->debug = debug;
3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
            break;
        case 'h':
            vshUsage();
            exit(EXIT_SUCCESS);
            break;
        case 'q':
            ctl->quiet = true;
            break;
        case 't':
            ctl->timing = true;
            break;
        case 'c':
            ctl->name = vshStrdup(ctl, optarg);
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
            /* fall through */
        case 'V':
            vshShowVersion(ctl);
            exit(EXIT_SUCCESS);
        case 'r':
            ctl->readonly = true;
            break;
        case 'l':
            ctl->logfile = vshStrdup(ctl, optarg);
            break;
        case 'e':
            len = strlen(optarg);

            if ((len == 2 && *optarg == '^' &&
                 vshAllowedEscapeChar(optarg[1])) ||
                (len == 1 && *optarg != '^')) {
                ctl->escapeChar = optarg;
            } else {
                vshError(ctl, _("Invalid string '%s' for escape sequence"),
                         optarg);
                exit(EXIT_FAILURE);
            }
            break;
3054
        case ':':
3055
            for (i = 0; opt[i].name != NULL; i++) {
3056 3057
                if (opt[i].val == optopt)
                    break;
3058
            }
3059 3060 3061 3062 3063 3064
            if (opt[i].name)
                vshError(ctl, _("option '-%c'/'--%s' requires an argument"),
                         optopt, opt[i].name);
            else
                vshError(ctl, _("option '-%c' requires an argument"), optopt);
            exit(EXIT_FAILURE);
3065
        case '?':
3066 3067 3068 3069
            if (optopt)
                vshError(ctl, _("unsupported option '-%c'. See --help."), optopt);
            else
                vshError(ctl, _("unsupported option '%s'. See --help."), argv[optind - 1]);
3070
            exit(EXIT_FAILURE);
3071
        default:
3072
            vshError(ctl, _("unknown option"));
3073 3074
            exit(EXIT_FAILURE);
        }
3075
        longindex = -1;
3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
    }

    if (argc > optind) {
        /* parse command */
        ctl->imode = false;
        if (argc - optind == 1) {
            vshDebug(ctl, VSH_ERR_INFO, "commands: \"%s\"\n", argv[optind]);
            return vshCommandStringParse(ctl, argv[optind]);
        } else {
            return vshCommandArgvParse(ctl, argc - optind, argv + optind);
        }
    }
    return true;
}

static const vshCmdDef virshCmds[] = {
3092 3093 3094 3095 3096
    {.name = "cd",
     .handler = cmdCd,
     .opts = opts_cd,
     .info = info_cd,
     .flags = VSH_CMD_FLAG_NOCONNECT
3097 3098 3099 3100 3101 3102
    },
    {.name = "connect",
     .handler = cmdConnect,
     .opts = opts_connect,
     .info = info_connect,
     .flags = VSH_CMD_FLAG_NOCONNECT
3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
    },
    {.name = "echo",
     .handler = cmdEcho,
     .opts = opts_echo,
     .info = info_echo,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "exit",
     .handler = cmdQuit,
     .opts = NULL,
     .info = info_quit,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "help",
     .handler = cmdHelp,
     .opts = opts_help,
     .info = info_help,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "pwd",
     .handler = cmdPwd,
     .opts = NULL,
     .info = info_pwd,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "quit",
     .handler = cmdQuit,
     .opts = NULL,
     .info = info_quit,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = NULL}
3135
};
3136

3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
static const vshCmdGrp cmdGroups[] = {
    {VSH_CMD_GRP_DOM_MANAGEMENT, "domain", domManagementCmds},
    {VSH_CMD_GRP_DOM_MONITORING, "monitor", domMonitoringCmds},
    {VSH_CMD_GRP_HOST_AND_HV, "host", hostAndHypervisorCmds},
    {VSH_CMD_GRP_IFACE, "interface", ifaceCmds},
    {VSH_CMD_GRP_NWFILTER, "filter", nwfilterCmds},
    {VSH_CMD_GRP_NETWORK, "network", networkCmds},
    {VSH_CMD_GRP_NODEDEV, "nodedev", nodedevCmds},
    {VSH_CMD_GRP_SECRET, "secret", secretCmds},
    {VSH_CMD_GRP_SNAPSHOT, "snapshot", snapshotCmds},
    {VSH_CMD_GRP_STORAGE_POOL, "pool", storagePoolCmds},
    {VSH_CMD_GRP_STORAGE_VOL, "volume", storageVolCmds},
    {VSH_CMD_GRP_VIRSH, "virsh", virshCmds},
    {NULL, NULL, NULL}
};
K
Karel Zak 已提交
3152

3153 3154 3155 3156
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
3157
    char *defaultConn;
E
Eric Blake 已提交
3158
    bool ret = true;
K
Karel Zak 已提交
3159

3160 3161 3162
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
3163
    ctl->debug = VSH_DEBUG_DEFAULT;
E
Eric Blake 已提交
3164
    ctl->escapeChar = "^]";     /* Same default as telnet */
3165

3166

3167 3168
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
3169
        /* failure to setup locale is not fatal */
3170
    }
3171
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
3172
        perror("bindtextdomain");
E
Eric Blake 已提交
3173
        return EXIT_FAILURE;
3174
    }
3175
    if (!textdomain(PACKAGE)) {
3176
        perror("textdomain");
E
Eric Blake 已提交
3177
        return EXIT_FAILURE;
3178 3179
    }

3180 3181 3182 3183 3184
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

3185 3186 3187 3188 3189
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

3190
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
3191 3192 3193
        progname = argv[0];
    else
        progname++;
3194

3195
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
E
Eric Blake 已提交
3196
        ctl->name = vshStrdup(ctl, defaultConn);
3197 3198
    }

3199
    if (!vshInit(ctl)) {
D
Daniel P. Berrange 已提交
3200
        vshDeinit(ctl);
K
Karel Zak 已提交
3201
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3202
    }
3203

3204
    if (!vshParseArgv(ctl, argc, argv)) {
D
Daniel P. Berrange 已提交
3205
        vshDeinit(ctl);
K
Karel Zak 已提交
3206
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3207
    }
3208

K
Karel Zak 已提交
3209
    if (!ctl->imode) {
3210
        ret = vshCommandRun(ctl, ctl->cmd);
3211
    } else {
K
Karel Zak 已提交
3212 3213
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
3214
            vshPrint(ctl,
3215
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
3216
                     progname);
J
Jim Meyering 已提交
3217
            vshPrint(ctl, "%s",
3218
                     _("Type:  'help' for help with commands\n"
3219
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
3220
        }
3221 3222 3223 3224 3225 3226

        if (vshReadlineInit(ctl) < 0) {
            vshDeinit(ctl);
            exit(EXIT_FAILURE);
        }

K
Karel Zak 已提交
3227
        do {
3228
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
3229
            ctl->cmdstr =
3230
                vshReadline(ctl, prompt);
3231 3232
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
3233
            if (*ctl->cmdstr) {
3234
#if USE_READLINE
K
Karel Zak 已提交
3235
                add_history(ctl->cmdstr);
3236
#endif
3237
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
3238 3239
                    vshCommandRun(ctl, ctl->cmd);
            }
3240
            VIR_FREE(ctl->cmdstr);
3241
        } while (ctl->imode);
K
Karel Zak 已提交
3242

3243 3244
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
3245
    }
3246

K
Karel Zak 已提交
3247 3248
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
3249
}