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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


E
Eric Blake 已提交
170
virErrorPtr last_error;
J
John Levon 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183

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

184 185 186
/*
 * Reset libvirt error on graceful fallback paths
 */
E
Eric Blake 已提交
187
void
188 189 190 191 192 193
vshResetLibvirtError(void)
{
    virFreeError(last_error);
    last_error = NULL;
}

J
John Levon 已提交
194 195 196 197 198 199 200 201
/*
 * 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 已提交
202
void
E
Eric Blake 已提交
203
vshReportError(vshControl *ctl)
J
John Levon 已提交
204
{
205 206 207 208 209 210 211 212
    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)
213
            goto out;
214
    }
J
John Levon 已提交
215 216

    if (last_error->code == VIR_ERR_OK) {
217
        vshError(ctl, "%s", _("unknown error"));
J
John Levon 已提交
218 219 220
        goto out;
    }

221
    vshError(ctl, "%s", last_error->message);
J
John Levon 已提交
222 223

out:
224
    vshResetLibvirtError();
J
John Levon 已提交
225 226
}

227 228 229 230 231 232 233 234
/*
 * Detection of disconnections and automatic reconnection support
 */
static int disconnected = 0; /* we may have been disconnected */

/*
 * vshCatchDisconnect:
 *
235 236
 * We get here when the connection was closed.  We can't do much in the
 * handler, just save the fact it was raised.
237
 */
L
Laine Stump 已提交
238
static void
239 240 241 242 243 244
vshCatchDisconnect(virConnectPtr conn ATTRIBUTE_UNUSED,
                   int reason,
                   void *opaque ATTRIBUTE_UNUSED)
{
    if (reason != VIR_CONNECT_CLOSE_REASON_CLIENT)
        disconnected++;
245 246 247 248 249
}

/*
 * vshReconnect:
 *
L
Laine Stump 已提交
250
 * Reconnect after a disconnect from libvirtd
251 252
 *
 */
L
Laine Stump 已提交
253
static void
254 255 256 257 258 259
vshReconnect(vshControl *ctl)
{
    bool connected = false;

    if (ctl->conn != NULL) {
        connected = true;
260
        virConnectClose(ctl->conn);
261
    }
262 263 264 265

    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);
266
    if (!ctl->conn) {
267
        vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
268 269 270 271 272 273 274
    } 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"));
    }
275
    disconnected = 0;
276
    ctl->useGetInfo = false;
277
    ctl->useSnapshotOld = false;
278
}
279

280
#ifndef WIN32
281 282 283 284 285 286 287 288 289 290 291 292 293
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);
}

294 295 296 297 298 299 300 301 302 303 304 305 306
/**
 * 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 已提交
307
int
308 309 310 311 312 313 314 315
vshAskReedit(vshControl *ctl, const char *msg)
{
    int c = -1;
    struct termios ttyattr;

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

E
Eric Blake 已提交
316
    vshReportError(ctl);
317 318 319 320 321 322 323 324 325 326 327

    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 == '?') {
328 329 330 331 332 333 334
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
335 336 337 338 339 340 341 342 343 344
            continue;
        } else if (c == 'y' || c == 'n' || c == 'f') {
            break;
        }
    }

    tcsetattr(STDIN_FILENO, TCSAFLUSH, &ttyattr);

    vshPrint(ctl, "\r\n");
    return c;
345 346
}
#else /* WIN32 */
347
int
348 349
vshAskReedit(vshControl *ctl, const char *msg ATTRIBUTE_UNUSED)
{
350 351 352 353
    vshDebug(ctl, VSH_ERR_WARNING, "%s", _("This function is not "
                                           "supported on WIN32 platform"));
    return 0;
}
354
#endif /* WIN32 */
355

E
Eric Blake 已提交
356 357
int vshStreamSink(virStreamPtr st ATTRIBUTE_UNUSED,
                  const char *bytes, size_t nbytes, void *opaque)
358 359 360 361 362 363
{
    int *fd = opaque;

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

K
Karel Zak 已提交
364 365 366 367 368 369
/* ---------------
 * Commands
 * ---------------
 */

/*
370
 * "help" command
K
Karel Zak 已提交
371
 */
372
static const vshCmdInfo info_help[] = {
373
    {"help", N_("print help")},
374 375
    {"desc", N_("Prints global help, command specific help, or help for a\n"
                "    group of related commands")},
376

377
    {NULL, NULL}
K
Karel Zak 已提交
378 379
};

380
static const vshCmdOptDef opts_help[] = {
381
    {"command", VSH_OT_DATA, 0, N_("Prints global help, command specific help, or help for a group of related commands")},
382
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
383 384
};

E
Eric Blake 已提交
385
static bool
386
cmdHelp(vshControl *ctl, const vshCmd *cmd)
387
 {
388
    const char *name = NULL;
389

390
    if (vshCommandOptString(cmd, "command", &name) <= 0) {
391
        const vshCmdGrp *grp;
392
        const vshCmdDef *def;
393

394 395 396 397 398 399
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

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

400 401 402
            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
403 404
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
405
            }
406 407 408 409

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
410
        return true;
411
    }
412

E
Eric Blake 已提交
413
    if (vshCmddefSearch(name)) {
414
        return vshCmddefHelp(ctl, name);
E
Eric Blake 已提交
415
    } else if (vshCmdGrpSearch(name)) {
416 417 418
        return vshCmdGrpHelp(ctl, name);
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
E
Eric Blake 已提交
419
        return false;
K
Karel Zak 已提交
420 421 422
    }
}

423 424 425 426 427 428 429 430 431 432 433
/* Tree listing helpers.  */

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

440
    if (virBufferError(indent))
441 442
        goto cleanup;

443 444 445 446 447 448 449 450 451 452
    /* 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;
453 454
    }

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

459 460 461
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
462

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

467 468 469 470
    /* Finally print all children */
    virBufferAddLit(indent, "  ");
    for (i = 0 ; i < num_devices ; i++) {
        const char *parent = (lookup)(i, true, opaque);
471

472 473 474 475 476
        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
477
    }
478
    virBufferTrim(indent, "  ", -1);
479

480 481 482 483
    /* 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));
484

485 486 487
    if (!root)
        virBufferTrim(indent, NULL, 2);
    ret = 0;
488 489 490 491
cleanup:
    return ret;
}

E
Eric Blake 已提交
492
int
493 494
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
495
{
496 497
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;
498

499 500 501 502 503
    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
504
    return ret;
505
}
506

507
/* Common code for the edit / net-edit / pool-edit functions which follow. */
E
Eric Blake 已提交
508
char *
E
Eric Blake 已提交
509
vshEditWriteToTempFile(vshControl *ctl, const char *doc)
510 511 512 513 514 515 516
{
    char *ret;
    const char *tmpdir;
    int fd;

    tmpdir = getenv ("TMPDIR");
    if (!tmpdir) tmpdir = "/tmp";
517 518 519 520
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
521
    fd = mkstemps(ret, 4);
522
    if (fd == -1) {
523
        vshError(ctl, _("mkstemps: failed to create temporary file: %s"),
524
                 strerror(errno));
525
        VIR_FREE(ret);
526 527 528
        return NULL;
    }

529
    if (safewrite(fd, doc, strlen(doc)) == -1) {
530 531
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
                 ret, strerror(errno));
S
Stefan Berger 已提交
532
        VIR_FORCE_CLOSE(fd);
533
        unlink(ret);
534
        VIR_FREE(ret);
535 536
        return NULL;
    }
