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

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

28
#include <stdio.h>
K
Karel Zak 已提交
29 30 31
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
32
#include <unistd.h>
33
#include <errno.h>
K
Karel Zak 已提交
34
#include <getopt.h>
K
Karel Zak 已提交
35
#include <sys/time.h>
J
Jim Meyering 已提交
36
#include "c-ctype.h"
37
#include <fcntl.h>
38
#include <locale.h>
39
#include <time.h>
40
#include <limits.h>
41
#include <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 "virerror.h"
58
#include "base64.h"
59
#include "virbuffer.h"
60
#include "console.h"
61
#include "virutil.h"
62
#include "viralloc.h"
63
#include "virxml.h"
64
#include "libvirt/libvirt-qemu.h"
65
#include "libvirt/libvirt-lxc.h"
E
Eric Blake 已提交
66
#include "virfile.h"
67
#include "configmake.h"
68
#include "virthread.h"
69
#include "vircommand.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 444 445 446 447 448 449 450
    {.name = "help",
     .data = N_("print help")
    },
    {.name = "desc",
     .data = N_("Prints global help, command specific help, or help for a\n"
                "    group of related commands")
    },
    {.name = NULL}
K
Karel Zak 已提交
451 452
};

453
static const vshCmdOptDef opts_help[] = {
454 455 456 457 458 459
    {.name = "command",
     .type = VSH_OT_DATA,
     .flags = 0,
     .help = N_("Prints global help, command specific help, or help for a group of related commands")
    },
    {.name = NULL}
K
Karel Zak 已提交
460 461
};

E
Eric Blake 已提交
462
static bool
463
cmdHelp(vshControl *ctl, const vshCmd *cmd)
464
 {
465
    const char *name = NULL;
466

467
    if (vshCommandOptString(cmd, "command", &name) <= 0) {
468
        const vshCmdGrp *grp;
469
        const vshCmdDef *def;
470

471 472 473 474 475 476
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

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

477 478 479
            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
480 481
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
482
            }
483 484 485 486

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
487
        return true;
488
    }
489

E
Eric Blake 已提交
490
    if (vshCmddefSearch(name)) {
491
        return vshCmddefHelp(ctl, name);
E
Eric Blake 已提交
492
    } else if (vshCmdGrpSearch(name)) {
493 494 495
        return vshCmdGrpHelp(ctl, name);
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
E
Eric Blake 已提交
496
        return false;
K
Karel Zak 已提交
497 498 499
    }
}

500 501 502 503 504 505 506 507 508 509 510
/* Tree listing helpers.  */

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

517
    if (virBufferError(indent))
518 519
        goto cleanup;

520 521 522 523 524 525 526 527 528 529
    /* 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;
530 531
    }

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

536 537 538
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
539

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

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

551 552 553 554 555
        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
556
    }
557 558
    if (virBufferTrim(indent, "  ", -1) < 0)
        goto cleanup;
559

560 561 562 563
    /* 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));
564

565 566 567 568
    if (!root) {
        if (virBufferTrim(indent, NULL, 2) < 0)
            goto cleanup;
    }
569
    ret = 0;
570 571 572 573
cleanup:
    return ret;
}

E
Eric Blake 已提交
574
int
575 576
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
577
{
578 579
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;
580

581 582 583 584 585
    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
586
    return ret;
587
}
588

589
/* Common code for the edit / net-edit / pool-edit functions which follow. */
E
Eric Blake 已提交
590
char *
E
Eric Blake 已提交
591
vshEditWriteToTempFile(vshControl *ctl, const char *doc)
592 593 594 595
{
    char *ret;
    const char *tmpdir;
    int fd;
596
    char ebuf[1024];
597

598
    tmpdir = getenv("TMPDIR");
599
    if (!tmpdir) tmpdir = "/tmp";
600 601 602 603
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
604
    fd = mkostemps(ret, 4, O_CLOEXEC);
605
    if (fd == -1) {
606
        vshError(ctl, _("mkostemps: failed to create temporary file: %s"),
607
                 virStrerror(errno, ebuf, sizeof(ebuf)));
608
        VIR_FREE(ret);
609 610 611
        return NULL;
    }

612
    if (safewrite(fd, doc, strlen(doc)) == -1) {
613
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
614
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
S
Stefan Berger 已提交
615
        VIR_FORCE_CLOSE(fd);
616
        unlink(ret);
617
        VIR_FREE(ret);
618 619
        return NULL;
    }
S
Stefan Berger 已提交
620
    if (VIR_CLOSE(fd) < 0) {
621
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
622
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
623
        unlink(ret);
624
        VIR_FREE(ret);
625 626 627 628 629 630 631 632 633 634 635
        return NULL;
    }

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

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

E
Eric Blake 已提交
636
int
E
Eric Blake 已提交
637
vshEditFile(vshControl *ctl, const char *filename)
638 639
{
    const char *editor;
E
Eric Blake 已提交
640 641 642 643
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;
644

645
    editor = getenv("VISUAL");
E
Eric Blake 已提交
646
    if (!editor)
647
        editor = getenv("EDITOR");
E
Eric Blake 已提交
648 649
    if (!editor)
        editor = "vi"; /* could be cruel & default to ed(1) here */
650

651 652 653 654 655
    /* 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 已提交
656 657
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
658
     */
659 660
    if (strspn(editor, ACCEPTED_CHARS) != strlen(editor)) {
        if (strspn(filename, ACCEPTED_CHARS) != strlen(filename)) {
E
Eric Blake 已提交
661 662 663 664 665 666 667 668 669 670
            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);
671 672
    }

E
Eric Blake 已提交
673 674 675 676 677
    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
E
Eric Blake 已提交
678
        vshReportError(ctl);
E
Eric Blake 已提交
679
        goto cleanup;
680
    }
E
Eric Blake 已提交
681
    ret = 0;
682

E
Eric Blake 已提交
683 684 685
cleanup:
    virCommandFree(cmd);
    return ret;
686 687
}

E
Eric Blake 已提交
688
char *
E
Eric Blake 已提交
689
vshEditReadBackFile(vshControl *ctl, const char *filename)
690 691
{
    char *ret;
692
    char ebuf[1024];
693

E
Eric Blake 已提交
694
    if (virFileReadAll(filename, VSH_MAX_XML_FILE, &ret) == -1) {
695
        vshError(ctl,
696
                 _("%s: failed to read temporary file: %s"),
697
                 filename, virStrerror(errno, ebuf, sizeof(ebuf)));
698 699 700 701 702
        return NULL;
    }
    return ret;
}

703

P
Paolo Bonzini 已提交
704 705 706 707
/*
 * "cd" command
 */
