virsh.c 78.1 KB
Newer Older
1
/*
2
 * virsh.c: a shell to exercise the libvirt API
3
 *
4
 * Copyright (C) 2005, 2007-2012 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 <assert.h>
42
#include <sys/stat.h>
43
#include <inttypes.h>
E
Eric Blake 已提交
44
#include <strings.h>
K
Karel Zak 已提交
45

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

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

56
#include "internal.h"
57
#include "virterror_internal.h"
58
#include "base64.h"
59
#include "virbuffer.h"
60
#include "console.h"
61
#include "util.h"
62
#include "memory.h"
63
#include "xml.h"
64
#include "libvirt/libvirt-qemu.h"
E
Eric Blake 已提交
65
#include "virfile.h"
66
#include "event_poll.h"
67
#include "configmake.h"
68
#include "threads.h"
E
Eric Blake 已提交
69
#include "command.h"
70
#include "virkeycode.h"
71
#include "virnetdevbandwidth.h"
72
#include "virbitmap.h"
H
Hu Tao 已提交
73
#include "conf/domain_conf.h"
74
#include "virtypedparam.h"
K
Karel Zak 已提交
75

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

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

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

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

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

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

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

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

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

    if (s == NULL)
127
        return NULL;
E
Eric Blake 已提交
128 129 130 131 132 133 134 135 136
    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
137

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

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

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

168 169
/*
 * Convert the strings separated by ',' into array. The caller
E
Eric Blake 已提交
170 171 172
 * 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).
173 174 175 176 177
 *
 * Returns the length of the filled array on success, or -1
 * on error.
 */
int
178
vshStringToArray(const char *str,
179 180
                 char ***array)
{
181
    char *str_copied = vshStrdup(NULL, str);
182
    char *str_tok = NULL;
E
Eric Blake 已提交
183
    char *tmp;
184 185
    unsigned int nstr_tokens = 0;
    char **arr = NULL;
E
Eric Blake 已提交
186
    size_t len = strlen(str_copied);
187

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

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

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

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

    *array = arr;
    return nstr_tokens;
}
227

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

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

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

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

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

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

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

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

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

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

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

    if (ctl->conn != NULL) {
        connected = true;
327
        virConnectClose(ctl->conn);
328
    }
329 330 331 332

    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);
333
    if (!ctl->conn) {
334 335 336 337
        if (disconnected)
            vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
        else
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
338 339 340 341 342 343 344
    } 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"));
    }
345
    disconnected = 0;
346
    ctl->useGetInfo = false;
347
    ctl->useSnapshotOld = false;
348
}
349

350
#ifndef WIN32
351 352 353 354 355 356 357 358 359 360 361 362 363
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);
}

364 365 366 367 368 369 370 371 372 373 374 375 376
/**
 * 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 已提交
377
int
378 379 380 381 382 383 384 385
vshAskReedit(vshControl *ctl, const char *msg)
{
    int c = -1;
    struct termios ttyattr;

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

E
Eric Blake 已提交
386
    vshReportError(ctl);
387 388 389 390 391 392 393 394 395 396 397

    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 == '?') {
398 399 400 401 402 403 404
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
405 406 407 408 409 410 411 412 413 414
            continue;
        } else if (c == 'y' || c == 'n' || c == 'f') {
            break;
        }
    }

    tcsetattr(STDIN_FILENO, TCSAFLUSH, &ttyattr);

    vshPrint(ctl, "\r\n");
    return c;
415 416
}
#else /* WIN32 */
417
int
418 419
vshAskReedit(vshControl *ctl, const char *msg ATTRIBUTE_UNUSED)
{
420 421 422 423
    vshDebug(ctl, VSH_ERR_WARNING, "%s", _("This function is not "
                                           "supported on WIN32 platform"));
    return 0;
}
424
#endif /* WIN32 */
425

E
Eric Blake 已提交
426 427
int vshStreamSink(virStreamPtr st ATTRIBUTE_UNUSED,
                  const char *bytes, size_t nbytes, void *opaque)
428 429 430 431 432 433
{
    int *fd = opaque;

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

K
Karel Zak 已提交
434 435 436 437 438 439
/* ---------------
 * Commands
 * ---------------
 */

/*
440
 * "help" command
K
Karel Zak 已提交
441
 */
442
static const vshCmdInfo info_help[] = {
443
    {"help", N_("print help")},
444 445
    {"desc", N_("Prints global help, command specific help, or help for a\n"
                "    group of related commands")},
446

447
    {NULL, NULL}
K
Karel Zak 已提交
448 449
};

450
static const vshCmdOptDef opts_help[] = {
451
    {"command", VSH_OT_DATA, 0, N_("Prints global help, command specific help, or help for a group of related commands")},
452
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
453 454
};

E
Eric Blake 已提交
455
static bool
456
cmdHelp(vshControl *ctl, const vshCmd *cmd)
457
 {
458
    const char *name = NULL;
459

460
    if (vshCommandOptString(cmd, "command", &name) <= 0) {
461
        const vshCmdGrp *grp;
462
        const vshCmdDef *def;
463

464 465 466 467 468 469
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

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

470 471 472
            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
473 474
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
475
            }
476 477 478 479

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
480
        return true;
481
    }
482

E
Eric Blake 已提交
483
    if (vshCmddefSearch(name)) {
484
        return vshCmddefHelp(ctl, name);
E
Eric Blake 已提交
485
    } else if (vshCmdGrpSearch(name)) {
486 487 488
        return vshCmdGrpHelp(ctl, name);
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
E
Eric Blake 已提交
489
        return false;
K
Karel Zak 已提交
490 491 492
    }
}

493 494 495 496 497 498 499 500 501 502 503
/* Tree listing helpers.  */

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

510
    if (virBufferError(indent))
511 512
        goto cleanup;

513 514 515 516 517 518 519 520 521 522
    /* 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;
523 524
    }

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

529 530 531
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
532

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

537 538 539 540
    /* Finally print all children */
    virBufferAddLit(indent, "  ");
    for (i = 0 ; i < num_devices ; i++) {
        const char *parent = (lookup)(i, true, opaque);
541

542 543 544 545 546
        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
547
    }
548
    virBufferTrim(indent, "  ", -1);
549