S
Stefan Berger 已提交
537
    if (VIR_CLOSE(fd) < 0) {
538 539
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
                 ret, strerror(errno));
540
        unlink(ret);
541
        VIR_FREE(ret);
542 543 544 545 546 547 548 549 550 551 552
        return NULL;
    }

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

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

E
Eric Blake 已提交
553
int
E
Eric Blake 已提交
554
vshEditFile(vshControl *ctl, const char *filename)
555 556
{
    const char *editor;
E
Eric Blake 已提交
557 558 559 560
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;
561

562
    editor = getenv("VISUAL");
E
Eric Blake 已提交
563
    if (!editor)
564
        editor = getenv("EDITOR");
E
Eric Blake 已提交
565 566
    if (!editor)
        editor = "vi"; /* could be cruel & default to ed(1) here */
567

568 569 570 571 572
    /* 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 已提交
573 574
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
575
     */
576 577
    if (strspn(editor, ACCEPTED_CHARS) != strlen(editor)) {
        if (strspn(filename, ACCEPTED_CHARS) != strlen(filename)) {
E
Eric Blake 已提交
578 579 580 581 582 583 584 585 586 587
            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);
588 589
    }

E
Eric Blake 已提交
590 591 592 593 594
    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
E
Eric Blake 已提交
595
        vshReportError(ctl);
E
Eric Blake 已提交
596
        goto cleanup;
597
    }
E
Eric Blake 已提交
598
    ret = 0;
599

E
Eric Blake 已提交
600 601 602
cleanup:
    virCommandFree(cmd);
    return ret;
603 604
}

E
Eric Blake 已提交
605
char *
E
Eric Blake 已提交
606
vshEditReadBackFile(vshControl *ctl, const char *filename)
607 608 609
{
    char *ret;

E
Eric Blake 已提交
610
    if (virFileReadAll(filename, VSH_MAX_XML_FILE, &ret) == -1) {
611
        vshError(ctl,
612
                 _("%s: failed to read temporary file: %s"),
613
                 filename, strerror(errno));
614 615 616 617 618
        return NULL;
    }
    return ret;
}

619

P
Paolo Bonzini 已提交
620 621 622 623
/*
 * "cd" command
 */
static const vshCmdInfo info_cd[] = {
624 625
    {"help", N_("change the current directory")},
    {"desc", N_("Change the current directory.")},
P
Paolo Bonzini 已提交
626 627 628 629
    {NULL, NULL}
};

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

E
Eric Blake 已提交
634
static bool
635
cmdCd(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
636
{
637
    const char *dir = NULL;
638
    char *dir_malloced = NULL;
E
Eric Blake 已提交
639
    bool ret = true;
P
Paolo Bonzini 已提交
640 641

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

646
    if (vshCommandOptString(cmd, "dir", &dir) <= 0) {
647
        dir = dir_malloced = virGetUserDirectory();
P
Paolo Bonzini 已提交
648 649 650 651
    }
    if (!dir)
        dir = "/";

P
Phil Petty 已提交
652
    if (chdir(dir) == -1) {
653
        vshError(ctl, _("cd: %s: %s"), strerror(errno), dir);
E
Eric Blake 已提交
654
        ret = false;
P
Paolo Bonzini 已提交
655 656
    }

657
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
658
    return ret;
P
Paolo Bonzini 已提交
659 660 661 662 663 664
}

/*
 * "pwd" command
 */
static const vshCmdInfo info_pwd[] = {
665 666
    {"help", N_("print the current directory")},
    {"desc", N_("Print the current directory.")},
P
Paolo Bonzini 已提交
667 668 669
    {NULL, NULL}
};

E
Eric Blake 已提交
670
static bool
P
Paolo Bonzini 已提交
671 672 673
cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cwd;
674
    bool ret = true;
P
Paolo Bonzini 已提交
675

676 677
    cwd = getcwd(NULL, 0);
    if (!cwd) {
678 679
        vshError(ctl, _("pwd: cannot get current directory: %s"),
                 strerror(errno));
680 681
        ret = false;
    } else {
682
        vshPrint(ctl, _("%s\n"), cwd);
683 684
        VIR_FREE(cwd);
    }
P
Paolo Bonzini 已提交
685

686
    return ret;
P
Paolo Bonzini 已提交
687 688
}

E
Eric Blake 已提交
689 690 691 692 693 694 695 696 697 698 699 700
/*
 * "echo" command
 */
static const vshCmdInfo info_echo[] = {
    {"help", N_("echo arguments")},
    {"desc", N_("Echo back arguments, possibly with quoting.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_echo[] = {
    {"shell", VSH_OT_BOOL, 0, N_("escape for shell use")},
    {"xml", VSH_OT_BOOL, 0, N_("escape for XML use")},
E
Eric Blake 已提交
701
    {"str", VSH_OT_ALIAS, 0, "string"},
702
    {"string", VSH_OT_ARGV, 0, N_("arguments to echo")},
E
Eric Blake 已提交
703 704 705 706 707 708
    {NULL, 0, 0, NULL}
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
E
Eric Blake 已提交
709
static bool
710
cmdEcho(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
711 712 713 714
{
    bool shell = false;
    bool xml = false;
    int count = 0;
715
    const vshCmdOpt *opt = NULL;
E
Eric Blake 已提交
716 717 718 719 720 721 722 723
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

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

724
    while ((opt = vshCommandOptArgv(cmd, opt))) {
725 726
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
727

728
        arg = opt->data;
729

E
Eric Blake 已提交
730 731
        if (count)
            virBufferAddChar(&buf, ' ');
732

E
Eric Blake 已提交
733
        if (xml) {
734 735 736 737
            virBufferEscapeString(&xmlbuf, "%s", arg);
            if (virBufferError(&buf)) {
                vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
                return false;
E
Eric Blake 已提交
738
            }
739 740 741
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
E
Eric Blake 已提交
742
        }
743 744 745 746 747

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
E
Eric Blake 已提交
748
        count++;
749
        VIR_FREE(str);
E
Eric Blake 已提交
750 751 752 753
    }

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
754
        return false;
E
Eric Blake 已提交
755 756 757 758 759
    }
    arg = virBufferContentAndReset(&buf);
    if (arg)
        vshPrint(ctl, "%s", arg);
    VIR_FREE(arg);
E
Eric Blake 已提交
760
    return true;
E
Eric Blake 已提交
761 762
}

K
Karel Zak 已提交
763 764 765
/*
 * "quit" command
 */
766
static const vshCmdInfo info_quit[] = {
767
    {"help", N_("quit this interactive terminal")},
768
    {"desc", ""},
769
    {NULL, NULL}
K
Karel Zak 已提交
770 771
};

E
Eric Blake 已提交
772
static bool
773
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
774
{
E
Eric Blake 已提交
775 776
    ctl->imode = false;
    return true;
K
Karel Zak 已提交
777 778
}

779 780 781 782
/* ---------------
 * Utils for work with command definition
 * ---------------
 */
E
Eric Blake 已提交
783
const char *
784 785 786
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
{
    const vshCmdInfo *info;
787

788 789 790 791 792 793
    for (info = cmd->info; info && info->name; info++) {
        if (STREQ(info->name, name))
            return info->data;
    }
    return NULL;
}
794

795 796 797 798 799 800 801
/* 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;
802

803 804
    *opts_need_arg = 0;
    *opts_required = 0;
805

806 807
    if (!cmd->opts)
        return 0;
808

809 810
    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
811 812 813 814

        if (i > 31)
            return -1; /* too many options */
        if (opt->type == VSH_OT_BOOL) {
E
Eric Blake 已提交
815
            if (opt->flags & VSH_OFLAG_REQ)
816 817 818
                return -1; /* bool options can't be mandatory */
            continue;
        }
E
Eric Blake 已提交
819 820 821 822 823 824 825 826 827 828 829 830
        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 已提交
831 832
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
L
Lai Jiangshan 已提交
833 834 835 836
                *opts_required |= 1 << i;
            continue;
        }

837
        *opts_need_arg |= 1 << i;
E
Eric Blake 已提交
838
        if (opt->flags & VSH_OFLAG_REQ) {
839 840 841 842 843 844
            if (optional)
                return -1; /* mandatory options must be listed first */
            *opts_required |= 1 << i;
        } else {
            optional = true;
        }
845 846 847

        if (opt->type == VSH_OT_ARGV && cmd->opts[i + 1].name)
            return -1; /* argv option must be listed last */
848 849 850 851
    }
    return 0;
}

