virsh.c 77.4 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>
35
#include <sys/types.h>
K
Karel Zak 已提交
36
#include <sys/time.h>
E
Eric Blake 已提交
37
#include <sys/wait.h>
J
Jim Meyering 已提交
38
#include "c-ctype.h"
39
#include <fcntl.h>
40
#include <locale.h>
41
#include <time.h>
42
#include <limits.h>
43
#include <assert.h>
44
#include <sys/stat.h>
45
#include <inttypes.h>
46
#include <signal.h>
47
#include <poll.h>
E
Eric Blake 已提交
48
#include <strings.h>
49
#include <termios.h>
K
Karel Zak 已提交
50

51 52 53
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
54
#include <libxml/xmlsave.h>
55

56
#ifdef HAVE_READLINE_READLINE_H
57 58
# include <readline/readline.h>
# include <readline/history.h>
59
#endif
K
Karel Zak 已提交
60

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

E
Eric Blake 已提交
81 82
#include "virsh-domain.h"

K
Karel Zak 已提交
83 84
static char *progname;

85
static const vshCmdGrp cmdGroups[];
K
Karel Zak 已提交
86

E
Eric Blake 已提交
87 88
/* Bypass header poison */
#undef strdup
89

E
Eric Blake 已提交
90
void *
E
Eric Blake 已提交
91 92
_vshMalloc(vshControl *ctl, size_t size, const char *filename, int line)
{
E
Eric Blake 已提交
93
    char *x;
E
Eric Blake 已提交
94

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

E
Eric Blake 已提交
102 103 104
void *
_vshCalloc(vshControl *ctl, size_t nmemb, size_t size, const char *filename,
           int line)
E
Eric Blake 已提交
105
{
E
Eric Blake 已提交
106
    char *x;
E
Eric Blake 已提交
107

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

E
Eric Blake 已提交
116
char *
E
Eric Blake 已提交
117 118 119 120 121
_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line)
{
    char *x;

    if (s == NULL)
122
        return NULL;
E
Eric Blake 已提交
123 124 125 126 127 128 129 130 131
    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
132

133 134 135 136 137
static int
vshNameSorter(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;
138

139
    return vshStrcasecmp(*sa, *sb);
140 141
}

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


E
Eric Blake 已提交
164
virErrorPtr last_error;
J
John Levon 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177

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

178 179 180
/*
 * Reset libvirt error on graceful fallback paths
 */
E
Eric Blake 已提交
181
void
182 183 184 185 186 187
vshResetLibvirtError(void)
{
    virFreeError(last_error);
    last_error = NULL;
}

J
John Levon 已提交
188 189 190 191 192 193 194 195
/*
 * 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 已提交
196
void
J
John Levon 已提交
197 198
virshReportError(vshControl *ctl)
{
199 200 201 202 203 204 205 206
    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)
207
            goto out;
208
    }
J
John Levon 已提交
209 210

    if (last_error->code == VIR_ERR_OK) {
211
        vshError(ctl, "%s", _("unknown error"));
J
John Levon 已提交
212 213 214
        goto out;
    }

215
    vshError(ctl, "%s", last_error->message);
J
John Levon 已提交
216 217

out:
218
    vshResetLibvirtError();
J
John Levon 已提交
219 220
}

221 222 223 224 225
/*
 * Detection of disconnections and automatic reconnection support
 */
static int disconnected = 0; /* we may have been disconnected */

226 227 228 229 230
/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

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

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

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

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

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

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

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

    virshReportError(ctl);

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

    tcsetattr(STDIN_FILENO, TCSAFLUSH, &ttyattr);

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

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

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

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

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

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

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

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

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

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

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

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

            vshPrint(ctl, "\n");
        }

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

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

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

/* Given an index, return either the name of that device (non-NULL) or
 * of its parent (NULL if a root).  */
typedef const char * (*vshTreeLookup)(int devid, bool parent, void *opaque);

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

443
    if (virBufferError(indent))
444 445
        goto cleanup;

446 447 448 449 450 451 452 453 454 455
    /* 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;
456 457
    }

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

462 463 464
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
465

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

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

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

483 484 485 486
    /* 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));
487

488 489 490
    if (!root)
        virBufferTrim(indent, NULL, 2);
    ret = 0;
491 492 493 494
cleanup:
    return ret;
}

495 496 497
static int
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
498
{
499 500
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;
501

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

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

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

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

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

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

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

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

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

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

E
Eric Blake 已提交
603 604 605
cleanup:
    virCommandFree(cmd);
    return ret;
606 607
}

E
Eric Blake 已提交
608
char *
609
editReadBackFile(vshControl *ctl, const char *filename)
610 611 612
{
    char *ret;

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

622

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

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

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

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

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

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

660
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
661
    return ret;
P
Paolo Bonzini 已提交
662 663 664 665 666 667
}

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

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

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

689
    return ret;
P
Paolo Bonzini 已提交
690 691
}

E
Eric Blake 已提交
692 693 694 695 696 697 698 699 700 701 702 703
/*
 * "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 已提交
704
    {"str", VSH_OT_ALIAS, 0, "string"},
705
    {"string", VSH_OT_ARGV, 0, N_("arguments to echo")},
E
Eric Blake 已提交
706 707 708 709 710 711
    {NULL, 0, 0, NULL}
};

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

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

727
    while ((opt = vshCommandOptArgv(cmd, opt))) {
728 729
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
730

731
        arg = opt->data;
732

E
Eric Blake 已提交
733 734
        if (count)
            virBufferAddChar(&buf, ' ');
735

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

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

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

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

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

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

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

798 799 800 801 802 803 804
/* 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;
805

806 807
    *opts_need_arg = 0;
    *opts_required = 0;
808

809 810
    if (!cmd->opts)
        return 0;
811

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

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

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

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

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

863 864 865 866
    if (STREQ(name, helpopt.name)) {
        return &helpopt;
    }

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

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

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

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

899 900 901 902
    if (!*opts_need_arg)
        return NULL;

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

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

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

E
Eric Blake 已提交
939
const vshCmdDef *
940 941
vshCmddefSearch(const char *cmdname)
{
942
    const vshCmdGrp *g;
943
    const vshCmdDef *c;
944

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

K
Karel Zak 已提交
952 953 954
    return NULL;
}

E
Eric Blake 已提交
955
const vshCmdGrp *
956 957 958 959 960
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

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

    return NULL;
}

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

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

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

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

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

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

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

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

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

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

1122
    while (a) {
K
Karel Zak 已提交
1123
        vshCmdOpt *tmp = a;
1124

K
Karel Zak 已提交
1125 1126
        a = a->next;

1127 1128
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
1129 1130 1131 1132
    }
}

static void
1133
vshCommandFree(vshCmd *cmd)
1134
{
K
Karel Zak 已提交
1135 1136
    vshCmd *c = cmd;

1137
    while (c) {
K
Karel Zak 已提交
1138
        vshCmd *tmp = c;
1139

K
Karel Zak 已提交
1140 1141 1142 1143
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
1144
        VIR_FREE(tmp);
K
Karel Zak 已提交
1145 1146 1147
    }
}

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

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

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

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

E
Eric Blake 已提交
1206 1207 1208 1209 1210 1211 1212
    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;
1213
    }
E
Eric Blake 已提交
1214

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

1220

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

E
Eric Blake 已提交
1236 1237 1238 1239 1240 1241 1242
    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;
1243
    }
E
Eric Blake 已提交
1244

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


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

E
Eric Blake 已提交
1266 1267 1268 1269 1270 1271 1272
    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;
1273
    }
E
Eric Blake 已提交
1274

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

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

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

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

E
Eric Blake 已提交
1330 1331 1332 1333 1334 1335 1336
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1337
    }
E
Eric Blake 已提交
1338

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

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

E
Eric Blake 已提交
1360 1361 1362 1363 1364 1365 1366
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1367
    }
E
Eric Blake 已提交
1368

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


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

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

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

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

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

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

E
Eric Blake 已提交
1471
virDomainPtr
J
Jim Meyering 已提交
1472
vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
1473
                      const char **name, int flag)
1474
{
K
Karel Zak 已提交
1475
    virDomainPtr dom = NULL;
1476
    const char *n = NULL;
K
Karel Zak 已提交
1477
    int id;
J
Jim Meyering 已提交
1478
    const char *optname = "domain";
1479
    if (!cmd_has_option(ctl, cmd, optname))
J
Jim Meyering 已提交
1480
        return NULL;
1481

1482
    if (vshCommandOptString(cmd, optname, &n) <= 0)
1483 1484
        return NULL;

1485
    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
1486 1487
             cmd->def->name, optname, n);

K
Karel Zak 已提交
1488 1489
    if (name)
        *name = n;
1490

K
Karel Zak 已提交
1491
    /* try it by ID */
1492
    if (flag & VSH_BYID) {
1493
        if (virStrToLong_i(n, NULL, 10, &id) == 0 && id >= 0) {
1494 1495
            vshDebug(ctl, VSH_ERR_DEBUG,
                     "%s: <%s> seems like domain ID\n",
K
Karel Zak 已提交
1496 1497 1498
                     cmd->def->name, optname);
            dom = virDomainLookupByID(ctl->conn, id);
        }
1499
    }
K
Karel Zak 已提交
1500
    /* try it by UUID */
1501
    if (dom==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
1502
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain UUID\n",
1503
                 cmd->def->name, optname);
K
Karel Zak 已提交
1504
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
1505
    }