550 551 552 553
    /* 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));
554

555 556 557
    if (!root)
        virBufferTrim(indent, NULL, 2);
    ret = 0;
558 559 560 561
cleanup:
    return ret;
}

E
Eric Blake 已提交
562
int
563 564
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
565
{
566 567
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;
568

569 570 571 572 573
    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
574
    return ret;
575
}
576

577
/* Common code for the edit / net-edit / pool-edit functions which follow. */
E
Eric Blake 已提交
578
char *
E
Eric Blake 已提交
579
vshEditWriteToTempFile(vshControl *ctl, const char *doc)
580 581 582 583
{
    char *ret;
    const char *tmpdir;
    int fd;
584
    char ebuf[1024];
585

586
    tmpdir = getenv("TMPDIR");
587
    if (!tmpdir) tmpdir = "/tmp";
588 589 590 591
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
592
    fd = mkostemps(ret, 4, O_CLOEXEC);
593
    if (fd == -1) {
594
        vshError(ctl, _("mkostemps: failed to create temporary file: %s"),
595
                 virStrerror(errno, ebuf, sizeof(ebuf)));
596
        VIR_FREE(ret);
597 598 599
        return NULL;
    }

600
    if (safewrite(fd, doc, strlen(doc)) == -1) {
601
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
602
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
S
Stefan Berger 已提交
603
        VIR_FORCE_CLOSE(fd);
604
        unlink(ret);
605
        VIR_FREE(ret);
606 607
        return NULL;
    }
S
Stefan Berger 已提交
608
    if (VIR_CLOSE(fd) < 0) {
609
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
610
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
611
        unlink(ret);
612
        VIR_FREE(ret);
613 614 615 616 617 618 619 620 621 622 623
        return NULL;
    }

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

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

E
Eric Blake 已提交
624
int
E
Eric Blake 已提交
625
vshEditFile(vshControl *ctl, const char *filename)
626 627
{
    const char *editor;
E
Eric Blake 已提交
628 629 630 631
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;
632

633
    editor = getenv("VISUAL");
E
Eric Blake 已提交
634
    if (!editor)
635
        editor = getenv("EDITOR");
E
Eric Blake 已提交
636 637
    if (!editor)
        editor = "vi"; /* could be cruel & default to ed(1) here */
638

639 640 641 642 643
    /* 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 已提交
644 645
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
646
     */
647 648
    if (strspn(editor, ACCEPTED_CHARS) != strlen(editor)) {
        if (strspn(filename, ACCEPTED_CHARS) != strlen(filename)) {
E
Eric Blake 已提交
649 650 651 652 653 654 655 656 657 658
            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);
659 660
    }

E
Eric Blake 已提交
661 662 663 664 665
    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
E
Eric Blake 已提交
666
        vshReportError(ctl);
E
Eric Blake 已提交
667
        goto cleanup;
668
    }
E
Eric Blake 已提交
669
    ret = 0;
670

E
Eric Blake 已提交
671 672 673
cleanup:
    virCommandFree(cmd);
    return ret;
674 675
}

E
Eric Blake 已提交
676
char *
E
Eric Blake 已提交
677
vshEditReadBackFile(vshControl *ctl, const char *filename)
678 679
{
    char *ret;
680
    char ebuf[1024];
681

E
Eric Blake 已提交
682
    if (virFileReadAll(filename, VSH_MAX_XML_FILE, &ret) == -1) {
683
        vshError(ctl,
684
                 _("%s: failed to read temporary file: %s"),
685
                 filename, virStrerror(errno, ebuf, sizeof(ebuf)));
686 687 688 689 690
        return NULL;
    }
    return ret;
}

691

P
Paolo Bonzini 已提交
692 693 694 695
/*
 * "cd" command
 */
static const vshCmdInfo info_cd[] = {
696 697
    {"help", N_("change the current directory")},
    {"desc", N_("Change the current directory.")},
P
Paolo Bonzini 已提交
698 699 700 701
    {NULL, NULL}
};

static const vshCmdOptDef opts_cd[] = {
702
    {"dir", VSH_OT_DATA, 0, N_("directory to switch to (default: home or else root)")},
P
Paolo Bonzini 已提交
703 704 705
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
706
static bool
707
cmdCd(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
708
{
709
    const char *dir = NULL;
710
    char *dir_malloced = NULL;
E
Eric Blake 已提交
711
    bool ret = true;
712
    char ebuf[1024];
P
Paolo Bonzini 已提交
713 714

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

719
    if (vshCommandOptString(cmd, "dir", &dir) <= 0) {
720
        dir = dir_malloced = virGetUserDirectory();
P
Paolo Bonzini 已提交
721 722 723 724
    }
    if (!dir)
        dir = "/";

P
Phil Petty 已提交
725
    if (chdir(dir) == -1) {
726 727
        vshError(ctl, _("cd: %s: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)), dir);
E
Eric Blake 已提交
728
        ret = false;
P
Paolo Bonzini 已提交
729 730
    }

731
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
732
    return ret;
P
Paolo Bonzini 已提交
733 734 735 736 737 738
}

/*
 * "pwd" command
 */
static const vshCmdInfo info_pwd[] = {
739 740
    {"help", N_("print the current directory")},
    {"desc", N_("Print the current directory.")},
P
Paolo Bonzini 已提交
741 742 743
    {NULL, NULL}
};

E
Eric Blake 已提交
744
static bool
P
Paolo Bonzini 已提交
745 746 747
cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cwd;
748
    bool ret = true;
749
    char ebuf[1024];
P
Paolo Bonzini 已提交
750

751 752
    cwd = getcwd(NULL, 0);
    if (!cwd) {
753
        vshError(ctl, _("pwd: cannot get current directory: %s"),
754
                 virStrerror(errno, ebuf, sizeof(ebuf)));
755 756
        ret = false;
    } else {
757
        vshPrint(ctl, _("%s\n"), cwd);
758 759
        VIR_FREE(cwd);
    }
P
Paolo Bonzini 已提交
760

761
    return ret;
P
Paolo Bonzini 已提交
762 763
}

E
Eric Blake 已提交
764 765 766 767 768 769 770 771 772 773 774 775
/*
 * "echo" command
 */
static const vshCmdInfo info_echo[] = {
    {"help", N_("echo arguments")},
    {"desc", N_("Echo back arguments, possibly with quoting.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_echo[] = {
    {"shell", VSH_OT_BOOL, 0, N_("escape for shell use")},
    {"xml", VSH_OT_BOOL, 0, N_("escape for XML use")},
E
Eric Blake 已提交
776
    {"str", VSH_OT_ALIAS, 0, "string"},
777
    {"string", VSH_OT_ARGV, 0, N_("arguments to echo")},
E
Eric Blake 已提交
778 779 780 781 782 783
    {NULL, 0, 0, NULL}
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
E
Eric Blake 已提交
784
static bool
785
cmdEcho(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
786 787 788 789
{
    bool shell = false;
    bool xml = false;
    int count = 0;
790
    const vshCmdOpt *opt = NULL;
E
Eric Blake 已提交
791 792 793 794 795 796 797 798
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

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

799
    while ((opt = vshCommandOptArgv(cmd, opt))) {
800 801
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
802

803
        arg = opt->data;
804

E
Eric Blake 已提交
805 806
        if (count)
            virBufferAddChar(&buf, ' ');
807

E
Eric Blake 已提交
808
        if (xml) {
809 810 811 812
            virBufferEscapeString(&xmlbuf, "%s", arg);
            if (virBufferError(&buf)) {
                vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
                return false;
E
Eric Blake 已提交
813
            }
814 815 816
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
E
Eric Blake 已提交
817
        }
818 819 820 821 822

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
E
Eric Blake 已提交
823
        count++;
824
        VIR_FREE(str);
E
Eric Blake 已提交
825 826 827 828
    }

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
829
        return false;
E
Eric Blake 已提交
830 831 832 833 834
    }
    arg = virBufferContentAndReset(&buf);
    if (arg)
        vshPrint(ctl, "%s", arg);
    VIR_FREE(arg);
E
Eric Blake 已提交
835
    return true;
E
Eric Blake 已提交
836 837
}

K
Karel Zak 已提交
838 839 840
/*
 * "quit" command
 */
841
static const vshCmdInfo info_quit[] = {
842
    {"help", N_("quit this interactive terminal")},
843
    {"desc", ""},
844
    {NULL, NULL}
K
Karel Zak 已提交
845 846
};

E
Eric Blake 已提交
847
static bool
848
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
849
{
E
Eric Blake 已提交
850 851
    ctl->imode = false;
    return true;
K
Karel Zak 已提交
852 853
}

854 855 856 857
/* ---------------
 * Utils for work with command definition
 * ---------------
 */
E
Eric Blake 已提交
858
const char *
859 860 861
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
{
    const vshCmdInfo *info;
862

863 864 865 866 867 868
    for (info = cmd->info; info && info->name; info++) {
        if (STREQ(info->name, name))
            return info->data;
    }
    return NULL;
}
869

870 871 872 873 874 875 876
/* 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;
877

878 879
    *opts_need_arg = 0;
    *opts_required = 0;
880

881 882
    if (!cmd->opts)
        return 0;
883

884 885
    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
886 887 888 889

        if (i > 31)
            return -1; /* too many options */
        if (opt->type == VSH_OT_BOOL) {
E
Eric Blake 已提交
890
            if (opt->flags & VSH_OFLAG_REQ)
891 892 893
                return -1; /* bool options can't be mandatory */
            continue;
        }
E
Eric Blake 已提交
894 895 896 897 898 899 900 901 902 903 904 905
        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 已提交
906 907
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
L
Lai Jiangshan 已提交
908 909 910 911
                *opts_required |= 1 << i;
            continue;
        }

912
        *opts_need_arg |= 1 << i;
E
Eric Blake 已提交
913
        if (opt->flags & VSH_OFLAG_REQ) {
914 915 916 917 918 919
            if (optional)
                return -1; /* mandatory options must be listed first */
            *opts_required |= 1 << i;
        } else {
            optional = true;
        }
920 921 922

        if (opt->type == VSH_OT_ARGV && cmd->opts[i + 1].name)
            return -1; /* argv option must be listed last */
923 924 925 926
    }
    return 0;
}

927 928
static vshCmdOptDef helpopt = {"help", VSH_OT_BOOL, 0,
                               N_("print help for this function")};
929
static const vshCmdOptDef *
930
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
931
                   uint32_t *opts_seen, int *opt_index)
932
{
933 934
    int i;

935 936 937 938
    if (STREQ(name, helpopt.name)) {
        return &helpopt;
    }

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

942
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
943 944 945 946
            if (opt->type == VSH_OT_ALIAS) {
                name = opt->help;
                continue;
            }
947
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
948 949 950
                vshError(ctl, _("option --%s already seen"), name);
                return NULL;
            }
951 952
            *opts_seen |= 1 << i;
            *opt_index = i;
K
Karel Zak 已提交
953
            return opt;
954 955 956
        }
    }