852 853
static vshCmdOptDef helpopt = {"help", VSH_OT_BOOL, 0,
                               N_("print help for this function")};
854
static const vshCmdOptDef *
855
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
856
                   uint32_t *opts_seen, int *opt_index)
857
{
858 859
    int i;

860 861 862 863
    if (STREQ(name, helpopt.name)) {
        return &helpopt;
    }

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

867
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
868 869 870 871
            if (opt->type == VSH_OT_ALIAS) {
                name = opt->help;
                continue;
            }
872
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
873 874 875
                vshError(ctl, _("option --%s already seen"), name);
                return NULL;
            }
876 877
            *opts_seen |= 1 << i;
            *opt_index = i;
K
Karel Zak 已提交
878
            return opt;
879 880 881
        }
    }

882 883 884 885
    if (STRNEQ(cmd->name, "help")) {
        vshError(ctl, _("command '%s' doesn't support option --%s"),
                 cmd->name, name);
    }
K
Karel Zak 已提交
886 887 888
    return NULL;
}

889
static const vshCmdOptDef *
890 891
vshCmddefGetData(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                 uint32_t *opts_seen)
892
{
893
    int i;
894
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
895

896 897 898 899
    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
E
Eric Blake 已提交
900
    i = ffs(*opts_need_arg) - 1;
901
    opt = &cmd->opts[i];
902
    if (opt->type != VSH_OT_ARGV)
903
        *opts_need_arg &= ~(1 << i);
904
    *opts_seen |= 1 << i;
905
    return opt;
K
Karel Zak 已提交
906 907
}

908 909 910
/*
 * Checks for required options
 */
911
static int
912 913
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint32_t opts_required,
                    uint32_t opts_seen)
914
{
915
    const vshCmdDef *def = cmd->def;
916 917 918 919 920 921 922 923 924
    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];
925

926
            vshError(ctl,
927
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
928 929 930
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
931 932
        }
    }
933
    return -1;
934 935
}

E
Eric Blake 已提交
936
const vshCmdDef *
937 938
vshCmddefSearch(const char *cmdname)
{
939
    const vshCmdGrp *g;
940
    const vshCmdDef *c;
941

942 943
    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
944
            if (STREQ(c->name, cmdname))
945 946 947 948
                return c;
        }
    }

K
Karel Zak 已提交
949 950 951
    return NULL;
}

E
Eric Blake 已提交
952
const vshCmdGrp *
953 954 955 956 957
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
958
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
959 960 961 962 963 964
            return g;
    }

    return NULL;
}

E
Eric Blake 已提交
965
bool
966 967 968 969 970 971 972
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 已提交
973
        return false;
974 975 976 977 978 979 980 981 982 983
    } 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 已提交
984
    return true;
985 986
}

E
Eric Blake 已提交
987
bool
988
vshCmddefHelp(vshControl *ctl, const char *cmdname)
989
{
990
    const vshCmdDef *def = vshCmddefSearch(cmdname);
991

K
Karel Zak 已提交
992
    if (!def) {
993
        vshError(ctl, _("command '%s' doesn't exist"), cmdname);
E
Eric Blake 已提交
994
        return false;
995
    } else {
E
Eric Blake 已提交
996 997
        /* Don't translate desc if it is "".  */
        const char *desc = vshCmddefGetInfo(def, "desc");
E
Eric Blake 已提交
998
        const char *help = _(vshCmddefGetInfo(def, "help"));
999
        char buf[256];
1000 1001
        uint32_t opts_need_arg;
        uint32_t opts_required;
1002
        bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
1003 1004 1005 1006

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

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

1013 1014 1015 1016 1017
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
1018
                const char *fmt = "%s";
1019 1020
                switch (opt->type) {
                case VSH_OT_BOOL:
1021
                    fmt = "[--%s]";
1022 1023
                    break;
                case VSH_OT_INT:
E
Eric Blake 已提交
1024
                    /* xgettext:c-format */
E
Eric Blake 已提交
1025
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
1026
                           : _("[--%s <number>]"));
1027 1028
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1029 1030
                    break;
                case VSH_OT_STRING:
E
Eric Blake 已提交
1031 1032
                    /* xgettext:c-format */
                    fmt = _("[--%s <string>]");
1033 1034
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1035 1036
                    break;
                case VSH_OT_DATA:
E
Eric Blake 已提交
1037
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
1038 1039
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1040 1041 1042
                    break;
                case VSH_OT_ARGV:
                    /* xgettext:c-format */
1043 1044 1045 1046 1047 1048 1049 1050
                    if (shortopt) {
                        fmt = (opt->flags & VSH_OFLAG_REQ)
                            ? _("{[--%s] <string>}...")
                            : _("[[--%s] <string>]...");
                    } else {
                        fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                            : _("[<%s>]...");
                    }
1051
                    break;
E
Eric Blake 已提交
1052 1053 1054
                case VSH_OT_ALIAS:
                    /* aliases are intentionally undocumented */
                    continue;
1055
                default:
1056
                    assert(0);
1057
                }
1058
                fputc(' ', stdout);
E
Eric Blake 已提交
1059
                fprintf(stdout, fmt, opt->name);
1060
            }