K
Karel Zak 已提交
1506
    /* try it by NAME */
1507
    if (dom==NULL && (flag & VSH_BYNAME)) {
1508
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain NAME\n",
1509
                 cmd->def->name, optname);
K
Karel Zak 已提交
1510
        dom = virDomainLookupByName(ctl->conn, n);
1511
    }
K
Karel Zak 已提交
1512

1513
    if (!dom)
1514
        vshError(ctl, _("failed to get domain '%s'"), n);
1515

K
Karel Zak 已提交
1516 1517 1518
    return dom;
}

K
Karel Zak 已提交
1519 1520 1521
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
1522
static bool
1523
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
1524
{
E
Eric Blake 已提交
1525
    bool ret = true;
1526 1527

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

1531 1532
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
1533 1534
            vshReconnect(ctl);

1535
        if (enable_timing)
K
Karel Zak 已提交
1536
            GETTIMEOFDAY(&before);
1537

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

1540
        if (enable_timing)
K
Karel Zak 已提交
1541
            GETTIMEOFDAY(&after);
1542

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
        /* 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++;

1553
        if (!ret)
J
John Levon 已提交
1554 1555
            virshReportError(ctl);

1556
        if (!ret && disconnected != 0)
1557 1558
            vshReconnect(ctl);

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

1562
        if (enable_timing)
1563
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
1564 1565
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
1566
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
1567 1568 1569 1570 1571 1572
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
1573
 * Command parsing
K
Karel Zak 已提交
1574 1575 1576
 * ---------------
 */

1577 1578 1579 1580 1581 1582 1583 1584
typedef enum {
    VSH_TK_ERROR, /* Failed to parse a token */
    VSH_TK_ARG, /* Arbitrary argument, might be option or empty */
    VSH_TK_SUBCMD_END, /* Separation between commands */
    VSH_TK_END /* No more commands */
} vshCommandToken;

typedef struct __vshCommandParser {
1585
    vshCommandToken(*getNextArg)(vshControl *, struct __vshCommandParser *,
1586
                                  char **);
L
Lai Jiangshan 已提交
1587
    /* vshCommandStringGetArg() */
1588
    char *pos;
L
Lai Jiangshan 已提交
1589 1590 1591
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
1592 1593
} vshCommandParser;

E
Eric Blake 已提交
1594
static bool
1595
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
1596
{
K
Karel Zak 已提交
1597 1598 1599
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
1600

K
Karel Zak 已提交
1601 1602 1603 1604
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
1605

1606
    while (1) {
K
Karel Zak 已提交
1607
        vshCmdOpt *last = NULL;
1608
        const vshCmdDef *cmd = NULL;
1609
        vshCommandToken tk;
L
Lai Jiangshan 已提交
1610
        bool data_only = false;
1611 1612 1613
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
1614

K
Karel Zak 已提交
1615
        first = NULL;
1616

1617
        while (1) {
1618
            const vshCmdOptDef *opt = NULL;
1619

K
Karel Zak 已提交
1620
            tkdata = NULL;
1621
            tk = parser->getNextArg(ctl, parser, &tkdata);
1622 1623

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1624
                goto syntaxError;
H
Hu Tao 已提交
1625 1626
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
1627
                break;
H
Hu Tao 已提交
1628
            }
1629 1630

            if (cmd == NULL) {
K
Karel Zak 已提交
1631 1632
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
1633
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
1634
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
1635
                }
1636 1637 1638 1639 1640 1641 1642
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
1643
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
1644 1645 1646 1647
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
1648
                char *optstr = strchr(tkdata + 2, '=');
C
Cole Robinson 已提交
1649
                int opt_index = 0;
1650

1651 1652 1653 1654
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
1655
                /* Special case 'help' to ignore all spurious options */
1656
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
1657
                                               &opts_seen, &opt_index))) {
1658
                    VIR_FREE(optstr);
1659 1660
                    if (STREQ(cmd->name, "help"))
                        continue;
K
Karel Zak 已提交
1661 1662
                    goto syntaxError;
                }