957 958 959 960
    if (STRNEQ(cmd->name, "help")) {
        vshError(ctl, _("command '%s' doesn't support option --%s"),
                 cmd->name, name);
    }
K
Karel Zak 已提交
961 962 963
    return NULL;
}

964
static const vshCmdOptDef *
965 966
vshCmddefGetData(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                 uint32_t *opts_seen)
967
{
968
    int i;
969
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
970

971 972 973 974
    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
E
Eric Blake 已提交
975
    i = ffs(*opts_need_arg) - 1;
976
    opt = &cmd->opts[i];
977
    if (opt->type != VSH_OT_ARGV)
978
        *opts_need_arg &= ~(1 << i);
979
    *opts_seen |= 1 << i;
980
    return opt;
K
Karel Zak 已提交
981 982
}

983 984 985
/*
 * Checks for required options
 */
986
static int
987 988
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint32_t opts_required,
                    uint32_t opts_seen)
989
{
990
    const vshCmdDef *def = cmd->def;
991 992 993 994 995 996 997 998 999
    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];
1000

1001
            vshError(ctl,
1002
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
1003 1004 1005
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
1006 1007
        }
    }
1008
    return -1;
1009 1010
}

E
Eric Blake 已提交
1011
const vshCmdDef *
1012 1013
vshCmddefSearch(const char *cmdname)
{
1014
    const vshCmdGrp *g;
1015
    const vshCmdDef *c;
1016

1017 1018
    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
1019
            if (STREQ(c->name, cmdname))
1020 1021 1022 1023
                return c;
        }
    }

K
Karel Zak 已提交
1024 1025 1026
    return NULL;
}

E
Eric Blake 已提交
1027
const vshCmdGrp *
1028 1029 1030 1031 1032
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
1033
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
1034 1035 1036 1037 1038 1039
            return g;
    }

    return NULL;
}

E
Eric Blake 已提交
1040
bool
1041 1042 1043 1044 1045 1046 1047
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 已提交
1048
        return false;
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    } else {
        vshPrint(ctl, _(" %s (help keyword '%s'):\n"), grp->name,
                 grp->keyword);

        for (cmd = grp->commands; cmd->name; cmd++) {
            vshPrint(ctl, "    %-30s %s\n", cmd->name,
                     _(vshCmddefGetInfo(cmd, "help")));
        }
    }

E
Eric Blake 已提交
1059
    return true;
1060 1061
}