static const vshCmdInfo info_cd[] = {
708 709 710 711 712 713 714
    {.name = "help",
     .data = N_("change the current directory")
    },
    {.name = "desc",
     .data = N_("Change the current directory.")
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
715 716 717
};

static const vshCmdOptDef opts_cd[] = {
718 719 720 721 722 723
    {.name = "dir",
     .type = VSH_OT_DATA,
     .flags = 0,
     .help = N_("directory to switch to (default: home or else root)")
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
724 725
};

E
Eric Blake 已提交
726
static bool
727
cmdCd(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
728
{
729
    const char *dir = NULL;
730
    char *dir_malloced = NULL;
E
Eric Blake 已提交
731
    bool ret = true;
732
    char ebuf[1024];
P
Paolo Bonzini 已提交
733 734

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

739
    if (vshCommandOptString(cmd, "dir", &dir) <= 0) {
740
        dir = dir_malloced = virGetUserDirectory();
P
Paolo Bonzini 已提交
741 742 743 744
    }
    if (!dir)
        dir = "/";

P
Phil Petty 已提交
745
    if (chdir(dir) == -1) {
746 747
        vshError(ctl, _("cd: %s: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)), dir);
E
Eric Blake 已提交
748
        ret = false;
P
Paolo Bonzini 已提交
749 750
    }

751
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
752
    return ret;
P
Paolo Bonzini 已提交
753 754 755 756 757 758
}

/*
 * "pwd" command
 */
static const vshCmdInfo info_pwd[] = {
759 760 761 762 763 764 765
    {.name = "help",
     .data = N_("print the current directory")
    },
    {.name = "desc",
     .data = N_("Print the current directory.")
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
766 767
};

E
Eric Blake 已提交
768
static bool
P
Paolo Bonzini 已提交
769 770 771
cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cwd;
772
    bool ret = true;
773
    char ebuf[1024];
P
Paolo Bonzini 已提交
774

775 776
    cwd = getcwd(NULL, 0);
    if (!cwd) {
777
        vshError(ctl, _("pwd: cannot get current directory: %s"),
778
                 virStrerror(errno, ebuf, sizeof(ebuf)));
779 780
        ret = false;
    } else {
781
        vshPrint(ctl, _("%s\n"), cwd);
782 783
        VIR_FREE(cwd);
    }
P
Paolo Bonzini 已提交
784

785
    return ret;
P
Paolo Bonzini 已提交
786 787
}

E
Eric Blake 已提交
788 789 790 791
/*
 * "echo" command
 */
static const vshCmdInfo info_echo[] = {
792 793 794 795 796 797 798
    {.name = "help",
     .data = N_("echo arguments")
    },
    {.name = "desc",
     .data = N_("Echo back arguments, possibly with quoting.")
    },
    {.name = NULL}
E
Eric Blake 已提交
799 800 801
};

static const vshCmdOptDef opts_echo[] = {
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    {.name = "shell",
     .type = VSH_OT_BOOL,
     .flags = 0,
     .help = N_("escape for shell use")
    },
    {.name = "xml",
     .type = VSH_OT_BOOL,
     .flags = 0,
     .help = N_("escape for XML use")
    },
    {.name = "str",
     .type = VSH_OT_ALIAS,
     .flags = 0,
     .help = "string"
    },
    {.name = "string",
     .type = VSH_OT_ARGV,
     .flags = 0,
     .help = N_("arguments to echo")
    },
    {.name = NULL}
E
Eric Blake 已提交
823 824 825 826 827
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
E
Eric Blake 已提交
828
static bool
829
cmdEcho(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
830 831 832 833
{
    bool shell = false;
    bool xml = false;
    int count = 0;
834
    const vshCmdOpt *opt = NULL;
E
Eric Blake 已提交
835 836 837 838 839 840 841 842
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

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

843
    while ((opt = vshCommandOptArgv(cmd, opt))) {
844 845
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
846

847
        arg = opt->data;
848

E
Eric Blake 已提交
849 850
        if (count)
            virBufferAddChar(&buf, ' ');
851

E
Eric Blake 已提交
852
        if (xml) {
853 854 855 856
            virBufferEscapeString(&xmlbuf, "%s", arg);
            if (virBufferError(&buf)) {
                vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
                return false;
E
Eric Blake 已提交
857
            }
858 859 860
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
E
Eric Blake 已提交
861
        }
862 863 864 865 866

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
E
Eric Blake 已提交
867
        count++;
868
        VIR_FREE(str);
E
Eric Blake 已提交
869 870 871 872
    }

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
873
        return false;
E
Eric Blake 已提交
874 875 876 877 878
    }
    arg = virBufferContentAndReset(&buf);
    if (arg)
        vshPrint(ctl, "%s", arg);
    VIR_FREE(arg);
E
Eric Blake 已提交
879
    return true;
E
Eric Blake 已提交
880 881
}

K
Karel Zak 已提交
882 883 884
/*
 * "quit" command
 */
885
static const vshCmdInfo info_quit[] = {
886 887 888 889 890 891 892
    {.name = "help",
     .data = N_("quit this interactive terminal")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
K
Karel Zak 已提交
893 894
};

E
Eric Blake 已提交
895
static bool
896
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
897
{
E
Eric Blake 已提交
898 899
    ctl->imode = false;
    return true;
K
Karel Zak 已提交
900 901
}

902 903 904 905
/* ---------------
 * Utils for work with command definition
 * ---------------
 */
E
Eric Blake 已提交
906
const char *
907 908 909
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
{
    const vshCmdInfo *info;
910

911 912 913 914 915 916
    for (info = cmd->info; info && info->name; info++) {
        if (STREQ(info->name, name))
            return info->data;
    }
    return NULL;
}
917

918 919 920 921 922 923 924
/* 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;
925

926 927
    *opts_need_arg = 0;
    *opts_required = 0;
928

929 930
    if (!cmd->opts)
        return 0;
931

932 933
    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
934 935 936 937

        if (i > 31)
            return -1; /* too many options */
        if (opt->type == VSH_OT_BOOL) {
E
Eric Blake 已提交
938
            if (opt->flags & VSH_OFLAG_REQ)
939 940 941
                return -1; /* bool options can't be mandatory */
            continue;
        }
E
Eric Blake 已提交
942 943 944 945 946 947 948 949 950 951 952 953
        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 已提交
954 955
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
L
Lai Jiangshan 已提交
956 957 958 959
                *opts_required |= 1 << i;
            continue;
        }

960
        *opts_need_arg |= 1 << i;
E
Eric Blake 已提交
961
        if (opt->flags & VSH_OFLAG_REQ) {
962 963 964 965 966 967
            if (optional)
                return -1; /* mandatory options must be listed first */
            *opts_required |= 1 << i;
        } else {
            optional = true;
        }
968 969 970

        if (opt->type == VSH_OT_ARGV && cmd->opts[i + 1].name)
            return -1; /* argv option must be listed last */
971 972 973 974
    }
    return 0;
}

975 976 977 978 979 980
static vshCmdOptDef helpopt = {
    .name = "help",
    .type = VSH_OT_BOOL,
    .flags = 0,
    .help = N_("print help for this function")
};
981
static const vshCmdOptDef *
982
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
983
                   uint32_t *opts_seen, int *opt_index)
984
{
985 986
    int i;

987 988 989 990
    if (STREQ(name, helpopt.name)) {
        return &helpopt;
    }

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

994
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
995 996 997 998
            if (opt->type == VSH_OT_ALIAS) {
                name = opt->help;
                continue;
            }
999
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
1000 1001 1002
                vshError(ctl, _("option --%s already seen"), name);
                return NULL;
            }
1003 1004
            *opts_seen |= 1 << i;
            *opt_index = i;
K
Karel Zak 已提交
1005
            return opt;
1006 1007 1008
        }
    }

1009 1010 1011 1012
    if (STRNEQ(cmd->name, "help")) {
        vshError(ctl, _("command '%s' doesn't support option --%s"),
                 cmd->name, name);
    }
K
Karel Zak 已提交
1013 1014 1015
    return NULL;
}