K
Karel Zak 已提交
1061
        }
1062 1063 1064
        fputc('\n', stdout);

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

K
Karel Zak 已提交
1070
        if (def->opts) {
1071
            const vshCmdOptDef *opt;
1072
            fputs(_("\n  OPTIONS\n"), stdout);
1073
            for (opt = def->opts; opt->name; opt++) {
1074 1075
                switch (opt->type) {
                case VSH_OT_BOOL:
K
Karel Zak 已提交
1076
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1077 1078
                    break;
                case VSH_OT_INT:
1079
                    snprintf(buf, sizeof(buf),
E
Eric Blake 已提交
1080
                             (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
1081
                             : _("--%s <number>"), opt->name);
1082 1083
                    break;
                case VSH_OT_STRING:
1084
                    /* OT_STRING should never be VSH_OFLAG_REQ */
1085
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
1086 1087
                    break;
                case VSH_OT_DATA:
1088 1089
                    snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                             opt->name);
1090 1091
                    break;
                case VSH_OT_ARGV:
1092 1093 1094
                    snprintf(buf, sizeof(buf),
                             shortopt ? _("[--%s] <string>") : _("<%s>"),
                             opt->name);
1095
                    break;
E
Eric Blake 已提交
1096 1097
                case VSH_OT_ALIAS:
                    continue;
1098 1099 1100
                default:
                    assert(0);
                }
1101

E
Eric Blake 已提交
1102
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
1103
            }
K
Karel Zak 已提交
1104 1105 1106
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
1107
    return true;
K
Karel Zak 已提交
1108 1109 1110 1111 1112 1113
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1114 1115 1116
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1117 1118
    vshCmdOpt *a = arg;

1119
    while (a) {
K
Karel Zak 已提交
1120
        vshCmdOpt *tmp = a;
1121

K
Karel Zak 已提交
1122 1123
        a = a->next;

1124 1125
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
1126 1127 1128 1129
    }
}

static void
1130
vshCommandFree(vshCmd *cmd)
1131
{
K
Karel Zak 已提交
1132 1133
    vshCmd *c = cmd;

1134
    while (c) {
K
Karel Zak 已提交
1135
        vshCmd *tmp = c;
1136

K
Karel Zak 已提交
1137 1138 1139 1140
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
1141
        VIR_FREE(tmp);
K
Karel Zak 已提交
1142 1143 1144
    }
}

E
Eric Blake 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
/**
 * 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 已提交
1156
 */
E
Eric Blake 已提交
1157
int
E
Eric Blake 已提交
1158
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
1159
{
E
Eric Blake 已提交
1160 1161
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
1162

E
Eric Blake 已提交
1163 1164 1165 1166 1167 1168 1169
    /* 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 已提交
1170
    }
E
Eric Blake 已提交
1171 1172 1173 1174 1175 1176 1177

    /* Option not present, see if command requires it.  */
    *opt = NULL;
    while (valid) {
        if (!valid->name)
            break;
        if (STREQ(name, valid->name))
E
Eric Blake 已提交
1178
            return (valid->flags & VSH_OFLAG_REQ) == 0 ? 0 : -1;
E
Eric Blake 已提交
1179 1180 1181 1182
        valid++;
    }
    /* If we got here, the name is unknown.  */
    return -2;
K
Karel Zak 已提交
1183 1184
}

E
Eric Blake 已提交
1185 1186
/**
 * vshCommandOptInt:
1187 1188 1189 1190 1191 1192 1193
 * @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 已提交
1194
 * 0 if option not found and not required (@value untouched)
1195
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
1196
 */
E
Eric Blake 已提交
1197
int
1198
vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
1199
{
E
Eric Blake 已提交
1200 1201
    vshCmdOpt *arg;
    int ret;
1202

E
Eric Blake 已提交
1203 1204 1205 1206 1207 1208 1209
    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;
1210
    }
E
Eric Blake 已提交
1211

E
Eric Blake 已提交
1212 1213 1214
    if (virStrToLong_i(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
K
Karel Zak 已提交
1215 1216
}

1217

E
Eric Blake 已提交
1218 1219 1220 1221 1222 1223
/**
 * vshCommandOptUInt:
 * @cmd command reference
 * @name option name
 * @value result
 *
1224 1225 1226
 * Convert option to unsigned int
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1227
int
1228 1229
vshCommandOptUInt(const vshCmd *cmd, const char *name, unsigned int *value)
{
E
Eric Blake 已提交
1230 1231
    vshCmdOpt *arg;
    int ret;
1232

E
Eric Blake 已提交
1233 1234 1235 1236 1237 1238 1239
    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;
1240
    }
E
Eric Blake 已提交
1241

E
Eric Blake 已提交
1242 1243 1244
    if (virStrToLong_ui(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1245 1246 1247
}


1248
/*
E
Eric Blake 已提交
1249 1250 1251 1252 1253
 * vshCommandOptUL:
 * @cmd command reference
 * @name option name
 * @value result
 *
1254 1255 1256
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1257
int
1258
vshCommandOptUL(const vshCmd *cmd, const char *name, unsigned long *value)
1259
{
E
Eric Blake 已提交
1260 1261
    vshCmdOpt *arg;
    int ret;
1262

E
Eric Blake 已提交
1263 1264 1265 1266 1267 1268 1269
    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;
1270
    }
E
Eric Blake 已提交
1271

E
Eric Blake 已提交
1272 1273 1274
    if (virStrToLong_ul(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1275 1276
}

E
Eric Blake 已提交
1277 1278 1279 1280 1281 1282
/**
 * vshCommandOptString:
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
1283
 * Returns option as STRING
E
Eric Blake 已提交
1284 1285 1286 1287
 * 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 已提交
1288
 */
E
Eric Blake 已提交
1289
int
1290
vshCommandOptString(const vshCmd *cmd, const char *name, const char **value)
1291
{
E
Eric Blake 已提交
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    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;
1302
    }
1303

E
Eric Blake 已提交
1304
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK)) {
E
Eric Blake 已提交
1305 1306 1307 1308
        return -1;
    }
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
1309 1310
}

E
Eric Blake 已提交
1311 1312 1313 1314 1315 1316
/**
 * vshCommandOptLongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
1317
 * Returns option as long long
1318
 * See vshCommandOptInt()
1319
 */
E
Eric Blake 已提交
1320
int
1321 1322
vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                      long long *value)
1323
{
E
Eric Blake 已提交
1324 1325
    vshCmdOpt *arg;
    int ret;
1326

E
Eric Blake 已提交
1327 1328 1329 1330 1331 1332 1333
    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;
1334
    }
E
Eric Blake 已提交
1335