E
Eric Blake 已提交
1062
bool
1063
vshCmddefHelp(vshControl *ctl, const char *cmdname)
1064
{
1065
    const vshCmdDef *def = vshCmddefSearch(cmdname);
1066

K
Karel Zak 已提交
1067
    if (!def) {
1068
        vshError(ctl, _("command '%s' doesn't exist"), cmdname);
E
Eric Blake 已提交
1069
        return false;
1070
    } else {
E
Eric Blake 已提交
1071 1072
        /* Don't translate desc if it is "".  */
        const char *desc = vshCmddefGetInfo(def, "desc");
E
Eric Blake 已提交
1073
        const char *help = _(vshCmddefGetInfo(def, "help"));
1074
        char buf[256];
1075 1076
        uint32_t opts_need_arg;
        uint32_t opts_required;
1077
        bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
1078 1079 1080 1081

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

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

1088 1089 1090 1091 1092
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
1093
                const char *fmt = "%s";
1094 1095
                switch (opt->type) {
                case VSH_OT_BOOL:
1096
                    fmt = "[--%s]";
1097 1098
                    break;
                case VSH_OT_INT:
E
Eric Blake 已提交
1099
                    /* xgettext:c-format */
E
Eric Blake 已提交
1100
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
1101
                           : _("[--%s <number>]"));
1102 1103
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1104 1105
                    break;
                case VSH_OT_STRING:
E
Eric Blake 已提交
1106 1107
                    /* xgettext:c-format */
                    fmt = _("[--%s <string>]");
1108 1109
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1110 1111
                    break;
                case VSH_OT_DATA:
E
Eric Blake 已提交
1112
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
1113 1114
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1115 1116 1117
                    break;
                case VSH_OT_ARGV:
                    /* xgettext:c-format */
1118 1119 1120 1121 1122 1123 1124 1125
                    if (shortopt) {
                        fmt = (opt->flags & VSH_OFLAG_REQ)
                            ? _("{[--%s] <string>}...")
                            : _("[[--%s] <string>]...");
                    } else {
                        fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                            : _("[<%s>]...");
                    }
1126
                    break;
E
Eric Blake 已提交
1127 1128 1129
                case VSH_OT_ALIAS:
                    /* aliases are intentionally undocumented */
                    continue;
1130
                default:
1131
                    assert(0);
1132
                }
1133
                fputc(' ', stdout);
E
Eric Blake 已提交
1134
                fprintf(stdout, fmt, opt->name);
1135
            }
K
Karel Zak 已提交
1136
        }
1137 1138 1139
        fputc('\n', stdout);

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

K
Karel Zak 已提交
1145
        if (def->opts) {
1146
            const vshCmdOptDef *opt;
1147
            fputs(_("\n  OPTIONS\n"), stdout);
1148
            for (opt = def->opts; opt->name; opt++) {
1149 1150
                switch (opt->type) {
                case VSH_OT_BOOL:
K
Karel Zak 已提交
1151
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1152 1153
                    break;
                case VSH_OT_INT:
1154
                    snprintf(buf, sizeof(buf),
E
Eric Blake 已提交
1155
                             (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
1156
                             : _("--%s <number>"), opt->name);
1157 1158
                    break;
                case VSH_OT_STRING:
1159
                    /* OT_STRING should never be VSH_OFLAG_REQ */
1160
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
1161 1162
                    break;
                case VSH_OT_DATA:
1163 1164
                    snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                             opt->name);
1165 1166
                    break;
                case VSH_OT_ARGV:
1167 1168 1169
                    snprintf(buf, sizeof(buf),
                             shortopt ? _("[--%s] <string>") : _("<%s>"),
                             opt->name);
1170
                    break;
E
Eric Blake 已提交
1171 1172
                case VSH_OT_ALIAS:
                    continue;
1173 1174 1175
                default:
                    assert(0);
                }
1176

E
Eric Blake 已提交
1177
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
1178
            }
K
Karel Zak 已提交
1179 1180 1181
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
1182
    return true;
K
Karel Zak 已提交
1183 1184 1185 1186 1187 1188
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1189 1190 1191
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1192 1193
    vshCmdOpt *a = arg;

1194
    while (a) {
K
Karel Zak 已提交
1195
        vshCmdOpt *tmp = a;
1196

K
Karel Zak 已提交
1197 1198
        a = a->next;

1199 1200
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
1201 1202 1203 1204
    }
}

static void
1205
vshCommandFree(vshCmd *cmd)
1206
{
K
Karel Zak 已提交
1207 1208
    vshCmd *c = cmd;

1209
    while (c) {
K
Karel Zak 已提交
1210
        vshCmd *tmp = c;
1211

K
Karel Zak 已提交
1212 1213 1214 1215
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
1216
        VIR_FREE(tmp);
K
Karel Zak 已提交
1217 1218 1219
    }
}

E
Eric Blake 已提交
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
/**
 * 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 已提交
1231
 */
E
Eric Blake 已提交
1232
int
E
Eric Blake 已提交
1233
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
1234
{
E
Eric Blake 已提交
1235 1236
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
1237

E
Eric Blake 已提交
1238 1239 1240 1241 1242 1243 1244
    /* 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 已提交
1245
    }
E
Eric Blake 已提交
1246 1247 1248 1249 1250 1251 1252

    /* Option not present, see if command requires it.  */
    *opt = NULL;
    while (valid) {
        if (!valid->name)
            break;
        if (STREQ(name, valid->name))
E
Eric Blake 已提交
1253
            return (valid->flags & VSH_OFLAG_REQ) == 0 ? 0 : -1;
E
Eric Blake 已提交
1254 1255 1256 1257
        valid++;
    }
    /* If we got here, the name is unknown.  */
    return -2;
K
Karel Zak 已提交
1258 1259
}

E
Eric Blake 已提交
1260 1261
/**
 * vshCommandOptInt:
1262 1263 1264 1265 1266 1267 1268
 * @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 已提交
1269
 * 0 if option not found and not required (@value untouched)
1270
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
1271
 */
E
Eric Blake 已提交
1272
int
1273
vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
1274
{
E
Eric Blake 已提交
1275 1276
    vshCmdOpt *arg;
    int ret;
1277

E
Eric Blake 已提交
1278 1279 1280 1281 1282 1283 1284
    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;
1285
    }
E
Eric Blake 已提交
1286

E
Eric Blake 已提交
1287 1288 1289
    if (virStrToLong_i(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
K
Karel Zak 已提交
1290 1291
}

1292

E
Eric Blake 已提交
1293 1294 1295 1296 1297 1298
/**
 * vshCommandOptUInt:
 * @cmd command reference
 * @name option name
 * @value result
 *
1299 1300 1301
 * Convert option to unsigned int
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1302
int
1303 1304
vshCommandOptUInt(const vshCmd *cmd, const char *name, unsigned int *value)
{
E
Eric Blake 已提交
1305 1306
    vshCmdOpt *arg;
    int ret;
1307

E
Eric Blake 已提交
1308 1309 1310 1311 1312 1313 1314
    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;
1315
    }
E
Eric Blake 已提交
1316

E
Eric Blake 已提交
1317 1318 1319
    if (virStrToLong_ui(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1320 1321 1322
}


1323
/*
E
Eric Blake 已提交
1324 1325 1326 1327 1328
 * vshCommandOptUL:
 * @cmd command reference
 * @name option name
 * @value result
 *
1329 1330 1331
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1332
int
1333
vshCommandOptUL(const vshCmd *cmd, const char *name, unsigned long *value)
1334
{
E
Eric Blake 已提交
1335 1336
    vshCmdOpt *arg;
    int ret;
1337

E
Eric Blake 已提交
1338 1339 1340 1341 1342 1343 1344
    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;
1345
    }
E
Eric Blake 已提交
1346

E
Eric Blake 已提交
1347 1348 1349
    if (virStrToLong_ul(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1350 1351
}

E
Eric Blake 已提交
1352 1353 1354 1355 1356 1357
/**
 * vshCommandOptString:
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
1358
 * Returns option as STRING
E
Eric Blake 已提交
1359 1360 1361 1362
 * 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 已提交
1363
 */
E
Eric Blake 已提交
1364
int
1365
vshCommandOptString(const vshCmd *cmd, const char *name, const char **value)
1366
{
E
Eric Blake 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    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;
1377
    }
1378

E
Eric Blake 已提交
1379
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK)) {
E
Eric Blake 已提交
1380 1381 1382 1383
        return -1;
    }
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
1384 1385
}