1016
static const vshCmdOptDef *
1017 1018
vshCmddefGetData(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                 uint32_t *opts_seen)
1019
{
1020
    int i;
1021
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
1022

1023 1024 1025 1026
    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
E
Eric Blake 已提交
1027
    i = ffs(*opts_need_arg) - 1;
1028
    opt = &cmd->opts[i];
1029
    if (opt->type != VSH_OT_ARGV)
1030
        *opts_need_arg &= ~(1 << i);
1031
    *opts_seen |= 1 << i;
1032
    return opt;
K
Karel Zak 已提交
1033 1034
}

1035 1036 1037
/*
 * Checks for required options
 */
1038
static int
1039 1040
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint32_t opts_required,
                    uint32_t opts_seen)
1041
{
1042
    const vshCmdDef *def = cmd->def;
1043 1044 1045 1046 1047 1048 1049 1050 1051
    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];
1052

1053
            vshError(ctl,
1054
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
1055 1056 1057
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
1058 1059
        }
    }
1060
    return -1;
1061 1062
}

E
Eric Blake 已提交
1063
const vshCmdDef *
1064 1065
vshCmddefSearch(const char *cmdname)
{
1066
    const vshCmdGrp *g;
1067
    const vshCmdDef *c;
1068

1069 1070
    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
1071
            if (STREQ(c->name, cmdname))
1072 1073 1074 1075
                return c;
        }
    }

K
Karel Zak 已提交
1076 1077 1078
    return NULL;
}

E
Eric Blake 已提交
1079
const vshCmdGrp *
1080 1081 1082 1083 1084
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
1085
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
1086 1087 1088 1089 1090 1091
            return g;
    }

    return NULL;
}

E
Eric Blake 已提交
1092
bool
1093 1094 1095 1096 1097 1098 1099
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 已提交
1100
        return false;
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
    } 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 已提交
1111
    return true;
1112 1113
}

E
Eric Blake 已提交
1114
bool
1115
vshCmddefHelp(vshControl *ctl, const char *cmdname)
1116
{
1117
    const vshCmdDef *def = vshCmddefSearch(cmdname);
1118

K
Karel Zak 已提交
1119
    if (!def) {
1120
        vshError(ctl, _("command '%s' doesn't exist"), cmdname);
E
Eric Blake 已提交
1121
        return false;
1122
    } else {
E
Eric Blake 已提交
1123 1124
        /* Don't translate desc if it is "".  */
        const char *desc = vshCmddefGetInfo(def, "desc");
E
Eric Blake 已提交
1125
        const char *help = _(vshCmddefGetInfo(def, "help"));
1126
        char buf[256];
1127 1128
        uint32_t opts_need_arg;
        uint32_t opts_required;
1129
        bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
1130 1131 1132 1133

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

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

1140 1141 1142 1143 1144
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
1145
                const char *fmt = "%s";
1146 1147
                switch (opt->type) {
                case VSH_OT_BOOL:
1148
                    fmt = "[--%s]";
1149 1150
                    break;
                case VSH_OT_INT:
E
Eric Blake 已提交
1151
                    /* xgettext:c-format */
E
Eric Blake 已提交
1152
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
1153
                           : _("[--%s <number>]"));
1154 1155
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1156 1157
                    break;
                case VSH_OT_STRING:
E
Eric Blake 已提交
1158 1159
                    /* xgettext:c-format */
                    fmt = _("[--%s <string>]");
1160 1161
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1162 1163
                    break;
                case VSH_OT_DATA:
E
Eric Blake 已提交
1164
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
1165 1166
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1167 1168 1169
                    break;
                case VSH_OT_ARGV:
                    /* xgettext:c-format */
1170 1171 1172 1173 1174 1175 1176 1177
                    if (shortopt) {
                        fmt = (opt->flags & VSH_OFLAG_REQ)
                            ? _("{[--%s] <string>}...")
                            : _("[[--%s] <string>]...");
                    } else {
                        fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                            : _("[<%s>]...");
                    }
1178
                    break;
E
Eric Blake 已提交
1179 1180 1181
                case VSH_OT_ALIAS:
                    /* aliases are intentionally undocumented */
                    continue;
1182
                default:
1183
                    assert(0);
1184
                }
1185
                fputc(' ', stdout);
E
Eric Blake 已提交
1186
                fprintf(stdout, fmt, opt->name);
1187
            }
K
Karel Zak 已提交
1188
        }
1189 1190 1191
        fputc('\n', stdout);

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