E
Eric Blake 已提交
1336 1337 1338
    if (virStrToLong_ll(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1339 1340
}

E
Eric Blake 已提交
1341 1342 1343 1344 1345 1346 1347 1348 1349
/**
 * vshCommandOptULongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1350
int
1351 1352 1353
vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                       unsigned long long *value)
{
E
Eric Blake 已提交
1354 1355
    vshCmdOpt *arg;
    int ret;
1356

E
Eric Blake 已提交
1357 1358 1359 1360 1361 1362 1363
    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;
1364
    }
E
Eric Blake 已提交
1365

E
Eric Blake 已提交
1366 1367 1368
    if (virStrToLong_ull(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1369 1370 1371
}


E
Eric Blake 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
/**
 * 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 已提交
1383
int
E
Eric Blake 已提交
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
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 已提交
1402 1403 1404 1405 1406 1407 1408 1409 1410
/**
 * 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 已提交
1411
 */
E
Eric Blake 已提交
1412
bool
1413
vshCommandOptBool(const vshCmd *cmd, const char *name)
1414
{
E
Eric Blake 已提交
1415 1416 1417
    vshCmdOpt *dummy;

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

E
Eric Blake 已提交
1420 1421 1422 1423 1424
/**
 * vshCommandOptArgv:
 * @cmd command reference
 * @opt starting point for the search
 *
1425 1426
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
1427
 *
1428
 * Requires that a VSH_OT_ARGV option be last in the
1429 1430
 * list of supported options in CMD->def->opts.
 */
E
Eric Blake 已提交
1431
const vshCmdOpt *
1432
vshCommandOptArgv(const vshCmd *cmd, const vshCmdOpt *opt)
1433
{
1434
    opt = opt ? opt->next : cmd->opts;
1435 1436

    while (opt) {
E
Eric Blake 已提交
1437
        if (opt->def->type == VSH_OT_ARGV) {
1438
            return opt;
1439 1440 1441 1442 1443 1444
        }
        opt = opt->next;
    }
    return NULL;
}

J
Jim Meyering 已提交
1445 1446 1447
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
1448 1449
bool
vshCmdHasOption(vshControl *ctl, const vshCmd *cmd, const char *optname)
J
Jim Meyering 已提交
1450 1451 1452 1453 1454 1455
{
    /* 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) {
1456
        if (STREQ(opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
J
Jim Meyering 已提交
1457 1458 1459 1460 1461 1462
            found = true;
            break;
        }
    }

    if (!found)
1463
        vshError(ctl, _("internal error: virsh %s: no %s VSH_OT_DATA option"),
J
Jim Meyering 已提交
1464 1465 1466
                 cmd->def->name, optname);
    return found;
}
1467

K
Karel Zak 已提交
1468 1469 1470
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
1471
static bool
1472
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
1473
{
E
Eric Blake 已提交
1474
    bool ret = true;
1475 1476

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

1480 1481
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
1482 1483
            vshReconnect(ctl);

1484
        if (enable_timing)
K
Karel Zak 已提交
1485
            GETTIMEOFDAY(&before);
1486

K
Karel Zak 已提交
1487 1488
        ret = cmd->def->handler(ctl, cmd);

1489
        if (enable_timing)
K
Karel Zak 已提交
1490
            GETTIMEOFDAY(&after);
1491

1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
        /* 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++;

1502
        if (!ret)
E
Eric Blake 已提交
1503
            vshReportError(ctl);
J
John Levon 已提交
1504

1505
        if (!ret && disconnected != 0)
1506 1507
            vshReconnect(ctl);

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

E
Eric Blake 已提交
1511
        if (enable_timing) {
1512
            double diff_ms = (((after.tv_sec - before.tv_sec) * 1000.0) +
E
Eric Blake 已提交
1513 1514 1515 1516
                              ((after.tv_usec - before.tv_usec) / 1000.0));

            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"), diff_ms);
        } else {
K
Karel Zak 已提交
1517
            vshPrintExtra(ctl, "\n");
E
Eric Blake 已提交
1518
        }
K
Karel Zak 已提交
1519 1520 1521 1522 1523 1524
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
1525
 * Command parsing
K
Karel Zak 已提交
1526 1527 1528
 * ---------------
 */

1529 1530 1531 1532 1533 1534 1535
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 已提交
1536 1537 1538 1539
typedef struct _vshCommandParser vshCommandParser;
struct _vshCommandParser {
    vshCommandToken(*getNextArg)(vshControl *, vshCommandParser *,
                                 char **);
L
Lai Jiangshan 已提交
1540
    /* vshCommandStringGetArg() */
1541
    char *pos;
L
Lai Jiangshan 已提交
1542 1543 1544
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
E
Eric Blake 已提交
1545
};
1546

E
Eric Blake 已提交
1547
static bool
1548
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
1549
{
K
Karel Zak 已提交
1550 1551 1552
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
1553

K
Karel Zak 已提交
1554 1555 1556 1557
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
1558

1559
    while (1) {
K
Karel Zak 已提交
1560
        vshCmdOpt *last = NULL;
1561
        const vshCmdDef *cmd = NULL;
1562
        vshCommandToken tk;
L
Lai Jiangshan 已提交
1563
        bool data_only = false;
1564 1565 1566
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
1567

K
Karel Zak 已提交
1568
        first = NULL;
1569

1570
        while (1) {
1571
            const vshCmdOptDef *opt = NULL;
1572

K
Karel Zak 已提交
1573
            tkdata = NULL;
1574
            tk = parser->getNextArg(ctl, parser, &tkdata);
1575 1576

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1577
                goto syntaxError;
H
Hu Tao 已提交
1578 1579
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
1580
                break;
H
Hu Tao 已提交
1581
            }
1582 1583

            if (cmd == NULL) {
K
Karel Zak 已提交
1584 1585
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
1586
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
1587
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
1588
                }
1589 1590 1591 1592 1593 1594 1595
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
1596
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
1597 1598 1599 1600
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
1601
                char *optstr = strchr(tkdata + 2, '=');
C
Cole Robinson 已提交
1602
                int opt_index = 0;
1603

1604 1605 1606 1607
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
1608
                /* Special case 'help' to ignore all spurious options */
1609
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
1610
                                               &opts_seen, &opt_index))) {
1611
                    VIR_FREE(optstr);
1612 1613
                    if (STREQ(cmd->name, "help"))
                        continue;
K
Karel Zak 已提交
1614 1615
                    goto syntaxError;
                }
1616
                VIR_FREE(tkdata);
K
Karel Zak 已提交
1617 1618 1619

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
1620 1621 1622
                    if (optstr)
                        tkdata = optstr;
                    else
1623
                        tk = parser->getNextArg(ctl, parser, &tkdata);
1624
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1625
                        goto syntaxError;
1626
                    if (tk != VSH_TK_ARG) {
1627
                        vshError(ctl,
1628
                                 _("expected syntax: --%s <%s>"),
1629 1630
                                 opt->name,
                                 opt->type ==
1631
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
1632 1633
                        goto syntaxError;
                    }
1634 1635
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
1636 1637 1638 1639 1640 1641 1642 1643
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                opt->name);
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
1644
                }
L
Lai Jiangshan 已提交
1645 1646 1647 1648
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
1649
            } else {
L
Lai Jiangshan 已提交
1650
get_data:
1651
                /* Special case 'help' to ignore spurious data */
1652
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
1653 1654
                                             &opts_seen)) &&
                     STRNEQ(cmd->name, "help")) {
1655
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
1656 1657 1658 1659 1660
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
1661
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
1662

K
Karel Zak 已提交
1663 1664 1665 1666
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
1667

K
Karel Zak 已提交
1668 1669 1670 1671 1672
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
1673

1674
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
1675 1676
                         cmd->name,
                         opt->name,
1677 1678
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
1679 1680
            }
        }