1663
                VIR_FREE(tkdata);
K
Karel Zak 已提交
1664 1665 1666

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
1667 1668 1669
                    if (optstr)
                        tkdata = optstr;
                    else
1670
                        tk = parser->getNextArg(ctl, parser, &tkdata);
1671
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1672
                        goto syntaxError;
1673
                    if (tk != VSH_TK_ARG) {
1674
                        vshError(ctl,
1675
                                 _("expected syntax: --%s <%s>"),
1676 1677
                                 opt->name,
                                 opt->type ==
1678
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
1679 1680
                        goto syntaxError;
                    }
1681 1682
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
1683 1684 1685 1686 1687 1688 1689 1690
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                opt->name);
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
1691
                }
L
Lai Jiangshan 已提交
1692 1693 1694 1695
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
1696
            } else {
L
Lai Jiangshan 已提交
1697
get_data:
1698
                /* Special case 'help' to ignore spurious data */
1699
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
1700 1701
                                             &opts_seen)) &&
                     STRNEQ(cmd->name, "help")) {
1702
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
1703 1704 1705 1706 1707
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
1708
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
1709

K
Karel Zak 已提交
1710 1711 1712 1713
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
1714

K
Karel Zak 已提交
1715 1716 1717 1718 1719
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
1720

1721
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
1722 1723
                         cmd->name,
                         opt->name,
1724 1725
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
1726 1727
            }
        }