K
Karel Zak 已提交
1197
        if (def->opts) {
1198
            const vshCmdOptDef *opt;
1199
            fputs(_("\n  OPTIONS\n"), stdout);
1200
            for (opt = def->opts; opt->name; opt++) {
1201 1202
                switch (opt->type) {
                case VSH_OT_BOOL:
K
Karel Zak 已提交
1203
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1204 1205
                    break;
                case VSH_OT_INT:
1206
                    snprintf(buf, sizeof(buf),
E
Eric Blake 已提交
1207
                             (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
1208
                             : _("--%s <number>"), opt->name);
1209 1210
                    break;
                case VSH_OT_STRING:
1211
                    /* OT_STRING should never be VSH_OFLAG_REQ */
1212
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
1213 1214
                    break;
                case VSH_OT_DATA:
1215 1216
                    snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                             opt->name);
1217 1218
                    break;
                case VSH_OT_ARGV:
1219 1220 1221
                    snprintf(buf, sizeof(buf),
                             shortopt ? _("[--%s] <string>") : _("<%s>"),
                             opt->name);
1222
                    break;
E
Eric Blake 已提交
1223 1224
                case VSH_OT_ALIAS:
                    continue;
1225 1226 1227
                default:
                    assert(0);
                }
1228

E
Eric Blake 已提交
1229
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
1230
            }
K
Karel Zak 已提交
1231 1232 1233
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
1234
    return true;
K
Karel Zak 已提交
1235 1236 1237 1238 1239 1240
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1241 1242 1243
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1244 1245
    vshCmdOpt *a = arg;

1246
    while (a) {
K
Karel Zak 已提交
1247
        vshCmdOpt *tmp = a;
1248

K
Karel Zak 已提交
1249 1250
        a = a->next;

1251 1252
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
1253 1254 1255 1256
    }
}

static void
1257
vshCommandFree(vshCmd *cmd)
1258
{
K
Karel Zak 已提交
1259 1260
    vshCmd *c = cmd;

1261
    while (c) {
K
Karel Zak 已提交
1262
        vshCmd *tmp = c;
1263

K
Karel Zak 已提交
1264 1265 1266 1267
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
1268
        VIR_FREE(tmp);
K
Karel Zak 已提交
1269 1270 1271
    }
}

E
Eric Blake 已提交
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
/**
 * 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 已提交
1283
 */
E
Eric Blake 已提交
1284
int
E
Eric Blake 已提交
1285
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
1286
{
E
Eric Blake 已提交
1287 1288
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
1289

E
Eric Blake 已提交
1290 1291 1292 1293 1294 1295 1296
    /* 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 已提交
1297
    }
E
Eric Blake 已提交
1298 1299 1300 1301 1302 1303 1304

    /* Option not present, see if command requires it.  */
    *opt = NULL;
    while (valid) {
        if (!valid->name)
            break;
        if (STREQ(name, valid->name))
E
Eric Blake 已提交
1305
            return (valid->flags & VSH_OFLAG_REQ) == 0 ? 0 : -1;
E
Eric Blake 已提交
1306 1307 1308 1309
        valid++;
    }
    /* If we got here, the name is unknown.  */
    return -2;
K
Karel Zak 已提交
1310 1311
}

E
Eric Blake 已提交
1312 1313
/**
 * vshCommandOptInt:
1314 1315 1316 1317 1318 1319 1320
 * @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 已提交
1321
 * 0 if option not found and not required (@value untouched)
1322
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
1323
 */
E
Eric Blake 已提交
1324
int
1325
vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
1326
{
E
Eric Blake 已提交
1327 1328
    vshCmdOpt *arg;
    int ret;
1329

E
Eric Blake 已提交
1330 1331 1332 1333 1334 1335 1336
    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;
1337
    }
E
Eric Blake 已提交
1338

E
Eric Blake 已提交
1339 1340 1341
    if (virStrToLong_i(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
K
Karel Zak 已提交
1342 1343
}

1344

E
Eric Blake 已提交
1345 1346 1347 1348 1349 1350
/**
 * vshCommandOptUInt:
 * @cmd command reference
 * @name option name
 * @value result
 *
1351 1352 1353
 * Convert option to unsigned int
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1354
int
1355 1356
vshCommandOptUInt(const vshCmd *cmd, const char *name, unsigned int *value)
{
E
Eric Blake 已提交
1357 1358
    vshCmdOpt *arg;
    int ret;
1359

E
Eric Blake 已提交
1360 1361 1362 1363 1364 1365 1366
    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;
1367
    }
E
Eric Blake 已提交
1368

E
Eric Blake 已提交
1369 1370 1371
    if (virStrToLong_ui(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1372 1373 1374
}


1375
/*
E
Eric Blake 已提交
1376 1377 1378 1379 1380
 * vshCommandOptUL:
 * @cmd command reference
 * @name option name
 * @value result
 *
1381 1382 1383
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1384
int
1385
vshCommandOptUL(const vshCmd *cmd, const char *name, unsigned long *value)
1386
{
E
Eric Blake 已提交
1387 1388
    vshCmdOpt *arg;
    int ret;
1389

E
Eric Blake 已提交
1390 1391 1392 1393 1394 1395 1396
    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;
1397
    }
E
Eric Blake 已提交
1398

E
Eric Blake 已提交
1399 1400 1401
    if (virStrToLong_ul(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1402 1403
}

E
Eric Blake 已提交
1404 1405 1406 1407 1408 1409
/**
 * vshCommandOptString:
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
1410
 * Returns option as STRING
E
Eric Blake 已提交
1411 1412 1413 1414
 * 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 已提交
1415
 */
E
Eric Blake 已提交
1416
int
1417
vshCommandOptString(const vshCmd *cmd, const char *name, const char **value)
1418
{
E
Eric Blake 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
    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;
1429
    }
1430

E
Eric Blake 已提交
1431
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK)) {
E
Eric Blake 已提交
1432 1433 1434 1435
        return -1;
    }
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
1436 1437
}

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
/**
 * vshCommandOptStringReq:
 * @ctl virsh control structure
 * @cmd command structure
 * @name option name
 * @value result (updated to NULL or the option argument)
 *
 * Gets a option argument as string.
 *
 * Returns 0 on success or when the option is not present and not
 * required, *value is set to the option argument. On error -1 is
 * returned and error message printed.
 */
int
vshCommandOptStringReq(vshControl *ctl,
                       const vshCmd *cmd,
                       const char *name,
                       const char **value)
{
    vshCmdOpt *arg;
    int ret;
    const char *error = NULL;

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

    ret = vshCommandOpt(cmd, name, &arg);
    /* option is not required and not present */
    if (ret == 0)
        return 0;
    /* this should not be propagated here, just to be sure */
    if (ret == -1)
        error = N_("Mandatory option not present");

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

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

1478
    if (arg->data && !*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK))
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
        error = N_("Option argument is empty");

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

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

E
Eric Blake 已提交
1490 1491 1492 1493 1494 1495
/**
 * vshCommandOptLongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
1496
 * Returns option as long long
1497
 * See vshCommandOptInt()
1498
 */
E
Eric Blake 已提交
1499
int
1500 1501
vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                      long long *value)
1502
{
E
Eric Blake 已提交
1503 1504
    vshCmdOpt *arg;
    int ret;
1505

E
Eric Blake 已提交
1506 1507 1508 1509 1510 1511 1512
    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;
1513
    }