E
Eric Blake 已提交
1386 1387 1388 1389 1390 1391
/**
 * vshCommandOptLongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
1392
 * Returns option as long long
1393
 * See vshCommandOptInt()
1394
 */
E
Eric Blake 已提交
1395
int
1396 1397
vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                      long long *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_ll(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1414 1415
}

E
Eric Blake 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424
/**
 * vshCommandOptULongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1425
int
1426 1427 1428
vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                       unsigned long long *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_ull(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1444 1445 1446
}


E
Eric Blake 已提交
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
/**
 * 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 已提交
1458
int
E
Eric Blake 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
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 已提交
1477 1478 1479 1480 1481 1482 1483 1484 1485
/**
 * 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 已提交
1486
 */
E
Eric Blake 已提交
1487
bool
1488
vshCommandOptBool(const vshCmd *cmd, const char *name)
1489
{
E
Eric Blake 已提交
1490 1491 1492
    vshCmdOpt *dummy;

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

E
Eric Blake 已提交
1495 1496 1497 1498 1499
/**
 * vshCommandOptArgv:
 * @cmd command reference
 * @opt starting point for the search
 *
1500 1501
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
1502
 *
1503
 * Requires that a VSH_OT_ARGV option be last in the
1504 1505
 * list of supported options in CMD->def->opts.
 */
E
Eric Blake 已提交
1506
const vshCmdOpt *
1507
vshCommandOptArgv(const vshCmd *cmd, const vshCmdOpt *opt)
1508
{
1509
    opt = opt ? opt->next : cmd->opts;
1510 1511

    while (opt) {
E
Eric Blake 已提交
1512
        if (opt->def->type == VSH_OT_ARGV) {
1513
            return opt;
1514 1515 1516 1517 1518 1519
        }
        opt = opt->next;
    }
    return NULL;
}

J
Jim Meyering 已提交
1520 1521 1522
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
1523 1524
bool
vshCmdHasOption(vshControl *ctl, const vshCmd *cmd, const char *optname)
J
Jim Meyering 已提交
1525 1526 1527 1528 1529 1530
{
    /* 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) {
1531
        if (STREQ(opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
J
Jim Meyering 已提交
1532 1533 1534 1535 1536 1537
            found = true;
            break;
        }
    }

    if (!found)
1538
        vshError(ctl, _("internal error: virsh %s: no %s VSH_OT_DATA option"),
J
Jim Meyering 已提交
1539 1540 1541
                 cmd->def->name, optname);
    return found;
}
1542

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
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 已提交
1560 1561 1562
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
1563
static bool
1564
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
1565
{
E
Eric Blake 已提交
1566
    bool ret = true;
1567 1568

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

1572 1573
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
1574 1575
            vshReconnect(ctl);

1576 1577 1578
        if (enable_timing)
            GETTIMEOFDAY(&before);

1579 1580 1581 1582 1583 1584 1585
        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;
        }
1586

1587 1588 1589
        if (enable_timing)
            GETTIMEOFDAY(&after);

1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
        /* 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++;

1600
        if (!ret)
E
Eric Blake 已提交
1601
            vshReportError(ctl);
J
John Levon 已提交
1602

1603
        if (!ret && disconnected != 0)
1604 1605
            vshReconnect(ctl);

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

E
Eric Blake 已提交
1609
        if (enable_timing) {
1610
            double diff_ms = (((after.tv_sec - before.tv_sec) * 1000.0) +
E
Eric Blake 已提交
1611 1612 1613 1614
                              ((after.tv_usec - before.tv_usec) / 1000.0));

            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"), diff_ms);
        } else {
K
Karel Zak 已提交
1615
            vshPrintExtra(ctl, "\n");
E
Eric Blake 已提交
1616
        }
K
Karel Zak 已提交
1617 1618 1619 1620 1621 1622
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
1623
 * Command parsing
K
Karel Zak 已提交
1624 1625 1626
 * ---------------
 */

1627 1628 1629 1630 1631 1632 1633
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 已提交
1634 1635 1636 1637
typedef struct _vshCommandParser vshCommandParser;
struct _vshCommandParser {
    vshCommandToken(*getNextArg)(vshControl *, vshCommandParser *,
                                 char **);
L
Lai Jiangshan 已提交
1638
    /* vshCommandStringGetArg() */
1639
    char *pos;
L
Lai Jiangshan 已提交
1640 1641 1642
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
E
Eric Blake 已提交
1643
};
1644

E
Eric Blake 已提交
1645
static bool
1646
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
1647
{
K
Karel Zak 已提交
1648 1649 1650
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
1651

K
Karel Zak 已提交
1652 1653 1654 1655
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
1656

1657
    while (1) {
K
Karel Zak 已提交
1658
        vshCmdOpt *last = NULL;
1659
        const vshCmdDef *cmd = NULL;
1660
        vshCommandToken tk;
L
Lai Jiangshan 已提交
1661
        bool data_only = false;
1662 1663 1664
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
1665

K
Karel Zak 已提交
1666
        first = NULL;
1667

1668
        while (1) {
1669
            const vshCmdOptDef *opt = NULL;
1670

K
Karel Zak 已提交
1671
            tkdata = NULL;
1672
            tk = parser->getNextArg(ctl, parser, &tkdata);
1673 1674

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1675
                goto syntaxError;
H
Hu Tao 已提交
1676 1677
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
1678
                break;
H
Hu Tao 已提交
1679
            }
1680 1681

            if (cmd == NULL) {
K
Karel Zak 已提交
1682 1683
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
1684
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
1685
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
1686
                }
1687 1688 1689 1690 1691 1692 1693
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
1694
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
1695 1696 1697 1698
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
1699
                char *optstr = strchr(tkdata + 2, '=');
C
Cole Robinson 已提交
1700
                int opt_index = 0;
1701

1702 1703 1704 1705
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
1706
                /* Special case 'help' to ignore all spurious options */
1707
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
1708
                                               &opts_seen, &opt_index))) {
1709
                    VIR_FREE(optstr);
1710 1711
                    if (STREQ(cmd->name, "help"))
                        continue;
K
Karel Zak 已提交
1712 1713
                    goto syntaxError;
                }
1714
                VIR_FREE(tkdata);
K
Karel Zak 已提交
1715 1716 1717

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
1718 1719 1720
                    if (optstr)
                        tkdata = optstr;
                    else
1721
                        tk = parser->getNextArg(ctl, parser, &tkdata);
1722
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1723
                        goto syntaxError;
1724
                    if (tk != VSH_TK_ARG) {
1725
                        vshError(ctl,
1726
                                 _("expected syntax: --%s <%s>"),
1727 1728
                                 opt->name,
                                 opt->type ==
1729
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
1730 1731
                        goto syntaxError;
                    }
1732 1733
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
1734 1735 1736 1737 1738 1739 1740 1741
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                opt->name);
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
1742
                }