1728

D
Daniel Veillard 已提交
1729
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
1730
        if (cmd) {
1731
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
            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;
            }
1751

K
Karel Zak 已提交
1752 1753 1754 1755
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

1756
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
1757
                VIR_FREE(c);
1758
                goto syntaxError;
1759
            }
1760

K
Karel Zak 已提交
1761 1762 1763 1764 1765 1766
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
1767 1768 1769

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
1770
    }
1771

E
Eric Blake 已提交
1772
    return true;
K
Karel Zak 已提交
1773

1774
 syntaxError:
1775
    if (ctl->cmd) {
K
Karel Zak 已提交
1776
        vshCommandFree(ctl->cmd);
1777 1778
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
1779 1780
    if (first)
        vshCommandOptFree(first);
1781
    VIR_FREE(tkdata);
E
Eric Blake 已提交
1782
    return false;
K
Karel Zak 已提交
1783 1784
}

1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
/* --------------------
 * 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 已提交
1803 1804
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
1805 1806 1807 1808
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
1809
        return false;
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881

    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 已提交
1882 1883
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
1884 1885 1886 1887
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
1888
        return false;
1889 1890 1891 1892 1893 1894

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

K
Karel Zak 已提交
1895
/* ---------------
1896
 * Misc utils
K
Karel Zak 已提交
1897 1898
 * ---------------
 */
E
Eric Blake 已提交
1899
int
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
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;
}

1927 1928
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
E
Eric Blake 已提交
1929
char *
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
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;

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

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

1968
    if (ret < 0) {
1969
        vshError(ctl, "%s", _("Out of memory"));
1970 1971
        exit(EXIT_FAILURE);
    }
1972 1973 1974
    return str;
}