1681

D
Daniel Veillard 已提交
1682
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
1683
        if (cmd) {
1684
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
            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;
            }
1704

K
Karel Zak 已提交
1705 1706 1707 1708
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

1709
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
1710
                VIR_FREE(c);
1711
                goto syntaxError;
1712
            }
1713

K
Karel Zak 已提交
1714 1715 1716 1717 1718 1719
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
1720 1721 1722

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
1723
    }
1724

E
Eric Blake 已提交
1725
    return true;
K
Karel Zak 已提交
1726

1727
 syntaxError:
1728
    if (ctl->cmd) {
K
Karel Zak 已提交
1729
        vshCommandFree(ctl->cmd);
1730 1731
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
1732 1733
    if (first)
        vshCommandOptFree(first);
1734
    VIR_FREE(tkdata);
E
Eric Blake 已提交
1735
    return false;
K
Karel Zak 已提交
1736 1737
}

1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
/* --------------------
 * 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 已提交
1756 1757
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
1758 1759 1760 1761
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
1762
        return false;
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834

    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 已提交
1835 1836
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
1837 1838 1839 1840
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
1841
        return false;
1842 1843 1844 1845 1846 1847

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

K
Karel Zak 已提交
1848
/* ---------------
1849
 * Misc utils
K
Karel Zak 已提交
1850 1851
 * ---------------
 */
E
Eric Blake 已提交
1852
int
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
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;
}

1880 1881
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
E
Eric Blake 已提交
1882
char *
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
{
    int ret = 0;
    char *str = NULL;

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

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

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

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

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

    case VIR_TYPED_PARAM_BOOLEAN:
        ret = virAsprintf(&str, "%s", item->value.b ? _("yes") : _("no"));
        break;

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

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

1921
    if (ret < 0) {
1922
        vshError(ctl, "%s", _("Out of memory"));
1923 1924
        exit(EXIT_FAILURE);
    }
1925 1926 1927
    return str;
}

E
Eric Blake 已提交
1928
virTypedParameterPtr
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
vshFindTypedParamByName(const char *name, virTypedParameterPtr list, int count)
{
    int i = count;
    virTypedParameterPtr found = list;

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

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

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

    /* not found */
    return NULL;
}

E
Eric Blake 已提交
1948
bool
1949
vshConnectionUsability(vshControl *ctl, virConnectPtr conn)
1950
{
1951 1952
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
1953 1954
     */
    if (!conn) {
1955
        vshError(ctl, "%s", _("no valid connection"));
E
Eric Blake 已提交
1956
        return false;
K
Karel Zak 已提交
1957
    }
E
Eric Blake 已提交
1958
    return true;
K
Karel Zak 已提交
1959 1960
}

E
Eric Blake 已提交
1961
void
1962
vshDebug(vshControl *ctl, int level, const char *format, ...)
1963
{
K
Karel Zak 已提交
1964
    va_list ap;
1965
    char *str;
K
Karel Zak 已提交
1966

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

1974
    va_start(ap, format);
1975
    vshOutputLogFile(ctl, level, format, ap);
1976 1977
    va_end(ap);

K
Karel Zak 已提交
1978
    va_start(ap, format);
1979 1980 1981 1982 1983
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
1984
    va_end(ap);
1985 1986
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
1987 1988
}

E
Eric Blake 已提交
1989
void
1990
vshPrintExtra(vshControl *ctl, const char *format, ...)
1991
{
K
Karel Zak 已提交
1992
    va_list ap;
1993
    char *str;
1994

1995
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
1996
        return;
1997

K
Karel Zak 已提交
1998
    va_start(ap, format);
1999 2000 2001 2002 2003
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2004
    va_end(ap);
2005
    fputs(str, stdout);
2006
    VIR_FREE(str);
K
Karel Zak 已提交
2007 2008
}

K
Karel Zak 已提交
2009

E
Eric Blake 已提交
2010
void
2011
vshError(vshControl *ctl, const char *format, ...)
2012
{
K
Karel Zak 已提交
2013
    va_list ap;
2014
    char *str;
2015

2016 2017 2018 2019 2020
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
2021

2022 2023 2024 2025
    /* 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);
2026
    fputs(_("error: "), stderr);
2027

K
Karel Zak 已提交
2028
    va_start(ap, format);
2029 2030 2031
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
2032 2033
    va_end(ap);

2034
    fprintf(stderr, "%s\n", NULLSTR(str));
2035
    fflush(stderr);
2036
    VIR_FREE(str);
K
Karel Zak 已提交
2037 2038
}

2039

J
Jiri Denemark 已提交
2040 2041 2042 2043 2044
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
E
Eric Blake 已提交
2055
            vshReportError(ctl);
J
Jiri Denemark 已提交
2056 2057 2058 2059
    }
}


K
Karel Zak 已提交
2060
/*
2061
 * Initialize connection.
K
Karel Zak 已提交
2062
 */
E
Eric Blake 已提交
2063
static bool
2064
vshInit(vshControl *ctl)
2065
{
2066 2067
    char *debugEnv;

K
Karel Zak 已提交
2068
    if (ctl->conn)
E
Eric Blake 已提交
2069
        return false;
K
Karel Zak 已提交
2070

J
Jiri Denemark 已提交
2071
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
2072 2073 2074
        /* log level not set from commandline, check env variable */
        debugEnv = getenv("VIRSH_DEBUG");
        if (debugEnv) {
J
Jiri Denemark 已提交
2075 2076 2077
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
2078 2079
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
2080 2081
            } else {
                ctl->debug = debug;
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
            }
        }
    }

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

2094 2095
    vshOpenLogFile(ctl);

2096 2097
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2098

2099
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
2100
        return false;
2101

J
Jiri Denemark 已提交
2102 2103 2104 2105
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