E
Eric Blake 已提交
1514

E
Eric Blake 已提交
1515 1516 1517
    if (virStrToLong_ll(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1518 1519
}

E
Eric Blake 已提交
1520 1521 1522 1523 1524 1525 1526 1527 1528
/**
 * vshCommandOptULongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1529
int
1530 1531 1532
vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                       unsigned long long *value)
{
E
Eric Blake 已提交
1533 1534
    vshCmdOpt *arg;
    int ret;
1535

E
Eric Blake 已提交
1536 1537 1538 1539 1540 1541 1542
    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;
1543
    }
E
Eric Blake 已提交
1544

E
Eric Blake 已提交
1545 1546 1547
    if (virStrToLong_ull(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1548 1549 1550
}


E
Eric Blake 已提交
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
/**
 * 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 已提交
1562
int
E
Eric Blake 已提交
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
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 已提交
1581 1582 1583 1584 1585 1586 1587 1588 1589
/**
 * 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 已提交
1590
 */
E
Eric Blake 已提交
1591
bool
1592
vshCommandOptBool(const vshCmd *cmd, const char *name)
1593
{
E
Eric Blake 已提交
1594 1595 1596
    vshCmdOpt *dummy;

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

E
Eric Blake 已提交
1599 1600 1601 1602 1603
/**
 * vshCommandOptArgv:
 * @cmd command reference
 * @opt starting point for the search
 *
1604 1605
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
1606
 *
1607
 * Requires that a VSH_OT_ARGV option be last in the
1608 1609
 * list of supported options in CMD->def->opts.
 */
E
Eric Blake 已提交
1610
const vshCmdOpt *
1611
vshCommandOptArgv(const vshCmd *cmd, const vshCmdOpt *opt)
1612
{
1613
    opt = opt ? opt->next : cmd->opts;
1614 1615

    while (opt) {
E
Eric Blake 已提交
1616
        if (opt->def->type == VSH_OT_ARGV) {
1617
            return opt;
1618 1619 1620 1621 1622 1623
        }
        opt = opt->next;
    }
    return NULL;
}

J
Jim Meyering 已提交
1624 1625 1626
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
1627 1628
bool
vshCmdHasOption(vshControl *ctl, const vshCmd *cmd, const char *optname)
J
Jim Meyering 已提交
1629 1630 1631 1632 1633 1634
{
    /* 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) {
1635
        if (STREQ(opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
J
Jim Meyering 已提交
1636 1637 1638 1639 1640 1641
            found = true;
            break;
        }
    }

    if (!found)
1642
        vshError(ctl, _("internal error: virsh %s: no %s VSH_OT_DATA option"),
J
Jim Meyering 已提交
1643 1644 1645
                 cmd->def->name, optname);
    return found;
}
1646

1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
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 已提交
1664 1665 1666
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
1667
static bool
1668
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
1669
{
E
Eric Blake 已提交
1670
    bool ret = true;
1671 1672

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

1676 1677
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
1678 1679
            vshReconnect(ctl);

1680 1681 1682
        if (enable_timing)
            GETTIMEOFDAY(&before);

1683 1684 1685 1686 1687 1688 1689
        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;
        }
1690

1691 1692 1693
        if (enable_timing)
            GETTIMEOFDAY(&after);

1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
        /* 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++;

1704
        if (!ret)
E
Eric Blake 已提交
1705
            vshReportError(ctl);
J
John Levon 已提交
1706

1707
        if (!ret && disconnected != 0)
1708 1709
            vshReconnect(ctl);

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

E
Eric Blake 已提交
1713
        if (enable_timing) {
1714
            double diff_ms = (((after.tv_sec - before.tv_sec) * 1000.0) +
E
Eric Blake 已提交
1715 1716 1717 1718
                              ((after.tv_usec - before.tv_usec) / 1000.0));

            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"), diff_ms);
        } else {
K
Karel Zak 已提交
1719
            vshPrintExtra(ctl, "\n");
E
Eric Blake 已提交
1720
        }
K
Karel Zak 已提交
1721 1722 1723 1724 1725 1726
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
1727
 * Command parsing
K
Karel Zak 已提交
1728 1729 1730
 * ---------------
 */

1731 1732 1733 1734 1735 1736 1737
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 已提交
1738 1739 1740 1741
typedef struct _vshCommandParser vshCommandParser;
struct _vshCommandParser {
    vshCommandToken(*getNextArg)(vshControl *, vshCommandParser *,
                                 char **);
L
Lai Jiangshan 已提交
1742
    /* vshCommandStringGetArg() */
1743
    char *pos;
L
Lai Jiangshan 已提交
1744 1745 1746
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
E
Eric Blake 已提交
1747
};
1748

E
Eric Blake 已提交
1749
static bool
1750
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
1751
{
K
Karel Zak 已提交
1752 1753 1754
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
1755

K
Karel Zak 已提交
1756 1757 1758 1759
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
1760

1761
    while (1) {
K
Karel Zak 已提交
1762
        vshCmdOpt *last = NULL;
1763
        const vshCmdDef *cmd = NULL;
1764
        vshCommandToken tk;
L
Lai Jiangshan 已提交
1765
        bool data_only = false;
1766 1767 1768
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
1769

K
Karel Zak 已提交
1770
        first = NULL;
1771

1772
        while (1) {
1773
            const vshCmdOptDef *opt = NULL;
1774

K
Karel Zak 已提交
1775
            tkdata = NULL;
1776
            tk = parser->getNextArg(ctl, parser, &tkdata);
1777 1778

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1779
                goto syntaxError;
H
Hu Tao 已提交
1780 1781
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
1782
                break;
H
Hu Tao 已提交
1783
            }
1784 1785

            if (cmd == NULL) {
K
Karel Zak 已提交
1786 1787
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
1788
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
1789
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
1790
                }
1791 1792 1793 1794 1795 1796 1797
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
1798
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
1799 1800 1801 1802
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
1803
                char *optstr = strchr(tkdata + 2, '=');
C
Cole Robinson 已提交
1804
                int opt_index = 0;
1805

1806 1807 1808 1809
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
1810
                /* Special case 'help' to ignore all spurious options */
1811
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
1812
                                               &opts_seen, &opt_index))) {
1813
                    VIR_FREE(optstr);
1814 1815
                    if (STREQ(cmd->name, "help"))
                        continue;
K
Karel Zak 已提交
1816 1817
                    goto syntaxError;
                }
1818
                VIR_FREE(tkdata);
K
Karel Zak 已提交
1819 1820 1821

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
1822 1823 1824
                    if (optstr)
                        tkdata = optstr;
                    else
1825
                        tk = parser->getNextArg(ctl, parser, &tkdata);
1826
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1827
                        goto syntaxError;
1828
                    if (tk != VSH_TK_ARG) {
1829
                        vshError(ctl,
1830
                                 _("expected syntax: --%s <%s>"),
1831 1832
                                 opt->name,
                                 opt->type ==
1833
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
1834 1835
                        goto syntaxError;
                    }
1836 1837
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
1838 1839 1840 1841 1842 1843 1844 1845
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                opt->name);
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
1846
                }
L
Lai Jiangshan 已提交
1847 1848 1849 1850
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
1851
            } else {
L
Lai Jiangshan 已提交
1852
get_data:
1853
                /* Special case 'help' to ignore spurious data */
1854
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
1855 1856
                                             &opts_seen)) &&
                     STRNEQ(cmd->name, "help")) {
1857
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
1858 1859 1860 1861 1862
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
1863
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
1864

K
Karel Zak 已提交
1865 1866 1867 1868
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
1869

K
Karel Zak 已提交
1870 1871 1872 1873 1874
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
1875

1876
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
1877 1878
                         cmd->name,
                         opt->name,
1879 1880
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
1881 1882
            }
        }