E
Eric Blake 已提交
1975
virTypedParameterPtr
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
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 已提交
1995
bool
1996
vshConnectionUsability(vshControl *ctl, virConnectPtr conn)
1997
{
1998 1999
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
2000 2001
     */
    if (!conn) {
2002
        vshError(ctl, "%s", _("no valid connection"));
E
Eric Blake 已提交
2003
        return false;
K
Karel Zak 已提交
2004
    }
E
Eric Blake 已提交
2005
    return true;
K
Karel Zak 已提交
2006 2007
}

E
Eric Blake 已提交
2008
void
2009
vshDebug(vshControl *ctl, int level, const char *format, ...)
2010
{
K
Karel Zak 已提交
2011
    va_list ap;
2012
    char *str;
K
Karel Zak 已提交
2013

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

2021
    va_start(ap, format);
2022
    vshOutputLogFile(ctl, level, format, ap);
2023 2024
    va_end(ap);

K
Karel Zak 已提交
2025
    va_start(ap, format);
2026 2027 2028 2029 2030
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2031
    va_end(ap);
2032 2033
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
2034 2035
}

E
Eric Blake 已提交
2036
void
2037
vshPrintExtra(vshControl *ctl, const char *format, ...)
2038
{
K
Karel Zak 已提交
2039
    va_list ap;
2040
    char *str;
2041

2042
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
2043
        return;
2044

K
Karel Zak 已提交
2045
    va_start(ap, format);
2046 2047 2048 2049 2050
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2051
    va_end(ap);
2052
    fputs(str, stdout);
2053
    VIR_FREE(str);
K
Karel Zak 已提交
2054 2055
}

K
Karel Zak 已提交
2056

E
Eric Blake 已提交
2057
void
2058
vshError(vshControl *ctl, const char *format, ...)
2059
{
K
Karel Zak 已提交
2060
    va_list ap;
2061
    char *str;
2062

2063 2064 2065 2066 2067
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
2068

2069 2070 2071 2072
    /* 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);
2073
    fputs(_("error: "), stderr);
2074

K
Karel Zak 已提交
2075
    va_start(ap, format);
2076 2077 2078
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
2079 2080
    va_end(ap);

2081
    fprintf(stderr, "%s\n", NULLSTR(str));
2082
    fflush(stderr);
2083
    VIR_FREE(str);
K
Karel Zak 已提交
2084 2085
}

2086

J
Jiri Denemark 已提交
2087 2088 2089 2090 2091
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
J
Jiri Denemark 已提交
2102 2103 2104 2105 2106
            virshReportError(ctl);
    }
}


K
Karel Zak 已提交
2107
/*
2108
 * Initialize connection.
K
Karel Zak 已提交
2109
 */
E
Eric Blake 已提交
2110
bool
2111
vshInit(vshControl *ctl)
2112
{
2113 2114
    char *debugEnv;

K
Karel Zak 已提交
2115
    if (ctl->conn)
E
Eric Blake 已提交
2116
        return false;
K
Karel Zak 已提交
2117

J
Jiri Denemark 已提交
2118
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
2119 2120 2121
        /* log level not set from commandline, check env variable */
        debugEnv = getenv("VIRSH_DEBUG");
        if (debugEnv) {
J
Jiri Denemark 已提交
2122 2123 2124
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
2125 2126
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
2127 2128
            } else {
                ctl->debug = debug;
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
            }
        }
    }

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

2141 2142
    vshOpenLogFile(ctl);

2143 2144
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2145

2146
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
2147
        return false;
2148

J
Jiri Denemark 已提交
2149 2150 2151 2152
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