2106 2107 2108 2109
    if (ctl->name) {
        ctl->conn = virConnectOpenAuth(ctl->name,
                                       virConnectAuthPtrDefault,
                                       ctl->readonly ? VIR_CONNECT_RO : 0);
2110

2111 2112 2113 2114 2115 2116 2117
        /* 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 已提交
2118
            vshReportError(ctl);
2119 2120 2121
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
            return false;
        }
2122
    }
K
Karel Zak 已提交
2123

E
Eric Blake 已提交
2124
    return true;
K
Karel Zak 已提交
2125 2126
}

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

2129 2130 2131 2132 2133
/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
E
Eric Blake 已提交
2134
void
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
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:
2148
                vshError(ctl, "%s",
J
Jim Meyering 已提交
2149
                         _("failed to get the log file information"));
2150
                exit(EXIT_FAILURE);
2151 2152 2153
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
2154 2155
            vshError(ctl, "%s", _("the log path is not a file"));
            exit(EXIT_FAILURE);
2156 2157 2158 2159
        }
    }

    /* log file open */
2160
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
2161
        vshError(ctl, "%s",
J
Jim Meyering 已提交
2162
                 _("failed to open the log file. check the log file path"));
2163
        exit(EXIT_FAILURE);
2164 2165 2166 2167 2168 2169 2170 2171
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
E
Eric Blake 已提交
2172
void
2173 2174
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
2175
{
2176 2177 2178
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *str;
    size_t len;
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
    const char *lvl = "";
    struct timeval stTimeval;
    struct tm *stTm;

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

    /**
     * create log format
     *
     * [YYYY.MM.DD HH:MM:SS SIGNATURE PID] LOG_LEVEL message
    */
    gettimeofday(&stTimeval, NULL);
    stTm = localtime(&stTimeval.tv_sec);
2193
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
2194 2195 2196 2197 2198 2199
                      (1900 + stTm->tm_year),
                      (1 + stTm->tm_mon),
                      stTm->tm_mday,
                      stTm->tm_hour,
                      stTm->tm_min,
                      stTm->tm_sec,
2200 2201
                      SIGN_NAME,
                      (int) getpid());
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
    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;
    }
2222 2223 2224
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
2225

2226 2227
    if (virBufferError(&buf))
        goto error;
2228

2229 2230 2231 2232 2233
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
2234
    }
2235

2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
    /* 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);
2247 2248 2249 2250 2251 2252 2253
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
E
Eric Blake 已提交
2254
void
2255 2256 2257
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
2258 2259 2260
    if (VIR_CLOSE(ctl->log_fd) < 0) {
        vshError(ctl, _("%s: failed to write log file: %s"),
                 ctl->logfile ? ctl->logfile : "?", strerror (errno));
2261 2262 2263
    }

    if (ctl->logfile) {
2264
        VIR_FREE(ctl->logfile);
2265 2266 2267 2268
        ctl->logfile = NULL;
    }
}

2269
#ifdef USE_READLINE
2270

K
Karel Zak 已提交
2271 2272 2273 2274 2275
/* -----------------
 * Readline stuff
 * -----------------
 */

2276
/*
K
Karel Zak 已提交
2277 2278
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
2279
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
2280 2281
 */
static char *
2282 2283
vshReadlineCommandGenerator(const char *text, int state)
{
2284
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
2285
    const char *name;
2286 2287
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
2288 2289

    if (!state) {
2290 2291
        grp_list_index = 0;
        cmd_list_index = 0;
2292
        len = strlen(text);
K
Karel Zak 已提交
2293 2294
    }

2295 2296
    grp = cmdGroups;

K
Karel Zak 已提交
2297
    /* Return the next name which partially matches from the
2298
     * command list.
K
Karel Zak 已提交
2299
     */
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
    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 已提交
2314 2315 2316 2317 2318 2319 2320
    }

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

static char *
2321 2322
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2323
    static int list_index, len;
2324
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
2325
    const char *name;
K
Karel Zak 已提交
2326 2327 2328 2329 2330 2331 2332 2333 2334

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

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

2335
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
2336
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
2337 2338 2339

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
2340
        len = strlen(text);
2341
        VIR_FREE(cmdname);
K
Karel Zak 已提交
2342 2343 2344 2345
    }

    if (!cmd)
        return NULL;
2346

2347 2348 2349
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
2350
    while ((name = cmd->opts[list_index].name)) {
2351
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
2352
        char *res;
2353

K
Karel Zak 已提交
2354
        list_index++;
2355

2356
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
2357 2358
            /* ignore non --option */
            continue;
2359

K
Karel Zak 已提交
2360
        if (len > 2) {
2361
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
2362 2363
                continue;
        }
2364
        res = vshMalloc(NULL, strlen(name) + 3);
2365
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
2366 2367 2368 2369 2370 2371 2372 2373
        return res;
    }

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

static char **
2374 2375 2376
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2377 2378
    char **matches = (char **) NULL;

2379
    if (start == 0)
K
Karel Zak 已提交
2380
        /* command name generator */
2381
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
2382 2383
    else
        /* commands options */
2384
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
2385 2386 2387 2388
    return matches;
}


2389 2390
static int
vshReadlineInit(vshControl *ctl)
2391
{
2392 2393
    char *userdir = NULL;

K
Karel Zak 已提交
2394 2395 2396 2397 2398
    /* 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;
2399 2400 2401

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

2403
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
2404
    userdir = virGetUserCacheDirectory();
2405

2406 2407
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
2408
        return -1;
2409
    }
2410

2411
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
2412
        vshError(ctl, "%s", _("Out of memory"));
2413
        VIR_FREE(userdir);
2414 2415 2416 2417 2418
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
2419
        VIR_FREE(userdir);
2420 2421 2422
        return -1;
    }

2423
    VIR_FREE(userdir);
2424 2425 2426 2427 2428 2429 2430

    read_history(ctl->historyfile);

    return 0;
}

static void
2431
vshReadlineDeinit(vshControl *ctl)
2432 2433
{
    if (ctl->historyfile != NULL) {
2434 2435
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
2436 2437
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
2438
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
2439
        } else {
2440
            write_history(ctl->historyfile);
E
Eric Blake 已提交
2441
        }
2442 2443
    }

2444 2445
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
2446 2447
}

2448
static char *
2449
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
2450
{
2451
    return readline(prompt);
2452 2453
}

2454
#else /* !USE_READLINE */
2455

2456
static int
2457
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
2458 2459 2460 2461 2462
{
    /* empty */
    return 0;
}

2463
static void
2464
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
2465 2466 2467 2468 2469
{
    /* empty */
}

static char *
2470
vshReadline(vshControl *ctl, const char *prompt)
2471 2472 2473 2474 2475
{
    char line[1024];
    char *r;
    int len;

2476 2477
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
2478 2479 2480
    if (r == NULL) return NULL; /* EOF */

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

2485
    return vshStrdup(ctl, r);
2486 2487
}

2488
#endif /* !USE_READLINE */
2489

2490 2491 2492 2493 2494 2495
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
2496
/*
J
Jim Meyering 已提交
2497
 * Deinitialize virsh
K
Karel Zak 已提交
2498
 */
E
Eric Blake 已提交
2499
static bool
2500
vshDeinit(vshControl *ctl)
2501
{
2502
    vshReadlineDeinit(ctl);
2503
    vshCloseLogFile(ctl);
2504
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
2505
    if (ctl->conn) {
2506 2507 2508
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
K
Karel Zak 已提交
2509 2510
        }
    }
D
Daniel P. Berrange 已提交
2511 2512
    virResetLastError();

J
Jiri Denemark 已提交
2513
    if (ctl->eventLoopStarted) {
2514 2515 2516 2517
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
2518
        /* HACK: Add a dummy timeout to break event loop */
2519 2520 2521 2522 2523
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
2524 2525 2526 2527 2528 2529
        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

2530 2531
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
2532
    return true;
K
Karel Zak 已提交
2533
}
2534

K
Karel Zak 已提交
2535 2536 2537
/*
 * Print usage
 */
E
Eric Blake 已提交
2538
static void
2539
vshUsage(void)
2540
{
2541
    const vshCmdGrp *grp;
2542
    const vshCmdDef *cmd;
2543

L
Lai Jiangshan 已提交
2544 2545
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
2546
                      "  options:\n"
2547
                      "    -c | --connect=URI      hypervisor connection URI\n"
2548
                      "    -r | --readonly         connect readonly\n"
2549
                      "    -d | --debug=NUM        debug level [0-4]\n"
2550 2551 2552
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
2553 2554 2555 2556 2557
                      "    -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"
2558
                      "  commands (non interactive mode):\n\n"), progname, progname);