1883

D
Daniel Veillard 已提交
1884
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
1885
        if (cmd) {
1886
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
            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;
            }
1906

K
Karel Zak 已提交
1907 1908 1909 1910
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

1911
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
1912
                VIR_FREE(c);
1913
                goto syntaxError;
1914
            }
1915

K
Karel Zak 已提交
1916 1917 1918 1919 1920 1921
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
1922 1923 1924

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
1925
    }
1926

E
Eric Blake 已提交
1927
    return true;
K
Karel Zak 已提交
1928

1929
 syntaxError:
1930
    if (ctl->cmd) {
K
Karel Zak 已提交
1931
        vshCommandFree(ctl->cmd);
1932 1933
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
1934 1935
    if (first)
        vshCommandOptFree(first);
1936
    VIR_FREE(tkdata);
E
Eric Blake 已提交
1937
    return false;
K
Karel Zak 已提交
1938 1939
}

1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
/* --------------------
 * 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 已提交
1958 1959
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
1960 1961 1962 1963
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
1964
        return false;
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036

    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 已提交
2037 2038
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
2039 2040 2041 2042
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
2043
        return false;
2044 2045 2046 2047 2048 2049

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

K
Karel Zak 已提交
2050
/* ---------------
2051
 * Misc utils
K
Karel Zak 已提交
2052 2053
 * ---------------
 */
E
Eric Blake 已提交
2054
int
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
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;
}

2082 2083
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
E
Eric Blake 已提交
2084
char *
2085 2086 2087 2088 2089
vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
{
    int ret = 0;
    char *str = NULL;

2090
    switch (item->type) {
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
    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;

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

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

2123
    if (ret < 0) {
2124
        vshError(ctl, "%s", _("Out of memory"));
2125 2126
        exit(EXIT_FAILURE);
    }
2127 2128 2129
    return str;
}

E
Eric Blake 已提交
2130
void
2131
vshDebug(vshControl *ctl, int level, const char *format, ...)
2132
{
K
Karel Zak 已提交
2133
    va_list ap;
2134
    char *str;
K
Karel Zak 已提交
2135

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

2143
    va_start(ap, format);
2144
    vshOutputLogFile(ctl, level, format, ap);
2145 2146
    va_end(ap);

K
Karel Zak 已提交
2147
    va_start(ap, format);
2148 2149 2150 2151 2152
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2153
    va_end(ap);
2154 2155
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
2156 2157
}

E
Eric Blake 已提交
2158
void
2159
vshPrintExtra(vshControl *ctl, const char *format, ...)
2160
{
K
Karel Zak 已提交
2161
    va_list ap;
2162
    char *str;
2163

2164
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
2165
        return;
2166

K
Karel Zak 已提交
2167
    va_start(ap, format);
2168 2169 2170 2171 2172
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2173
    va_end(ap);
2174
    fputs(str, stdout);
2175
    VIR_FREE(str);
K
Karel Zak 已提交
2176 2177
}

K
Karel Zak 已提交
2178

E
Eric Blake 已提交
2179
void
2180
vshError(vshControl *ctl, const char *format, ...)
2181
{
K
Karel Zak 已提交
2182
    va_list ap;
2183
    char *str;
2184

2185 2186 2187 2188 2189
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
2190

2191 2192 2193 2194
    /* 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);
2195
    fputs(_("error: "), stderr);
2196

K
Karel Zak 已提交
2197
    va_start(ap, format);
2198 2199 2200
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
2201 2202
    va_end(ap);

2203
    fprintf(stderr, "%s\n", NULLSTR(str));
2204
    fflush(stderr);
2205
    VIR_FREE(str);
K
Karel Zak 已提交
2206 2207
}

2208

J
Jiri Denemark 已提交
2209 2210 2211 2212 2213
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
E
Eric Blake 已提交
2224
            vshReportError(ctl);
J
Jiri Denemark 已提交
2225 2226 2227 2228
    }
}


K
Karel Zak 已提交
2229
/*
2230
 * Initialize connection.
K
Karel Zak 已提交
2231
 */
E
Eric Blake 已提交
2232
static bool
2233
vshInit(vshControl *ctl)
2234
{
2235 2236
    char *debugEnv;

K
Karel Zak 已提交
2237
    if (ctl->conn)
E
Eric Blake 已提交
2238
        return false;
K
Karel Zak 已提交
2239

J
Jiri Denemark 已提交
2240
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
2241 2242 2243
        /* log level not set from commandline, check env variable */
        debugEnv = getenv("VIRSH_DEBUG");
        if (debugEnv) {
J
Jiri Denemark 已提交
2244 2245 2246
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
2247 2248
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
2249 2250
            } else {
                ctl->debug = debug;
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
            }
        }
    }

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

2263 2264
    vshOpenLogFile(ctl);

2265 2266
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2267

2268
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
2269
        return false;
2270

J
Jiri Denemark 已提交
2271 2272 2273 2274
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

2275
    if (ctl->name) {
2276
        vshReconnect(ctl);
2277 2278 2279 2280 2281 2282 2283
        /* 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 已提交
2284
            vshReportError(ctl);
2285 2286
            return false;
        }
2287
    }
K
Karel Zak 已提交
2288

E
Eric Blake 已提交
2289
    return true;
K
Karel Zak 已提交
2290 2291
}

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

2294 2295 2296 2297 2298
/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
E
Eric Blake 已提交
2299
void
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
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:
2313
                vshError(ctl, "%s",
J
Jim Meyering 已提交
2314
                         _("failed to get the log file information"));
2315
                exit(EXIT_FAILURE);
2316 2317 2318
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
2319 2320
            vshError(ctl, "%s", _("the log path is not a file"));
            exit(EXIT_FAILURE);
2321 2322 2323 2324
        }
    }

    /* log file open */
2325
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
2326
        vshError(ctl, "%s",
J
Jim Meyering 已提交
2327
                 _("failed to open the log file. check the log file path"));
2328
        exit(EXIT_FAILURE);
2329 2330 2331 2332 2333 2334 2335 2336
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
E
Eric Blake 已提交
2337
void
2338 2339
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
2340
{
2341
    virBuffer buf = VIR_BUFFER_INITIALIZER;
J
John Ferlan 已提交
2342
    char *str = NULL;
2343
    size_t len;
2344
    const char *lvl = "";
2345
    time_t stTime;
2346
    struct tm stTm;
2347 2348 2349 2350 2351 2352 2353 2354 2355

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

    /**
     * create log format
     *
     * [YYYY.MM.DD HH:MM:SS SIGNATURE PID] LOG_LEVEL message
    */
2356 2357
    time(&stTime);
    localtime_r(&stTime, &stTm);
2358
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
2359 2360 2361 2362 2363 2364
                      (1900 + stTm.tm_year),
                      (1 + stTm.tm_mon),
                      stTm.tm_mday,
                      stTm.tm_hour,
                      stTm.tm_min,
                      stTm.tm_sec,
2365 2366
                      SIGN_NAME,
                      (int) getpid());
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
    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;
    }
2387 2388 2389
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
2390

2391 2392
    if (virBufferError(&buf))
        goto error;
2393

2394 2395 2396 2397 2398
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
2399
    }