2153 2154 2155 2156
    if (ctl->name) {
        ctl->conn = virConnectOpenAuth(ctl->name,
                                       virConnectAuthPtrDefault,
                                       ctl->readonly ? VIR_CONNECT_RO : 0);
2157

2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
        /* 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) {
            virshReportError(ctl);
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
            return false;
        }
2169
    }
K
Karel Zak 已提交
2170

E
Eric Blake 已提交
2171
    return true;
K
Karel Zak 已提交
2172 2173
}

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

2176 2177 2178 2179 2180
/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
E
Eric Blake 已提交
2181
void
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
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:
2195
                vshError(ctl, "%s",
J
Jim Meyering 已提交
2196
                         _("failed to get the log file information"));
2197
                exit(EXIT_FAILURE);
2198 2199 2200
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
2201 2202
            vshError(ctl, "%s", _("the log path is not a file"));
            exit(EXIT_FAILURE);
2203 2204 2205 2206
        }
    }

    /* log file open */
2207
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
2208
        vshError(ctl, "%s",
J
Jim Meyering 已提交
2209
                 _("failed to open the log file. check the log file path"));
2210
        exit(EXIT_FAILURE);
2211 2212 2213 2214 2215 2216 2217 2218
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
E
Eric Blake 已提交
2219
void
2220 2221
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
2222
{
2223 2224 2225
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *str;
    size_t len;
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
    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);
2240
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
2241 2242 2243 2244 2245 2246
                      (1900 + stTm->tm_year),
                      (1 + stTm->tm_mon),
                      stTm->tm_mday,
                      stTm->tm_hour,
                      stTm->tm_min,
                      stTm->tm_sec,
2247 2248
                      SIGN_NAME,
                      (int) getpid());
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
    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;
    }
2269 2270 2271
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
2272

2273 2274
    if (virBufferError(&buf))
        goto error;
2275

2276 2277 2278 2279 2280
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
2281
    }
2282

2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
    /* 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);
2294 2295 2296 2297 2298 2299 2300
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
E
Eric Blake 已提交
2301
void
2302 2303 2304
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
2305 2306 2307
    if (VIR_CLOSE(ctl->log_fd) < 0) {
        vshError(ctl, _("%s: failed to write log file: %s"),
                 ctl->logfile ? ctl->logfile : "?", strerror (errno));
2308 2309 2310
    }

    if (ctl->logfile) {
2311
        VIR_FREE(ctl->logfile);
2312 2313 2314 2315
        ctl->logfile = NULL;
    }
}

2316
#ifdef USE_READLINE
2317

K
Karel Zak 已提交
2318 2319 2320 2321 2322
/* -----------------
 * Readline stuff
 * -----------------
 */

2323
/*
K
Karel Zak 已提交
2324 2325
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
2326
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
2327 2328
 */
static char *
2329 2330
vshReadlineCommandGenerator(const char *text, int state)
{
2331
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
2332
    const char *name;
2333 2334
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
2335 2336

    if (!state) {
2337 2338
        grp_list_index = 0;
        cmd_list_index = 0;
2339
        len = strlen(text);
K
Karel Zak 已提交
2340 2341
    }

2342 2343
    grp = cmdGroups;

K
Karel Zak 已提交
2344
    /* Return the next name which partially matches from the
2345
     * command list.
K
Karel Zak 已提交
2346
     */
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
    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 已提交
2361 2362 2363 2364 2365 2366 2367
    }

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

static char *
2368 2369
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2370
    static int list_index, len;
2371
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
2372
    const char *name;
K
Karel Zak 已提交
2373 2374 2375 2376 2377 2378 2379 2380 2381

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

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

2382
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
2383
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
2384 2385 2386

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
2387
        len = strlen(text);
2388
        VIR_FREE(cmdname);
K
Karel Zak 已提交
2389 2390 2391 2392
    }

    if (!cmd)
        return NULL;
2393

2394 2395 2396
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
2397
    while ((name = cmd->opts[list_index].name)) {
2398
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
2399
        char *res;
2400

K
Karel Zak 已提交
2401
        list_index++;
2402

2403
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
2404 2405
            /* ignore non --option */
            continue;
2406

K
Karel Zak 已提交
2407
        if (len > 2) {
2408
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
2409 2410
                continue;
        }
2411
        res = vshMalloc(NULL, strlen(name) + 3);
2412
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
2413 2414 2415 2416 2417 2418 2419 2420
        return res;
    }

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

static char **
2421 2422 2423
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2424 2425
    char **matches = (char **) NULL;

2426
    if (start == 0)
K
Karel Zak 已提交
2427
        /* command name generator */
2428
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
2429 2430
    else
        /* commands options */
2431
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
2432 2433 2434 2435
    return matches;
}