L
Lai Jiangshan 已提交
1743 1744 1745 1746
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
1747
            } else {
L
Lai Jiangshan 已提交
1748
get_data:
1749
                /* Special case 'help' to ignore spurious data */
1750
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
1751 1752
                                             &opts_seen)) &&
                     STRNEQ(cmd->name, "help")) {
1753
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
1754 1755 1756 1757 1758
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
1759
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
1760

K
Karel Zak 已提交
1761 1762 1763 1764
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
1765

K
Karel Zak 已提交
1766 1767 1768 1769 1770
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
1771

1772
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
1773 1774
                         cmd->name,
                         opt->name,
1775 1776
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
1777 1778
            }
        }
1779

D
Daniel Veillard 已提交
1780
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
1781
        if (cmd) {
1782
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
            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;
            }
1802

K
Karel Zak 已提交
1803 1804 1805 1806
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

1807
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
1808
                VIR_FREE(c);
1809
                goto syntaxError;
1810
            }
1811

K
Karel Zak 已提交
1812 1813 1814 1815 1816 1817
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
1818 1819 1820

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
1821
    }
1822

E
Eric Blake 已提交
1823
    return true;
K
Karel Zak 已提交
1824

1825
 syntaxError:
1826
    if (ctl->cmd) {
K
Karel Zak 已提交
1827
        vshCommandFree(ctl->cmd);
1828 1829
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
1830 1831
    if (first)
        vshCommandOptFree(first);
1832
    VIR_FREE(tkdata);
E
Eric Blake 已提交
1833
    return false;
K
Karel Zak 已提交
1834 1835
}

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
/* --------------------
 * 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 已提交
1854 1855
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
1856 1857 1858 1859
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
1860
        return false;
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932

    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 已提交
1933 1934
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
1935 1936 1937 1938
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
1939
        return false;
1940 1941 1942 1943 1944 1945

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

K
Karel Zak 已提交
1946
/* ---------------
1947
 * Misc utils
K
Karel Zak 已提交
1948 1949
 * ---------------
 */
E
Eric Blake 已提交
1950
int
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
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;
}

1978 1979
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
E
Eric Blake 已提交
1980
char *
1981 1982 1983 1984 1985
vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
{
    int ret = 0;
    char *str = NULL;

1986
    switch (item->type) {
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
    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:
        ret = virAsprintf(&str, "%s", item->value.b ? _("yes") : _("no"));
        break;

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

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

2019
    if (ret < 0) {
2020
        vshError(ctl, "%s", _("Out of memory"));
2021 2022
        exit(EXIT_FAILURE);
    }
2023 2024 2025
    return str;
}

E
Eric Blake 已提交
2026
virTypedParameterPtr
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
vshFindTypedParamByName(const char *name, virTypedParameterPtr list, int count)
{
    int i = count;
    virTypedParameterPtr found = list;

    if (!list || !name)
        return NULL;

    while (i-- > 0) {
        if (STREQ(name, found->field))
            return found;

        found++; /* go to next struct in array */
    }

    /* not found */
    return NULL;
}

E
Eric Blake 已提交
2046
void
2047
vshDebug(vshControl *ctl, int level, const char *format, ...)
2048
{
K
Karel Zak 已提交
2049
    va_list ap;
2050
    char *str;
K
Karel Zak 已提交
2051

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

2059
    va_start(ap, format);
2060
    vshOutputLogFile(ctl, level, format, ap);
2061 2062
    va_end(ap);

K
Karel Zak 已提交
2063
    va_start(ap, format);
2064 2065 2066 2067 2068
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2069
    va_end(ap);
2070 2071
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
2072 2073
}

E
Eric Blake 已提交
2074
void
2075
vshPrintExtra(vshControl *ctl, const char *format, ...)
2076
{
K
Karel Zak 已提交
2077
    va_list ap;
2078
    char *str;
2079

2080
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
2081
        return;
2082

K
Karel Zak 已提交
2083
    va_start(ap, format);
2084 2085 2086 2087 2088
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2089
    va_end(ap);
2090
    fputs(str, stdout);
2091
    VIR_FREE(str);
K
Karel Zak 已提交
2092 2093
}

K
Karel Zak 已提交
2094

E
Eric Blake 已提交
2095
void
2096
vshError(vshControl *ctl, const char *format, ...)
2097
{
K
Karel Zak 已提交
2098
    va_list ap;
2099
    char *str;
2100

2101 2102 2103 2104 2105
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
2106

2107 2108 2109 2110
    /* 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);
2111
    fputs(_("error: "), stderr);
2112

K
Karel Zak 已提交
2113
    va_start(ap, format);
2114 2115 2116
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
2117 2118
    va_end(ap);

2119
    fprintf(stderr, "%s\n", NULLSTR(str));
2120
    fflush(stderr);
2121
    VIR_FREE(str);
K
Karel Zak 已提交
2122 2123
}

2124

J
Jiri Denemark 已提交
2125 2126 2127 2128 2129
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
E
Eric Blake 已提交
2140
            vshReportError(ctl);
J
Jiri Denemark 已提交
2141 2142 2143 2144
    }
}


K
Karel Zak 已提交
2145
/*
2146
 * Initialize connection.
K
Karel Zak 已提交
2147
 */
E
Eric Blake 已提交
2148
static bool
2149
vshInit(vshControl *ctl)
2150
{
2151 2152
    char *debugEnv;

K
Karel Zak 已提交
2153
    if (ctl->conn)
E
Eric Blake 已提交
2154
        return false;
K
Karel Zak 已提交
2155

J
Jiri Denemark 已提交
2156
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
2157 2158 2159
        /* log level not set from commandline, check env variable */
        debugEnv = getenv("VIRSH_DEBUG");
        if (debugEnv) {
J
Jiri Denemark 已提交
2160 2161 2162
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
2163 2164
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
2165 2166
            } else {
                ctl->debug = debug;
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
            }
        }
    }

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

2179 2180
    vshOpenLogFile(ctl);

2181 2182
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2183

2184
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
2185
        return false;
2186

J
Jiri Denemark 已提交
2187 2188 2189 2190
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

2191
    if (ctl->name) {
2192
        vshReconnect(ctl);
2193 2194 2195 2196 2197 2198 2199
        /* 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 已提交
2200
            vshReportError(ctl);
2201 2202
            return false;
        }
2203
    }
K
Karel Zak 已提交
2204

E
Eric Blake 已提交
2205
    return true;
K
Karel Zak 已提交
2206 2207
}

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

2210 2211 2212 2213 2214
/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
E
Eric Blake 已提交
2215
void
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
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:
2229
                vshError(ctl, "%s",
J
Jim Meyering 已提交
2230
                         _("failed to get the log file information"));
2231
                exit(EXIT_FAILURE);
2232 2233 2234
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
2235 2236
            vshError(ctl, "%s", _("the log path is not a file"));
            exit(EXIT_FAILURE);
2237 2238 2239 2240
        }
    }

    /* log file open */
2241
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
2242
        vshError(ctl, "%s",
J
Jim Meyering 已提交
2243
                 _("failed to open the log file. check the log file path"));
2244
        exit(EXIT_FAILURE);
2245 2246 2247 2248 2249 2250 2251 2252
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
E
Eric Blake 已提交
2253
void
2254 2255
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
2256
{
2257 2258 2259
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *str;
    size_t len;
2260
    const char *lvl = "";
2261
    time_t stTime;
2262
    struct tm stTm;
2263 2264 2265 2266 2267 2268 2269 2270 2271

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

    /**
     * create log format
     *
     * [YYYY.MM.DD HH:MM:SS SIGNATURE PID] LOG_LEVEL message
    */
2272 2273
    time(&stTime);
    localtime_r(&stTime, &stTm);
2274
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
2275 2276 2277 2278 2279 2280
                      (1900 + stTm.tm_year),
                      (1 + stTm.tm_mon),
                      stTm.tm_mday,
                      stTm.tm_hour,
                      stTm.tm_min,
                      stTm.tm_sec,
2281 2282
                      SIGN_NAME,
                      (int) getpid());
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
    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;
    }
2303 2304 2305
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
2306

2307 2308
    if (virBufferError(&buf))
        goto error;
2309

2310 2311 2312 2313 2314
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
2315
    }