2559

2560
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
2561 2562 2563 2564 2565
        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;
2566
            fprintf(stdout,
E
Eric Blake 已提交
2567 2568 2569
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
2570 2571 2572 2573 2574
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
2575 2576 2577
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
2578 2579
}

2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
/*
 * 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 已提交
2590 2591
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
2592 2593 2594
#ifdef WITH_QEMU
    vshPrint(ctl, " QEmu/KVM");
#endif
D
Doug Goldstein 已提交
2595 2596 2597
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
2598 2599 2600
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
2601 2602 2603 2604 2605 2606
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
2607 2608 2609
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
2610 2611
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
2612
#endif
D
Doug Goldstein 已提交
2613 2614
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
2615
#endif
D
Doug Goldstein 已提交
2616 2617
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
2618 2619 2620 2621
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
2622 2623
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
2624
#endif
D
Doug Goldstein 已提交
2625 2626
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
2627 2628 2629 2630 2631 2632
#endif
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2633
    vshPrint(ctl, "%s", _(" Networking:"));
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
#ifdef WITH_NETCF
D
Doug Goldstein 已提交
2647
    vshPrint(ctl, " Interface");
2648 2649 2650 2651 2652 2653 2654 2655 2656
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2657
    vshPrint(ctl, "%s", _(" Storage:"));
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
#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");
2678 2679 2680
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
2681 2682 2683
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
2684 2685 2686
#endif
    vshPrint(ctl, "\n");

2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
#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 已提交
2729
static bool
2730 2731
vshParseArgv(vshControl *ctl, int argc, char **argv)
{
2732
    int arg, len, debug;
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751
    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':
2752
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
2753 2754 2755
                vshError(ctl, "%s", _("option -d takes a numeric argument"));
                exit(EXIT_FAILURE);
            }
2756 2757 2758 2759 2760
            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;
2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830
            break;
        case 'h':
            vshUsage();
            exit(EXIT_SUCCESS);
            break;
        case 'q':
            ctl->quiet = true;
            break;
        case 't':
            ctl->timing = true;
            break;
        case 'c':
            ctl->name = vshStrdup(ctl, optarg);
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
            /* fall through */
        case 'V':
            vshShowVersion(ctl);
            exit(EXIT_SUCCESS);
        case 'r':
            ctl->readonly = true;
            break;
        case 'l':
            ctl->logfile = vshStrdup(ctl, optarg);
            break;
        case 'e':
            len = strlen(optarg);

            if ((len == 2 && *optarg == '^' &&
                 vshAllowedEscapeChar(optarg[1])) ||
                (len == 1 && *optarg != '^')) {
                ctl->escapeChar = optarg;
            } else {
                vshError(ctl, _("Invalid string '%s' for escape sequence"),
                         optarg);
                exit(EXIT_FAILURE);
            }
            break;
        default:
            vshError(ctl, _("unsupported option '-%c'. See --help."), arg);
            exit(EXIT_FAILURE);
        }
    }

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

static const vshCmdDef virshCmds[] = {
    {"cd", cmdCd, opts_cd, info_cd, VSH_CMD_FLAG_NOCONNECT},
    {"echo", cmdEcho, opts_echo, info_echo, VSH_CMD_FLAG_NOCONNECT},
    {"exit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT},
    {"help", cmdHelp, opts_help, info_help, VSH_CMD_FLAG_NOCONNECT},
    {"pwd", cmdPwd, NULL, info_pwd, VSH_CMD_FLAG_NOCONNECT},
    {"quit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT},
    {NULL, NULL, NULL, NULL, 0}
};
2831

2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
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 已提交
2847

2848 2849 2850 2851
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
2852
    char *defaultConn;
E
Eric Blake 已提交
2853
    bool ret = true;
K
Karel Zak 已提交
2854

2855 2856 2857
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
2858
    ctl->debug = VSH_DEBUG_DEFAULT;
E
Eric Blake 已提交
2859
    ctl->escapeChar = "^]";     /* Same default as telnet */
2860

2861

2862 2863
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
2864
        /* failure to setup locale is not fatal */
2865
    }
2866
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
2867
        perror("bindtextdomain");
E
Eric Blake 已提交
2868
        return EXIT_FAILURE;
2869
    }
2870
    if (!textdomain(PACKAGE)) {
2871
        perror("textdomain");
E
Eric Blake 已提交
2872
        return EXIT_FAILURE;
2873 2874
    }

2875 2876 2877 2878 2879
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

2880 2881 2882 2883 2884
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

2885
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
2886 2887 2888
        progname = argv[0];
    else
        progname++;
2889

2890
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
E
Eric Blake 已提交
2891
        ctl->name = vshStrdup(ctl, defaultConn);
2892 2893
    }

D
Daniel P. Berrange 已提交
2894 2895
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
2896
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
2897
    }
2898

D
Daniel P. Berrange 已提交
2899 2900
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
2901
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
2902
    }
2903

K
Karel Zak 已提交
2904
    if (!ctl->imode) {
2905
        ret = vshCommandRun(ctl, ctl->cmd);
2906
    } else {
K
Karel Zak 已提交
2907 2908
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
2909
            vshPrint(ctl,
2910
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
2911
                     progname);
J
Jim Meyering 已提交
2912
            vshPrint(ctl, "%s",
2913
                     _("Type:  'help' for help with commands\n"
2914
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
2915
        }
2916 2917 2918 2919 2920 2921

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

K
Karel Zak 已提交
2922
        do {
2923
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
2924
            ctl->cmdstr =
2925
                vshReadline(ctl, prompt);
2926 2927
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
2928
            if (*ctl->cmdstr) {
2929
#if USE_READLINE
K
Karel Zak 已提交
2930
                add_history(ctl->cmdstr);
2931
#endif
2932
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
2933 2934
                    vshCommandRun(ctl, ctl->cmd);
            }
2935
            VIR_FREE(ctl->cmdstr);
2936
        } while (ctl->imode);
K
Karel Zak 已提交
2937

2938 2939
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
2940
    }
2941

K
Karel Zak 已提交
2942 2943
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
2944
}