2436 2437
static int
vshReadlineInit(vshControl *ctl)
2438
{
2439 2440
    char *userdir = NULL;

K
Karel Zak 已提交
2441 2442 2443 2444 2445
    /* 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;
2446 2447 2448

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

2450
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
2451
    userdir = virGetUserCacheDirectory();
2452

2453 2454
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
2455
        return -1;
2456
    }
2457

2458
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
2459
        vshError(ctl, "%s", _("Out of memory"));
2460
        VIR_FREE(userdir);
2461 2462 2463 2464 2465
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
2466
        VIR_FREE(userdir);
2467 2468 2469
        return -1;
    }

2470
    VIR_FREE(userdir);
2471 2472 2473 2474 2475 2476 2477

    read_history(ctl->historyfile);

    return 0;
}

static void
2478
vshReadlineDeinit(vshControl *ctl)
2479 2480
{
    if (ctl->historyfile != NULL) {
2481 2482
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
2483 2484
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
2485
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
2486
        } else {
2487
            write_history(ctl->historyfile);
E
Eric Blake 已提交
2488
        }
2489 2490
    }

2491 2492
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
2493 2494
}

2495
static char *
2496
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
2497
{
2498
    return readline(prompt);
2499 2500
}

2501
#else /* !USE_READLINE */
2502

2503
static int
2504
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
2505 2506 2507 2508 2509
{
    /* empty */
    return 0;
}

2510
static void
2511
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
2512 2513 2514 2515 2516
{
    /* empty */
}

static char *
2517
vshReadline(vshControl *ctl, const char *prompt)
2518 2519 2520 2521 2522
{
    char line[1024];
    char *r;
    int len;

2523 2524
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
2525 2526 2527
    if (r == NULL) return NULL; /* EOF */

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

2532
    return vshStrdup(ctl, r);
2533 2534
}

2535
#endif /* !USE_READLINE */
2536

2537 2538 2539 2540 2541 2542
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
2543
/*
J
Jim Meyering 已提交
2544
 * Deinitialize virsh
K
Karel Zak 已提交
2545
 */
E
Eric Blake 已提交
2546
bool
2547
vshDeinit(vshControl *ctl)
2548
{
2549
    vshReadlineDeinit(ctl);
2550
    vshCloseLogFile(ctl);
2551
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
2552
    if (ctl->conn) {
2553 2554 2555
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
K
Karel Zak 已提交
2556 2557
        }
    }
D
Daniel P. Berrange 已提交
2558 2559
    virResetLastError();

J
Jiri Denemark 已提交
2560
    if (ctl->eventLoopStarted) {
2561 2562 2563 2564
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
2565
        /* HACK: Add a dummy timeout to break event loop */
2566 2567 2568 2569 2570
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
2571 2572 2573 2574 2575 2576
        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

2577 2578
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
2579
    return true;
K
Karel Zak 已提交
2580
}
2581

K
Karel Zak 已提交
2582 2583 2584
/*
 * Print usage
 */
E
Eric Blake 已提交
2585
void
2586
vshUsage(void)
2587
{
2588
    const vshCmdGrp *grp;
2589
    const vshCmdDef *cmd;
2590

L
Lai Jiangshan 已提交
2591 2592
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
2593
                      "  options:\n"
2594
                      "    -c | --connect=URI      hypervisor connection URI\n"
2595
                      "    -r | --readonly         connect readonly\n"
2596
                      "    -d | --debug=NUM        debug level [0-4]\n"
2597 2598 2599
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
2600 2601 2602 2603 2604
                      "    -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"
2605
                      "  commands (non interactive mode):\n\n"), progname, progname);
2606

2607
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
2608 2609 2610 2611 2612
        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;
2613
            fprintf(stdout,
E
Eric Blake 已提交
2614 2615 2616
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
2617 2618 2619 2620 2621
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
2622 2623 2624
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
2625 2626
}