2400

2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
    /* 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);
2412 2413 2414 2415 2416 2417 2418
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
E
Eric Blake 已提交
2419
void
2420 2421
vshCloseLogFile(vshControl *ctl)
{
2422 2423
    char ebuf[1024];

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

    if (ctl->logfile) {
2432
        VIR_FREE(ctl->logfile);
2433 2434 2435 2436
        ctl->logfile = NULL;
    }
}

2437
#ifdef USE_READLINE
2438

K
Karel Zak 已提交
2439 2440 2441 2442 2443
/* -----------------
 * Readline stuff
 * -----------------
 */

2444
/*
K
Karel Zak 已提交
2445 2446
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
2447
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
2448 2449
 */
static char *
2450 2451
vshReadlineCommandGenerator(const char *text, int state)
{
2452
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
2453
    const char *name;
2454 2455
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
2456 2457

    if (!state) {
2458 2459
        grp_list_index = 0;
        cmd_list_index = 0;
2460
        len = strlen(text);
K
Karel Zak 已提交
2461 2462
    }

2463 2464
    grp = cmdGroups;

K
Karel Zak 已提交
2465
    /* Return the next name which partially matches from the
2466
     * command list.
K
Karel Zak 已提交
2467
     */
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
    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 已提交
2482 2483 2484 2485 2486 2487 2488
    }

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

static char *
2489 2490
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2491
    static int list_index, len;
2492
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
2493
    const char *name;
K
Karel Zak 已提交
2494 2495 2496 2497 2498 2499 2500 2501 2502

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

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

2503
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
2504
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
2505 2506 2507

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
2508
        len = strlen(text);
2509
        VIR_FREE(cmdname);
K
Karel Zak 已提交
2510 2511 2512 2513
    }

    if (!cmd)
        return NULL;
2514

2515 2516 2517
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
2518
    while ((name = cmd->opts[list_index].name)) {
2519
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
2520
        char *res;
2521

K
Karel Zak 已提交
2522
        list_index++;
2523

2524
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
2525 2526
            /* ignore non --option */
            continue;
2527

K
Karel Zak 已提交
2528
        if (len > 2) {
2529
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
2530 2531
                continue;
        }
2532
        res = vshMalloc(NULL, strlen(name) + 3);
2533
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
2534 2535 2536 2537 2538 2539 2540 2541
        return res;
    }

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

static char **
2542 2543 2544
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2545 2546
    char **matches = (char **) NULL;

2547
    if (start == 0)
K
Karel Zak 已提交
2548
        /* command name generator */
2549
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
2550 2551
    else
        /* commands options */
2552
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
2553 2554 2555 2556
    return matches;
}


2557 2558
static int
vshReadlineInit(vshControl *ctl)
2559
{
2560 2561
    char *userdir = NULL;

K
Karel Zak 已提交
2562 2563 2564 2565 2566
    /* 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;
2567 2568 2569

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

2571
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
2572
    userdir = virGetUserCacheDirectory();
2573

2574 2575
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
2576
        return -1;
2577
    }
2578

2579
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
2580
        vshError(ctl, "%s", _("Out of memory"));
2581
        VIR_FREE(userdir);
2582 2583 2584 2585 2586
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
2587
        VIR_FREE(userdir);
2588 2589 2590
        return -1;
    }

2591
    VIR_FREE(userdir);
2592 2593 2594 2595 2596 2597 2598

    read_history(ctl->historyfile);

    return 0;
}

static void
2599
vshReadlineDeinit(vshControl *ctl)
2600 2601
{
    if (ctl->historyfile != NULL) {
2602 2603
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
2604 2605
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
2606
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
2607
        } else {
2608
            write_history(ctl->historyfile);
E
Eric Blake 已提交
2609
        }
2610 2611
    }

2612 2613
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
2614 2615
}

2616
static char *
2617
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
2618
{
2619
    return readline(prompt);
2620 2621
}

2622
#else /* !USE_READLINE */
2623

2624
static int
2625
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
2626 2627 2628 2629 2630
{
    /* empty */
    return 0;
}

2631
static void
2632
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
2633 2634 2635 2636 2637
{
    /* empty */
}

static char *
2638
vshReadline(vshControl *ctl, const char *prompt)
2639 2640 2641 2642 2643
{
    char line[1024];
    char *r;
    int len;

2644 2645
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
2646 2647 2648
    if (r == NULL) return NULL; /* EOF */

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

2653
    return vshStrdup(ctl, r);
2654 2655
}

2656
#endif /* !USE_READLINE */
2657

2658 2659 2660 2661 2662 2663
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
2664
/*
J
Jim Meyering 已提交
2665
 * Deinitialize virsh
K
Karel Zak 已提交
2666
 */
E
Eric Blake 已提交
2667
static bool
2668
vshDeinit(vshControl *ctl)
2669
{
2670
    vshReadlineDeinit(ctl);
2671
    vshCloseLogFile(ctl);
2672
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
2673
    if (ctl->conn) {
2674 2675 2676
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
K
Karel Zak 已提交
2677 2678
        }
    }
D
Daniel P. Berrange 已提交
2679 2680
    virResetLastError();

J
Jiri Denemark 已提交
2681
    if (ctl->eventLoopStarted) {
2682 2683 2684 2685
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
2686
        /* HACK: Add a dummy timeout to break event loop */
2687 2688 2689 2690 2691
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
2692 2693 2694 2695 2696 2697
        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

2698 2699
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
2700
    return true;
K
Karel Zak 已提交
2701
}
2702

K
Karel Zak 已提交
2703 2704 2705
/*
 * Print usage
 */
E
Eric Blake 已提交
2706
static void
2707
vshUsage(void)
2708
{
2709
    const vshCmdGrp *grp;
2710
    const vshCmdDef *cmd;
2711

L
Lai Jiangshan 已提交
2712 2713
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
2714
                      "  options:\n"
2715
                      "    -c | --connect=URI      hypervisor connection URI\n"
2716
                      "    -r | --readonly         connect readonly\n"
2717
                      "    -d | --debug=NUM        debug level [0-4]\n"
2718 2719 2720
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
2721 2722 2723 2724 2725
                      "    -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"
2726
                      "  commands (non interactive mode):\n\n"), progname, progname);