2316

2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
    /* 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);
2328 2329 2330 2331 2332 2333 2334
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
E
Eric Blake 已提交
2335
void
2336 2337
vshCloseLogFile(vshControl *ctl)
{
2338 2339
    char ebuf[1024];

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

    if (ctl->logfile) {
2348
        VIR_FREE(ctl->logfile);
2349 2350 2351 2352
        ctl->logfile = NULL;
    }
}

2353
#ifdef USE_READLINE
2354

K
Karel Zak 已提交
2355 2356 2357 2358 2359
/* -----------------
 * Readline stuff
 * -----------------
 */

2360
/*
K
Karel Zak 已提交
2361 2362
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
2363
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
2364 2365
 */
static char *
2366 2367
vshReadlineCommandGenerator(const char *text, int state)
{
2368
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
2369
    const char *name;
2370 2371
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
2372 2373

    if (!state) {
2374 2375
        grp_list_index = 0;
        cmd_list_index = 0;
2376
        len = strlen(text);
K
Karel Zak 已提交
2377 2378
    }

2379 2380
    grp = cmdGroups;

K
Karel Zak 已提交
2381
    /* Return the next name which partially matches from the
2382
     * command list.
K
Karel Zak 已提交
2383
     */
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
    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 已提交
2398 2399 2400 2401 2402 2403 2404
    }

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

static char *
2405 2406
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2407
    static int list_index, len;
2408
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
2409
    const char *name;
K
Karel Zak 已提交
2410 2411 2412 2413 2414 2415 2416 2417 2418

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

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

2419
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
2420
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
2421 2422 2423

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
2424
        len = strlen(text);
2425
        VIR_FREE(cmdname);
K
Karel Zak 已提交
2426 2427 2428 2429
    }

    if (!cmd)
        return NULL;
2430

2431 2432 2433
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
2434
    while ((name = cmd->opts[list_index].name)) {
2435
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
2436
        char *res;
2437

K
Karel Zak 已提交
2438
        list_index++;
2439

2440
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
2441 2442
            /* ignore non --option */
            continue;
2443

K
Karel Zak 已提交
2444
        if (len > 2) {
2445
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
2446 2447
                continue;
        }
2448
        res = vshMalloc(NULL, strlen(name) + 3);
2449
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
2450 2451 2452 2453 2454 2455 2456 2457
        return res;
    }

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

static char **
2458 2459 2460
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2461 2462
    char **matches = (char **) NULL;

2463
    if (start == 0)
K
Karel Zak 已提交
2464
        /* command name generator */
2465
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
2466 2467
    else
        /* commands options */
2468
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
2469 2470 2471 2472
    return matches;
}


2473 2474
static int
vshReadlineInit(vshControl *ctl)
2475
{
2476 2477
    char *userdir = NULL;

K
Karel Zak 已提交
2478 2479 2480 2481 2482
    /* 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;
2483 2484 2485

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

2487
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
2488
    userdir = virGetUserCacheDirectory();
2489

2490 2491
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
2492
        return -1;
2493
    }
2494

2495
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
2496
        vshError(ctl, "%s", _("Out of memory"));
2497
        VIR_FREE(userdir);
2498 2499 2500 2501 2502
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
2503
        VIR_FREE(userdir);
2504 2505 2506
        return -1;
    }

2507
    VIR_FREE(userdir);
2508 2509 2510 2511 2512 2513 2514

    read_history(ctl->historyfile);

    return 0;
}

static void
2515
vshReadlineDeinit(vshControl *ctl)
2516 2517
{
    if (ctl->historyfile != NULL) {
2518 2519
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
2520 2521
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
2522
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
2523
        } else {
2524
            write_history(ctl->historyfile);
E
Eric Blake 已提交
2525
        }
2526 2527
    }

2528 2529
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
2530 2531
}

2532
static char *
2533
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
2534
{
2535
    return readline(prompt);
2536 2537
}

2538
#else /* !USE_READLINE */
2539

2540
static int
2541
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
2542 2543 2544 2545 2546
{
    /* empty */
    return 0;
}

2547
static void
2548
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
2549 2550 2551 2552 2553
{
    /* empty */
}

static char *
2554
vshReadline(vshControl *ctl, const char *prompt)
2555 2556 2557 2558 2559
{
    char line[1024];
    char *r;
    int len;

2560 2561
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
2562 2563 2564
    if (r == NULL) return NULL; /* EOF */

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

2569
    return vshStrdup(ctl, r);
2570 2571
}

2572
#endif /* !USE_READLINE */
2573

2574 2575 2576 2577 2578 2579
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
2580
/*
J
Jim Meyering 已提交
2581
 * Deinitialize virsh
K
Karel Zak 已提交
2582
 */
E
Eric Blake 已提交
2583
static bool
2584
vshDeinit(vshControl *ctl)
2585
{
2586
    vshReadlineDeinit(ctl);
2587
    vshCloseLogFile(ctl);
2588
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
2589
    if (ctl->conn) {
2590 2591 2592
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
K
Karel Zak 已提交
2593 2594
        }
    }
D
Daniel P. Berrange 已提交
2595 2596
    virResetLastError();

J
Jiri Denemark 已提交
2597
    if (ctl->eventLoopStarted) {
2598 2599 2600 2601
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
2602
        /* HACK: Add a dummy timeout to break event loop */
2603 2604 2605 2606 2607
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
2608 2609 2610 2611 2612 2613
        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

2614 2615
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
2616
    return true;
K
Karel Zak 已提交
2617
}
2618

K
Karel Zak 已提交
2619 2620 2621
/*
 * Print usage
 */
E
Eric Blake 已提交
2622
static void
2623
vshUsage(void)
2624
{
2625
    const vshCmdGrp *grp;
2626
    const vshCmdDef *cmd;
2627

L
Lai Jiangshan 已提交
2628 2629
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
2630
                      "  options:\n"
2631
                      "    -c | --connect=URI      hypervisor connection URI\n"
2632
                      "    -r | --readonly         connect readonly\n"
2633
                      "    -d | --debug=NUM        debug level [0-4]\n"
2634 2635 2636
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
2637 2638 2639 2640 2641
                      "    -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"
2642
                      "  commands (non interactive mode):\n\n"), progname, progname);