2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
/*
 * 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 已提交
2637 2638
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
2639 2640 2641
#ifdef WITH_QEMU
    vshPrint(ctl, " QEmu/KVM");
#endif
D
Doug Goldstein 已提交
2642 2643 2644
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
2645 2646 2647
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
2648 2649 2650 2651 2652 2653
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
2654 2655 2656
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
2657 2658
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
2659
#endif
D
Doug Goldstein 已提交
2660 2661
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
2662
#endif
D
Doug Goldstein 已提交
2663 2664
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
2665 2666 2667 2668
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
2669 2670
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
2671
#endif
D
Doug Goldstein 已提交
2672 2673
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
2674 2675 2676 2677 2678 2679
#endif
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2680
    vshPrint(ctl, "%s", _(" Networking:"));
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
#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 已提交
2694
    vshPrint(ctl, " Interface");
2695 2696 2697 2698 2699 2700 2701 2702 2703
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2704
    vshPrint(ctl, "%s", _(" Storage:"));
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
#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");
2725 2726 2727
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
2728 2729 2730
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
2731 2732 2733
#endif
    vshPrint(ctl, "\n");

2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
    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 已提交
2776
bool
2777 2778
vshParseArgv(vshControl *ctl, int argc, char **argv)
{
2779
    int arg, len, debug;
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
    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':
2799
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
2800 2801 2802
                vshError(ctl, "%s", _("option -d takes a numeric argument"));
                exit(EXIT_FAILURE);
            }
2803 2804 2805 2806 2807
            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;
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868
            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;
}

2869
#include "virsh-domain-monitor.c"
E
Eric Blake 已提交
2870 2871
#include "virsh-host.c"
#include "virsh-interface.c"
2872
#include "virsh-network.c"
2873
#include "virsh-nodedev.c"
2874
#include "virsh-nwfilter.c"
E
Eric Blake 已提交
2875
#include "virsh-pool.c"
2876
#include "virsh-secret.c"
2877
#include "virsh-snapshot.c"
E
Eric Blake 已提交
2878
#include "virsh-volume.c"
2879

2880 2881 2882 2883 2884 2885 2886 2887 2888
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}
};
2889

2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
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 已提交
2905

2906 2907 2908 2909
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
2910
    char *defaultConn;
E
Eric Blake 已提交
2911
    bool ret = true;
K
Karel Zak 已提交
2912

2913 2914 2915
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
2916
    ctl->debug = VSH_DEBUG_DEFAULT;
2917 2918
    ctl->escapeChar = CTRL_CLOSE_BRACKET;

2919

2920 2921
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
2922
        /* failure to setup locale is not fatal */
2923
    }
2924
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
2925
        perror("bindtextdomain");
E
Eric Blake 已提交
2926
        return EXIT_FAILURE;
2927
    }
2928
    if (!textdomain(PACKAGE)) {
2929
        perror("textdomain");
E
Eric Blake 已提交
2930
        return EXIT_FAILURE;
2931 2932
    }

2933 2934 2935 2936 2937
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

2938 2939 2940 2941 2942
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

2943
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
2944 2945 2946
        progname = argv[0];
    else
        progname++;
2947

2948
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
E
Eric Blake 已提交
2949
        ctl->name = vshStrdup(ctl, defaultConn);
2950 2951
    }

D
Daniel P. Berrange 已提交
2952 2953
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
2954
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
2955
    }
2956

D
Daniel P. Berrange 已提交
2957 2958
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
2959
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
2960
    }
2961

K
Karel Zak 已提交
2962
    if (!ctl->imode) {
2963
        ret = vshCommandRun(ctl, ctl->cmd);
2964
    } else {
K
Karel Zak 已提交
2965 2966
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
2967
            vshPrint(ctl,
2968
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
2969
                     progname);
J
Jim Meyering 已提交
2970
            vshPrint(ctl, "%s",
2971
                     _("Type:  'help' for help with commands\n"
2972
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
2973
        }
2974 2975 2976 2977 2978 2979

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

K
Karel Zak 已提交
2980
        do {
2981
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
2982
            ctl->cmdstr =
2983
                vshReadline(ctl, prompt);
2984 2985
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
2986
            if (*ctl->cmdstr) {
2987
#if USE_READLINE
K
Karel Zak 已提交
2988
                add_history(ctl->cmdstr);
2989
#endif
2990
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
2991 2992
                    vshCommandRun(ctl, ctl->cmd);
            }
2993
            VIR_FREE(ctl->cmdstr);
2994
        } while (ctl->imode);
K
Karel Zak 已提交
2995

2996 2997
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
2998
    }
2999

K
Karel Zak 已提交
3000 3001
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
3002
}