2727

2728
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
2729 2730 2731 2732 2733
        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;
2734
            fprintf(stdout,
E
Eric Blake 已提交
2735 2736 2737
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
2738 2739 2740 2741 2742
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
2743 2744 2745
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
2746 2747
}

2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
/*
 * 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 已提交
2758 2759
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
2760
#ifdef WITH_QEMU
2761
    vshPrint(ctl, " QEMU/KVM");
2762
#endif
D
Doug Goldstein 已提交
2763 2764 2765
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
2766 2767 2768
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
2769 2770 2771 2772 2773 2774
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
2775 2776 2777
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
2778 2779
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
2780
#endif
D
Doug Goldstein 已提交
2781 2782
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
2783
#endif
D
Doug Goldstein 已提交
2784 2785
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
2786 2787 2788 2789
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
2790 2791
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
2792
#endif
D
Doug Goldstein 已提交
2793 2794
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
2795 2796 2797 2798 2799 2800
#endif
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2801
    vshPrint(ctl, "%s", _(" Networking:"));
2802 2803 2804 2805 2806 2807 2808 2809 2810
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
2811
#if defined(WITH_INTERFACE)
D
Doug Goldstein 已提交
2812
    vshPrint(ctl, " Interface");
2813 2814
# if defined(WITH_NETCF)
    vshPrint(ctl, " netcf");
2815
# elif defined(WITH_UDEV)
2816
    vshPrint(ctl, " udev");
2817
# endif
2818 2819 2820 2821 2822 2823 2824 2825 2826
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2827
    vshPrint(ctl, "%s", _(" Storage:"));
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
#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");
2848 2849 2850
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
2851 2852 2853
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
2854 2855 2856
#endif
    vshPrint(ctl, "\n");

2857
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
2858 2859 2860
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
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
#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 已提交
2902
static bool
2903 2904
vshParseArgv(vshControl *ctl, int argc, char **argv)
{
2905
    int arg, len, debug;
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
    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':
2925
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
2926 2927 2928
                vshError(ctl, "%s", _("option -d takes a numeric argument"));
                exit(EXIT_FAILURE);
            }
2929 2930 2931 2932 2933
            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;
2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995
            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[] = {
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032
    {.name = "cd",
     .handler = cmdCd,
     .opts = opts_cd,
     .info = info_cd,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "echo",
     .handler = cmdEcho,
     .opts = opts_echo,
     .info = info_echo,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "exit",
     .handler = cmdQuit,
     .opts = NULL,
     .info = info_quit,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "help",
     .handler = cmdHelp,
     .opts = opts_help,
     .info = info_help,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "pwd",
     .handler = cmdPwd,
     .opts = NULL,
     .info = info_pwd,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "quit",
     .handler = cmdQuit,
     .opts = NULL,
     .info = info_quit,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = NULL}
3033
};
3034

3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
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 已提交
3050

3051 3052 3053 3054
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
3055
    char *defaultConn;
E
Eric Blake 已提交
3056
    bool ret = true;
K
Karel Zak 已提交
3057

3058 3059 3060
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
3061
    ctl->debug = VSH_DEBUG_DEFAULT;
E
Eric Blake 已提交
3062
    ctl->escapeChar = "^]";     /* Same default as telnet */
3063

3064

3065 3066
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
3067
        /* failure to setup locale is not fatal */
3068
    }
3069
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
3070
        perror("bindtextdomain");
E
Eric Blake 已提交
3071
        return EXIT_FAILURE;
3072
    }
3073
    if (!textdomain(PACKAGE)) {
3074
        perror("textdomain");
E
Eric Blake 已提交
3075
        return EXIT_FAILURE;
3076 3077
    }

3078 3079 3080 3081 3082
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

3083 3084 3085 3086 3087
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

3088
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
3089 3090 3091
        progname = argv[0];
    else
        progname++;
3092

3093
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
E
Eric Blake 已提交
3094
        ctl->name = vshStrdup(ctl, defaultConn);
3095 3096
    }

D
Daniel P. Berrange 已提交
3097 3098
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
3099
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3100
    }
3101

D
Daniel P. Berrange 已提交
3102 3103
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
3104
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3105
    }
3106

K
Karel Zak 已提交
3107
    if (!ctl->imode) {
3108
        ret = vshCommandRun(ctl, ctl->cmd);
3109
    } else {
K
Karel Zak 已提交
3110 3111
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
3112
            vshPrint(ctl,
3113
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
3114
                     progname);
J
Jim Meyering 已提交
3115
            vshPrint(ctl, "%s",
3116
                     _("Type:  'help' for help with commands\n"
3117
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
3118
        }
3119 3120 3121 3122 3123 3124

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

K
Karel Zak 已提交
3125
        do {
3126
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
3127
            ctl->cmdstr =
3128
                vshReadline(ctl, prompt);
3129 3130
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
3131
            if (*ctl->cmdstr) {
3132
#if USE_READLINE
K
Karel Zak 已提交
3133
                add_history(ctl->cmdstr);
3134
#endif
3135
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
3136 3137
                    vshCommandRun(ctl, ctl->cmd);
            }
3138
            VIR_FREE(ctl->cmdstr);
3139
        } while (ctl->imode);
K
Karel Zak 已提交
3140

3141 3142
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
3143
    }
3144

K
Karel Zak 已提交
3145 3146
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
3147
}