2643

2644
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
2645 2646 2647 2648 2649
        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;
2650
            fprintf(stdout,
E
Eric Blake 已提交
2651 2652 2653
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
2654 2655 2656 2657 2658
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
2659 2660 2661
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
2662 2663
}

2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
/*
 * 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 已提交
2674 2675
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
2676
#ifdef WITH_QEMU
2677
    vshPrint(ctl, " QEMU/KVM");
2678
#endif
D
Doug Goldstein 已提交
2679 2680 2681
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
2682 2683 2684
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
2685 2686 2687 2688 2689 2690
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
2691 2692 2693
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
2694 2695
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
2696
#endif
D
Doug Goldstein 已提交
2697 2698
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
2699
#endif
D
Doug Goldstein 已提交
2700 2701
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
2702 2703 2704 2705
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
2706 2707
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
2708
#endif
D
Doug Goldstein 已提交
2709 2710
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
2711 2712 2713 2714 2715 2716
#endif
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2717
    vshPrint(ctl, "%s", _(" Networking:"));
2718 2719 2720 2721 2722 2723 2724 2725 2726
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
2727
#if defined(WITH_INTERFACE)
D
Doug Goldstein 已提交
2728
    vshPrint(ctl, " Interface");
2729 2730
# if defined(WITH_NETCF)
    vshPrint(ctl, " netcf");
2731 2732
# elif defined(HAVE_UDEV)
    vshPrint(ctl, " udev");
2733
# endif
2734 2735 2736 2737 2738 2739 2740 2741 2742
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2743
    vshPrint(ctl, "%s", _(" Storage:"));
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
#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");
2764 2765 2766
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
2767 2768 2769
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
2770 2771 2772
#endif
    vshPrint(ctl, "\n");

2773
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
2774 2775 2776
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
#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 已提交
2818
static bool
2819 2820
vshParseArgv(vshControl *ctl, int argc, char **argv)
{
2821
    int arg, len, debug;
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
    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. */
    while ((arg = getopt_long(argc, argv, "+d:hqtc:vVrl:e:", opt, NULL)) != -1) {
        switch (arg) {
        case 'd':
2841
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
2842 2843 2844
                vshError(ctl, "%s", _("option -d takes a numeric argument"));
                exit(EXIT_FAILURE);
            }
2845 2846 2847 2848 2849
            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;
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919
            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;
        default:
            vshError(ctl, _("unsupported option '-%c'. See --help."), arg);
            exit(EXIT_FAILURE);
        }
    }

    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[] = {
    {"cd", cmdCd, opts_cd, info_cd, VSH_CMD_FLAG_NOCONNECT},
    {"echo", cmdEcho, opts_echo, info_echo, VSH_CMD_FLAG_NOCONNECT},
    {"exit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT},
    {"help", cmdHelp, opts_help, info_help, VSH_CMD_FLAG_NOCONNECT},
    {"pwd", cmdPwd, NULL, info_pwd, VSH_CMD_FLAG_NOCONNECT},
    {"quit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT},
    {NULL, NULL, NULL, NULL, 0}
};
2920

2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935
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 已提交
2936

2937 2938 2939 2940
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
2941
    char *defaultConn;
E
Eric Blake 已提交
2942
    bool ret = true;
K
Karel Zak 已提交
2943

2944 2945 2946
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
2947
    ctl->debug = VSH_DEBUG_DEFAULT;
E
Eric Blake 已提交
2948
    ctl->escapeChar = "^]";     /* Same default as telnet */
2949

2950

2951 2952
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
2953
        /* failure to setup locale is not fatal */
2954
    }
2955
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
2956
        perror("bindtextdomain");
E
Eric Blake 已提交
2957
        return EXIT_FAILURE;
2958
    }
2959
    if (!textdomain(PACKAGE)) {
2960
        perror("textdomain");
E
Eric Blake 已提交
2961
        return EXIT_FAILURE;
2962 2963
    }

2964 2965 2966 2967 2968
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

2969 2970 2971 2972 2973
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

2974
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
2975 2976 2977
        progname = argv[0];
    else
        progname++;
2978

2979
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
E
Eric Blake 已提交
2980
        ctl->name = vshStrdup(ctl, defaultConn);
2981 2982
    }

D
Daniel P. Berrange 已提交
2983 2984
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
2985
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
2986
    }
2987

D
Daniel P. Berrange 已提交
2988 2989
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
2990
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
2991
    }
2992

K
Karel Zak 已提交
2993
    if (!ctl->imode) {
2994
        ret = vshCommandRun(ctl, ctl->cmd);
2995
    } else {
K
Karel Zak 已提交
2996 2997
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
2998
            vshPrint(ctl,
2999
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
3000
                     progname);
J
Jim Meyering 已提交
3001
            vshPrint(ctl, "%s",
3002
                     _("Type:  'help' for help with commands\n"
3003
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
3004
        }
3005 3006 3007 3008 3009 3010

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

K
Karel Zak 已提交
3011
        do {
3012
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
3013
            ctl->cmdstr =
3014
                vshReadline(ctl, prompt);
3015 3016
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
3017
            if (*ctl->cmdstr) {
3018
#if USE_READLINE
K
Karel Zak 已提交
3019
                add_history(ctl->cmdstr);
3020
#endif
3021
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
3022 3023
                    vshCommandRun(ctl, ctl->cmd);
            }
3024
            VIR_FREE(ctl->cmdstr);
3025
        } while (ctl->imode);
K
Karel Zak 已提交
3026

3027 3028
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
3029
    }
3030

K
Karel Zak 已提交
3031 3032
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
3033
}