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

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

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

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

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

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

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

89 90 91 92 93
/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

K
Karel Zak 已提交
94 95
static char *progname;

96
static const vshCmdGrp cmdGroups[];
K
Karel Zak 已提交
97

E
Eric Blake 已提交
98 99
/* Bypass header poison */
#undef strdup
100

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

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

E
Eric Blake 已提交
113 114 115
void *
_vshCalloc(vshControl *ctl, size_t nmemb, size_t size, const char *filename,
           int line)
E
Eric Blake 已提交
116
{
E
Eric Blake 已提交
117
    char *x;
E
Eric Blake 已提交
118

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

E
Eric Blake 已提交
127
char *
E
Eric Blake 已提交
128 129 130 131
_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line)
{
    char *x;

132
    if (VIR_STRDUP(x, s) >= 0)
E
Eric Blake 已提交
133 134 135 136 137 138 139 140
        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
141

142
int
143 144 145 146
vshNameSorter(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;
147

148
    return vshStrcasecmp(*sa, *sb);
149 150
}

E
Eric Blake 已提交
151
double
E
Eric Blake 已提交
152
vshPrettyCapacity(unsigned long long val, const char **unit)
E
Eric Blake 已提交
153
{
154 155 156
    double limit = 1024;

    if (val < limit) {
157
        *unit = "B";
158 159 160 161
        return val;
    }
    limit *= 1024;
    if (val < limit) {
162
        *unit = "KiB";
163 164 165 166
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
167
        *unit = "MiB";
168 169 170 171
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
172
        *unit = "GiB";
173 174 175 176
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
177
        *unit = "TiB";
178 179 180 181 182 183
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
        *unit = "PiB";
        return val / (limit / 1024);
184
    }
185 186 187
    limit *= 1024;
    *unit = "EiB";
    return val / (limit / 1024);
188 189
}

190
/*
191 192 193
 * Convert the strings separated by ',' into array. The returned
 * array is a NULL terminated string list. The caller has to free
 * the array using virStringFreeList or a similar method.
194 195 196 197 198
 *
 * Returns the length of the filled array on success, or -1
 * on error.
 */
int
199
vshStringToArray(const char *str,
200 201
                 char ***array)
{
202
    char *str_copied = vshStrdup(NULL, str);
203
    char *str_tok = NULL;
E
Eric Blake 已提交
204
    char *tmp;
205 206
    unsigned int nstr_tokens = 0;
    char **arr = NULL;
E
Eric Blake 已提交
207
    size_t len = strlen(str_copied);
208

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

E
Eric Blake 已提交
212 213 214 215 216
    /* count the delimiters, recognizing ,, as an escape for a
     * literal comma */
    str_tok = str_copied;
    while ((str_tok = strchr(str_tok, ','))) {
        if (str_tok[1] == ',')
217
            str_tok++;
E
Eric Blake 已提交
218 219 220 221
        else
            nstr_tokens++;
        str_tok++;
    }
222

223 224
    /* reserve the NULL element at the end */
    if (VIR_ALLOC_N(arr, nstr_tokens + 1) < 0) {
E
Eric Blake 已提交
225 226 227
        VIR_FREE(str_copied);
        return -1;
    }
228

E
Eric Blake 已提交
229 230 231 232 233 234 235 236 237 238 239
    /* tokenize the input string, while treating ,, as a literal comma */
    nstr_tokens = 0;
    tmp = str_tok = str_copied;
    while ((tmp = strchr(tmp, ','))) {
        if (tmp[1] == ',') {
            memmove(&tmp[1], &tmp[2], len - (tmp - str_copied) - 2 + 1);
            len--;
            tmp++;
            continue;
        }
        *tmp++ = '\0';
240
        arr[nstr_tokens++] = vshStrdup(NULL, str_tok);
E
Eric Blake 已提交
241
        str_tok = tmp;
242
    }
243
    arr[nstr_tokens++] = vshStrdup(NULL, str_tok);
244 245

    *array = arr;
246
    VIR_FREE(str_copied);
247 248
    return nstr_tokens;
}
249

E
Eric Blake 已提交
250
virErrorPtr last_error;
J
John Levon 已提交
251 252 253 254 255 256 257 258 259

/*
 * Quieten libvirt until we're done with the command.
 */
static void
virshErrorHandler(void *unused ATTRIBUTE_UNUSED, virErrorPtr error)
{
    virFreeError(last_error);
    last_error = virSaveLastError();
260
    if (virGetEnvAllowSUID("VIRSH_DEBUG") != NULL)
J
John Levon 已提交
261 262 263
        virDefaultErrorFunc(error);
}

264 265 266 267 268 269 270 271 272
/* Store a libvirt error that is from a helper API that doesn't raise errors
 * so it doesn't get overwritten */
void
vshSaveLibvirtError(void)
{
    virFreeError(last_error);
    last_error = virSaveLastError();
}

273 274 275
/*
 * Reset libvirt error on graceful fallback paths
 */
E
Eric Blake 已提交
276
void
277 278 279 280 281 282
vshResetLibvirtError(void)
{
    virFreeError(last_error);
    last_error = NULL;
}

J
John Levon 已提交
283 284 285 286 287 288 289 290
/*
 * 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 已提交
291
void
E
Eric Blake 已提交
292
vshReportError(vshControl *ctl)
J
John Levon 已提交
293
{
294 295 296 297 298 299 300 301
    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)
302
            goto out;
303
    }
J
John Levon 已提交
304 305

    if (last_error->code == VIR_ERR_OK) {
306
        vshError(ctl, "%s", _("unknown error"));
J
John Levon 已提交
307 308 309
        goto out;
    }

310
    vshError(ctl, "%s", last_error->message);
J
John Levon 已提交
311

312
 out:
313
    vshResetLibvirtError();
J
John Levon 已提交
314 315
}

316 317 318
/*
 * Detection of disconnections and automatic reconnection support
 */
319
static int disconnected; /* we may have been disconnected */
320 321 322 323

/*
 * vshCatchDisconnect:
 *
324 325
 * We get here when the connection was closed.  We can't do much in the
 * handler, just save the fact it was raised.
326
 */
L
Laine Stump 已提交
327
static void
328 329 330 331 332 333
vshCatchDisconnect(virConnectPtr conn ATTRIBUTE_UNUSED,
                   int reason,
                   void *opaque ATTRIBUTE_UNUSED)
{
    if (reason != VIR_CONNECT_CLOSE_REASON_CLIENT)
        disconnected++;
334 335
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
/* Main Function which should be used for connecting.
 * This function properly handles keepalive settings. */
virConnectPtr
vshConnect(vshControl *ctl, const char *uri, bool readonly)
{
    virConnectPtr c = NULL;
    int interval = 5; /* Default */
    int count = 6;    /* Default */
    bool keepalive_forced = false;

    if (ctl->keepalive_interval >= 0) {
        interval = ctl->keepalive_interval;
        keepalive_forced = true;
    }
    if (ctl->keepalive_count >= 0) {
        count = ctl->keepalive_count;
        keepalive_forced = true;
    }

    c = virConnectOpenAuth(uri, virConnectAuthPtrDefault,
                           readonly ? VIR_CONNECT_RO : 0);
    if (!c)
        return NULL;

    if (interval > 0 &&
        virConnectSetKeepAlive(c, interval, count) != 0) {
        if (keepalive_forced) {
            vshError(ctl, "%s",
                     _("Cannot setup keepalive on connection "
                       "as requested, disconnecting"));
            virConnectClose(c);
            return NULL;
        }
        vshDebug(ctl, VSH_ERR_INFO, "%s",
                 _("Failed to setup keepalive on connection\n"));
    }

    return c;
}

376 377 378
/*
 * vshReconnect:
 *
L
Laine Stump 已提交
379
 * Reconnect after a disconnect from libvirtd
380 381
 *
 */
L
Laine Stump 已提交
382
static void
383 384 385 386
vshReconnect(vshControl *ctl)
{
    bool connected = false;

387 388 389
    if (ctl->conn) {
        int ret;

390
        connected = true;
391 392 393 394 395 396 397 398

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

401 402
    ctl->conn = vshConnect(ctl, ctl->name, ctl->readonly);

403
    if (!ctl->conn) {
404 405 406 407
        if (disconnected)
            vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
        else
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
408 409 410 411 412 413 414
    } 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"));
    }
415
    disconnected = 0;
416
    ctl->useGetInfo = false;
417
    ctl->useSnapshotOld = false;
418
    ctl->blockJobNoBytes = false;
419
}
420

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

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

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

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

    if (ctl->conn) {
        int ret;
457 458 459 460 461 462 463 464

        virConnectUnregisterCloseCallback(ctl->conn, vshCatchDisconnect);
        ret = virConnectClose(ctl->conn);
        if (ret < 0)
            vshError(ctl, "%s", _("Failed to disconnect from the hypervisor"));
        else if (ret > 0)
            vshError(ctl, "%s", _("One or more references were leaked after "
                                  "disconnect from the hypervisor"));
465 466 467 468 469 470 471 472 473 474 475
        ctl->conn = NULL;
    }

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

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

    ctl->useGetInfo = false;
    ctl->useSnapshotOld = false;
476
    ctl->blockJobNoBytes = false;
477 478
    ctl->readonly = ro;

479
    ctl->conn = vshConnect(ctl, ctl->name, ctl->readonly);
480

481
    if (!ctl->conn) {
482
        vshError(ctl, "%s", _("Failed to connect to the hypervisor"));
483 484 485 486 487 488
        return false;
    }

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

490
    return true;
491 492 493
}


494
#ifndef WIN32
495 496 497 498 499 500 501
static void
vshPrintRaw(vshControl *ctl, ...)
{
    va_list ap;
    char *key;

    va_start(ap, ctl);
502
    while ((key = va_arg(ap, char *)) != NULL)
503 504 505 506
        vshPrint(ctl, "%s\r\n", key);
    va_end(ap);
}

507 508 509 510 511 512 513 514 515 516 517 518 519
/**
 * 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 已提交
520
int
521 522 523 524 525 526 527
vshAskReedit(vshControl *ctl, const char *msg)
{
    int c = -1;

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

E
Eric Blake 已提交
528
    vshReportError(ctl);
529

530
    if (vshTTYMakeRaw(ctl, false) < 0)
531 532 533 534 535 536 537 538 539
        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 == '?') {
540 541 542 543 544 545 546
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
547 548 549 550 551 552
            continue;
        } else if (c == 'y' || c == 'n' || c == 'f') {
            break;
        }
    }

553
    vshTTYRestore(ctl);
554 555 556

    vshPrint(ctl, "\r\n");
    return c;
557 558
}
#else /* WIN32 */
559
int
560 561
vshAskReedit(vshControl *ctl, const char *msg ATTRIBUTE_UNUSED)
{
562 563 564 565
    vshDebug(ctl, VSH_ERR_WARNING, "%s", _("This function is not "
                                           "supported on WIN32 platform"));
    return 0;
}
566
#endif /* WIN32 */
567

E
Eric Blake 已提交
568 569
int vshStreamSink(virStreamPtr st ATTRIBUTE_UNUSED,
                  const char *bytes, size_t nbytes, void *opaque)
570 571 572 573 574 575
{
    int *fd = opaque;

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

K
Karel Zak 已提交
576 577 578 579 580 581
/* ---------------
 * Commands
 * ---------------
 */

/*
582
 * "help" command
K
Karel Zak 已提交
583
 */
584
static const vshCmdInfo info_help[] = {
585 586 587 588 589 590 591 592
    {.name = "help",
     .data = N_("print help")
    },
    {.name = "desc",
     .data = N_("Prints global help, command specific help, or help for a\n"
                "    group of related commands")
    },
    {.name = NULL}
K
Karel Zak 已提交
593 594
};

595
static const vshCmdOptDef opts_help[] = {
596 597 598 599 600
    {.name = "command",
     .type = VSH_OT_DATA,
     .help = N_("Prints global help, command specific help, or help for a group of related commands")
    },
    {.name = NULL}
K
Karel Zak 已提交
601 602
};

E
Eric Blake 已提交
603
static bool
604
cmdHelp(vshControl *ctl, const vshCmd *cmd)
605
 {
606
    const char *name = NULL;
607

608
    if (vshCommandOptString(cmd, "command", &name) <= 0) {
609
        const vshCmdGrp *grp;
610
        const vshCmdDef *def;
611

612 613 614 615 616 617
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

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

618 619 620
            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
621 622
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
623
            }
624 625 626 627

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
628
        return true;
629
    }
630

E
Eric Blake 已提交
631
    if (vshCmddefSearch(name)) {
632
        return vshCmddefHelp(ctl, name);
E
Eric Blake 已提交
633
    } else if (vshCmdGrpSearch(name)) {
634 635 636
        return vshCmdGrpHelp(ctl, name);
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
E
Eric Blake 已提交
637
        return false;
K
Karel Zak 已提交
638 639 640
    }
}

641 642 643 644 645 646 647 648 649 650 651
/* Tree listing helpers.  */

static int
vshTreePrintInternal(vshControl *ctl,
                     vshTreeLookup lookup,
                     void *opaque,
                     int num_devices,
                     int devid,
                     int lastdev,
                     bool root,
                     virBufferPtr indent)
652
{
653
    size_t i;
654 655 656
    int nextlastdev = -1;
    int ret = -1;
    const char *dev = (lookup)(devid, false, opaque);
657

658
    if (virBufferError(indent))
659 660
        goto cleanup;

661 662 663 664 665 666 667 668 669 670
    /* 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;
671 672
    }

673
    /* Determine the index of the last child device */
674
    for (i = 0; i < num_devices; i++) {
675
        const char *parent = (lookup)(i, true, opaque);
676

677 678 679
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
680

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

685 686
    /* Finally print all children */
    virBufferAddLit(indent, "  ");
687 688
    if (virBufferError(indent))
        goto cleanup;
689
    for (i = 0; i < num_devices; i++) {
690
        const char *parent = (lookup)(i, true, opaque);
691

692 693 694 695 696
        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
697
    }
J
Ján Tomko 已提交
698
    virBufferTrim(indent, "  ", -1);
699

700 701 702 703
    /* 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));
704

J
Ján Tomko 已提交
705 706
    if (!root)
        virBufferTrim(indent, NULL, 2);
707
    ret = 0;
708
 cleanup:
709 710 711
    return ret;
}

E
Eric Blake 已提交
712
int
713 714
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
715
{
716 717
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;
718

719 720 721 722 723
    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
724
    return ret;
725
}
726

727
/* Common code for the edit / net-edit / pool-edit functions which follow. */
E
Eric Blake 已提交
728
char *
E
Eric Blake 已提交
729
vshEditWriteToTempFile(vshControl *ctl, const char *doc)
730 731 732 733
{
    char *ret;
    const char *tmpdir;
    int fd;
734
    char ebuf[1024];
735

736
    tmpdir = virGetEnvBlockSUID("TMPDIR");
737
    if (!tmpdir) tmpdir = "/tmp";
738 739 740 741
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
742
    fd = mkostemps(ret, 4, O_CLOEXEC);
743
    if (fd == -1) {
744
        vshError(ctl, _("mkostemps: failed to create temporary file: %s"),
745
                 virStrerror(errno, ebuf, sizeof(ebuf)));
746
        VIR_FREE(ret);
747 748 749
        return NULL;
    }

750
    if (safewrite(fd, doc, strlen(doc)) == -1) {
751
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
752
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
S
Stefan Berger 已提交
753
        VIR_FORCE_CLOSE(fd);
754
        unlink(ret);
755
        VIR_FREE(ret);
756 757
        return NULL;
    }
S
Stefan Berger 已提交
758
    if (VIR_CLOSE(fd) < 0) {
759
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
760
                 ret, virStrerror(errno, ebuf, sizeof(ebuf)));
761
        unlink(ret);
762
        VIR_FREE(ret);
763 764 765 766 767 768 769 770 771 772 773
        return NULL;
    }

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

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

E
Eric Blake 已提交
774
int
E
Eric Blake 已提交
775
vshEditFile(vshControl *ctl, const char *filename)
776 777
{
    const char *editor;
E
Eric Blake 已提交
778 779 780 781
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;
782

783
    editor = virGetEnvBlockSUID("VISUAL");
E
Eric Blake 已提交
784
    if (!editor)
785
        editor = virGetEnvBlockSUID("EDITOR");
E
Eric Blake 已提交
786
    if (!editor)
787
        editor = DEFAULT_EDITOR;
788

789 790 791 792 793
    /* 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 已提交
794 795
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
796
     */
797 798
    if (strspn(editor, ACCEPTED_CHARS) != strlen(editor)) {
        if (strspn(filename, ACCEPTED_CHARS) != strlen(filename)) {
E
Eric Blake 已提交
799 800 801 802 803 804 805 806 807 808
            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);
809 810
    }

E
Eric Blake 已提交
811 812 813 814 815
    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
E
Eric Blake 已提交
816
        vshReportError(ctl);
E
Eric Blake 已提交
817
        goto cleanup;
818
    }
E
Eric Blake 已提交
819
    ret = 0;
820

821
 cleanup:
E
Eric Blake 已提交
822 823
    virCommandFree(cmd);
    return ret;
824 825
}

E
Eric Blake 已提交
826
char *
E
Eric Blake 已提交
827
vshEditReadBackFile(vshControl *ctl, const char *filename)
828 829
{
    char *ret;
830
    char ebuf[1024];
831

E
Eric Blake 已提交
832
    if (virFileReadAll(filename, VSH_MAX_XML_FILE, &ret) == -1) {
833
        vshError(ctl,
834
                 _("%s: failed to read temporary file: %s"),
835
                 filename, virStrerror(errno, ebuf, sizeof(ebuf)));
836 837 838 839 840
        return NULL;
    }
    return ret;
}

841

P
Paolo Bonzini 已提交
842 843 844 845
/*
 * "cd" command
 */
static const vshCmdInfo info_cd[] = {
846 847 848 849 850 851 852
    {.name = "help",
     .data = N_("change the current directory")
    },
    {.name = "desc",
     .data = N_("Change the current directory.")
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
853 854 855
};

static const vshCmdOptDef opts_cd[] = {
856 857 858 859 860
    {.name = "dir",
     .type = VSH_OT_DATA,
     .help = N_("directory to switch to (default: home or else root)")
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
861 862
};

E
Eric Blake 已提交
863
static bool
864
cmdCd(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
865
{
866
    const char *dir = NULL;
867
    char *dir_malloced = NULL;
E
Eric Blake 已提交
868
    bool ret = true;
869
    char ebuf[1024];
P
Paolo Bonzini 已提交
870 871

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

876
    if (vshCommandOptString(cmd, "dir", &dir) <= 0)
877
        dir = dir_malloced = virGetUserDirectory();
P
Paolo Bonzini 已提交
878 879 880
    if (!dir)
        dir = "/";

P
Phil Petty 已提交
881
    if (chdir(dir) == -1) {
882 883
        vshError(ctl, _("cd: %s: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)), dir);
E
Eric Blake 已提交
884
        ret = false;
P
Paolo Bonzini 已提交
885 886
    }

887
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
888
    return ret;
P
Paolo Bonzini 已提交
889 890 891 892 893 894
}

/*
 * "pwd" command
 */
static const vshCmdInfo info_pwd[] = {
895 896 897 898 899 900 901
    {.name = "help",
     .data = N_("print the current directory")
    },
    {.name = "desc",
     .data = N_("Print the current directory.")
    },
    {.name = NULL}
P
Paolo Bonzini 已提交
902 903
};

E
Eric Blake 已提交
904
static bool
P
Paolo Bonzini 已提交
905 906 907
cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cwd;
908
    bool ret = true;
909
    char ebuf[1024];
P
Paolo Bonzini 已提交
910

911 912
    cwd = getcwd(NULL, 0);
    if (!cwd) {
913
        vshError(ctl, _("pwd: cannot get current directory: %s"),
914
                 virStrerror(errno, ebuf, sizeof(ebuf)));
915 916
        ret = false;
    } else {
917
        vshPrint(ctl, _("%s\n"), cwd);
918 919
        VIR_FREE(cwd);
    }
P
Paolo Bonzini 已提交
920

921
    return ret;
P
Paolo Bonzini 已提交
922 923
}

E
Eric Blake 已提交
924 925 926 927
/*
 * "echo" command
 */
static const vshCmdInfo info_echo[] = {
928 929 930 931 932 933 934
    {.name = "help",
     .data = N_("echo arguments")
    },
    {.name = "desc",
     .data = N_("Echo back arguments, possibly with quoting.")
    },
    {.name = NULL}
E
Eric Blake 已提交
935 936 937
};

static const vshCmdOptDef opts_echo[] = {
938 939 940 941 942 943 944 945 946 947 948 949
    {.name = "shell",
     .type = VSH_OT_BOOL,
     .help = N_("escape for shell use")
    },
    {.name = "xml",
     .type = VSH_OT_BOOL,
     .help = N_("escape for XML use")
    },
    {.name = "str",
     .type = VSH_OT_ALIAS,
     .help = "string"
    },
950 951 952 953
    {.name = "hi",
     .type = VSH_OT_ALIAS,
     .help = "string=hello"
    },
954 955 956 957 958
    {.name = "string",
     .type = VSH_OT_ARGV,
     .help = N_("arguments to echo")
    },
    {.name = NULL}
E
Eric Blake 已提交
959 960 961 962 963
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
E
Eric Blake 已提交
964
static bool
965
cmdEcho(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
966 967 968 969
{
    bool shell = false;
    bool xml = false;
    int count = 0;
970
    const vshCmdOpt *opt = NULL;
E
Eric Blake 已提交
971 972 973 974 975 976 977 978
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

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

979
    while ((opt = vshCommandOptArgv(cmd, opt))) {
980 981
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
982

983
        arg = opt->data;
984

E
Eric Blake 已提交
985 986
        if (count)
            virBufferAddChar(&buf, ' ');
987

E
Eric Blake 已提交
988
        if (xml) {
989
            virBufferEscapeString(&xmlbuf, "%s", arg);
990
            if (virBufferError(&xmlbuf)) {
991 992
                vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
                return false;
E
Eric Blake 已提交
993
            }
994 995 996
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
E
Eric Blake 已提交
997
        }
998 999 1000 1001 1002

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
E
Eric Blake 已提交
1003
        count++;
1004
        VIR_FREE(str);
E
Eric Blake 已提交
1005 1006 1007 1008
    }

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
1009
        return false;
E
Eric Blake 已提交
1010 1011 1012 1013 1014
    }
    arg = virBufferContentAndReset(&buf);
    if (arg)
        vshPrint(ctl, "%s", arg);
    VIR_FREE(arg);
E
Eric Blake 已提交
1015
    return true;
E
Eric Blake 已提交
1016 1017
}

K
Karel Zak 已提交
1018 1019 1020
/*
 * "quit" command
 */
1021
static const vshCmdInfo info_quit[] = {
1022 1023 1024 1025 1026 1027 1028
    {.name = "help",
     .data = N_("quit this interactive terminal")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
K
Karel Zak 已提交
1029 1030
};

E
Eric Blake 已提交
1031
static bool
1032
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
1033
{
E
Eric Blake 已提交
1034 1035
    ctl->imode = false;
    return true;
K
Karel Zak 已提交
1036 1037
}

1038 1039 1040 1041
/* ---------------
 * Utils for work with command definition
 * ---------------
 */
E
Eric Blake 已提交
1042
const char *
1043 1044 1045
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
{
    const vshCmdInfo *info;
1046

1047 1048 1049 1050 1051 1052
    for (info = cmd->info; info && info->name; info++) {
        if (STREQ(info->name, name))
            return info->data;
    }
    return NULL;
}
1053

1054 1055 1056 1057 1058
/* 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)
{
1059
    size_t i;
1060
    bool optional = false;
1061

1062 1063
    *opts_need_arg = 0;
    *opts_required = 0;
1064

1065 1066
    if (!cmd->opts)
        return 0;
1067

1068 1069
    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
1070 1071 1072 1073

        if (i > 31)
            return -1; /* too many options */
        if (opt->type == VSH_OT_BOOL) {
1074
            optional = true;
E
Eric Blake 已提交
1075
            if (opt->flags & VSH_OFLAG_REQ)
1076 1077 1078
                return -1; /* bool options can't be mandatory */
            continue;
        }
E
Eric Blake 已提交
1079
        if (opt->type == VSH_OT_ALIAS) {
1080
            size_t j;
1081 1082 1083
            char *name = (char *)opt->help; /* cast away const */
            char *p;

E
Eric Blake 已提交
1084 1085
            if (opt->flags || !opt->help)
                return -1; /* alias options are tracked by the original name */
1086 1087 1088
            if ((p = strchr(name, '=')) &&
                VIR_STRNDUP(name, name, p - name) < 0)
                return -1;
E
Eric Blake 已提交
1089
            for (j = i + 1; cmd->opts[j].name; j++) {
1090 1091
                if (STREQ(name, cmd->opts[j].name) &&
                    cmd->opts[j].type != VSH_OT_ALIAS)
E
Eric Blake 已提交
1092 1093
                    break;
            }
1094 1095 1096 1097 1098 1099
            if (name != opt->help) {
                VIR_FREE(name);
                /* If alias comes with value, replacement must not be bool */
                if (cmd->opts[j].type == VSH_OT_BOOL)
                    return -1;
            }
E
Eric Blake 已提交
1100 1101 1102 1103
            if (!cmd->opts[j].name)
                return -1; /* alias option must map to a later option name */
            continue;
        }
E
Eric Blake 已提交
1104 1105
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
L
Lai Jiangshan 已提交
1106
                *opts_required |= 1 << i;
1107 1108
            else
                optional = true;
L
Lai Jiangshan 已提交
1109 1110 1111
            continue;
        }

1112
        *opts_need_arg |= 1 << i;
E
Eric Blake 已提交
1113
        if (opt->flags & VSH_OFLAG_REQ) {
1114
            if (optional && opt->type != VSH_OT_ARGV)
1115 1116 1117 1118 1119
                return -1; /* mandatory options must be listed first */
            *opts_required |= 1 << i;
        } else {
            optional = true;
        }
1120 1121 1122

        if (opt->type == VSH_OT_ARGV && cmd->opts[i + 1].name)
            return -1; /* argv option must be listed last */
1123 1124 1125 1126
    }
    return 0;
}

1127 1128 1129 1130 1131
static vshCmdOptDef helpopt = {
    .name = "help",
    .type = VSH_OT_BOOL,
    .help = N_("print help for this function")
};
1132
static const vshCmdOptDef *
1133
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
1134
                   uint32_t *opts_seen, int *opt_index, char **optstr)
1135
{
1136
    size_t i;
1137 1138
    const vshCmdOptDef *ret = NULL;
    char *alias = NULL;
1139

1140
    if (STREQ(name, helpopt.name))
1141 1142
        return &helpopt;

1143 1144
    for (i = 0; cmd->opts && cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
1145

1146
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
1147
            if (opt->type == VSH_OT_ALIAS) {
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
                char *value;

                /* Two types of replacements:
                   opt->help = "string": straight replacement of name
                   opt->help = "string=value": treat boolean flag as
                   alias of option and its default value */
                sa_assert(!alias);
                if (VIR_STRDUP(alias, opt->help) < 0)
                    goto cleanup;
                name = alias;
                if ((value = strchr(name, '='))) {
                    *value = '\0';
                    if (*optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                 opt->name);
                        goto cleanup;
                    }
                    if (VIR_STRDUP(*optstr, value + 1) < 0)
                        goto cleanup;
                }
E
Eric Blake 已提交
1168 1169
                continue;
            }
1170
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
1171
                vshError(ctl, _("option --%s already seen"), name);
1172
                goto cleanup;
1173
            }
1174 1175
            *opts_seen |= 1 << i;
            *opt_index = i;
1176 1177
            ret = opt;
            goto cleanup;
1178 1179 1180
        }
    }

1181 1182 1183 1184
    if (STRNEQ(cmd->name, "help")) {
        vshError(ctl, _("command '%s' doesn't support option --%s"),
                 cmd->name, name);
    }
1185
 cleanup:
1186 1187
    VIR_FREE(alias);
    return ret;
K
Karel Zak 已提交
1188 1189
}

1190
static const vshCmdOptDef *
1191 1192
vshCmddefGetData(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                 uint32_t *opts_seen)
1193
{
1194
    size_t i;
1195
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
1196

1197 1198 1199 1200
    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
E
Eric Blake 已提交
1201
    i = ffs(*opts_need_arg) - 1;
1202
    opt = &cmd->opts[i];
1203
    if (opt->type != VSH_OT_ARGV)
1204
        *opts_need_arg &= ~(1 << i);
1205
    *opts_seen |= 1 << i;
1206
    return opt;
K
Karel Zak 已提交
1207 1208
}

1209 1210 1211
/*
 * Checks for required options
 */
1212
static int
1213 1214
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint32_t opts_required,
                    uint32_t opts_seen)
1215
{
1216
    const vshCmdDef *def = cmd->def;
1217
    size_t i;
1218 1219 1220 1221 1222 1223 1224 1225

    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];
1226

1227
            vshError(ctl,
1228
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
1229 1230 1231
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
1232 1233
        }
    }
1234
    return -1;
1235 1236
}

E
Eric Blake 已提交
1237
const vshCmdDef *
1238 1239
vshCmddefSearch(const char *cmdname)
{
1240
    const vshCmdGrp *g;
1241
    const vshCmdDef *c;
1242

1243 1244
    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
1245
            if (STREQ(c->name, cmdname))
1246 1247 1248 1249
                return c;
        }
    }

K
Karel Zak 已提交
1250 1251 1252
    return NULL;
}

E
Eric Blake 已提交
1253
const vshCmdGrp *
1254 1255 1256 1257 1258
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
1259
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
1260 1261 1262 1263 1264 1265
            return g;
    }

    return NULL;
}

E
Eric Blake 已提交
1266
bool
1267 1268 1269 1270 1271 1272 1273
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 已提交
1274
        return false;
1275 1276 1277 1278 1279
    } else {
        vshPrint(ctl, _(" %s (help keyword '%s'):\n"), grp->name,
                 grp->keyword);

        for (cmd = grp->commands; cmd->name; cmd++) {
1280 1281
            if (cmd->flags & VSH_CMD_FLAG_ALIAS)
                continue;
1282 1283 1284 1285 1286
            vshPrint(ctl, "    %-30s %s\n", cmd->name,
                     _(vshCmddefGetInfo(cmd, "help")));
        }
    }

E
Eric Blake 已提交
1287
    return true;
1288 1289
}

E
Eric Blake 已提交
1290
bool
1291
vshCmddefHelp(vshControl *ctl, const char *cmdname)
1292
{
1293
    const vshCmdDef *def = vshCmddefSearch(cmdname);
1294

K
Karel Zak 已提交
1295
    if (!def) {
1296
        vshError(ctl, _("command '%s' doesn't exist"), cmdname);
E
Eric Blake 已提交
1297
        return false;
1298
    } else {
E
Eric Blake 已提交
1299 1300
        /* Don't translate desc if it is "".  */
        const char *desc = vshCmddefGetInfo(def, "desc");
E
Eric Blake 已提交
1301
        const char *help = _(vshCmddefGetInfo(def, "help"));
1302
        char buf[256];
1303 1304
        uint32_t opts_need_arg;
        uint32_t opts_required;
1305
        bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
1306 1307 1308 1309

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

1313
        fputs(_("  NAME\n"), stdout);
1314 1315
        fprintf(stdout, "    %s - %s\n", def->name, help);

1316 1317 1318 1319 1320
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
1321
                const char *fmt = "%s";
1322 1323
                switch (opt->type) {
                case VSH_OT_BOOL:
1324
                    fmt = "[--%s]";
1325 1326
                    break;
                case VSH_OT_INT:
E
Eric Blake 已提交
1327
                    /* xgettext:c-format */
E
Eric Blake 已提交
1328
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
1329
                           : _("[--%s <number>]"));
1330 1331
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1332 1333
                    break;
                case VSH_OT_STRING:
E
Eric Blake 已提交
1334 1335
                    /* xgettext:c-format */
                    fmt = _("[--%s <string>]");
1336 1337
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1338 1339
                    break;
                case VSH_OT_DATA:
E
Eric Blake 已提交
1340
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
1341 1342
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1343 1344 1345
                    break;
                case VSH_OT_ARGV:
                    /* xgettext:c-format */
1346 1347 1348 1349 1350 1351 1352 1353
                    if (shortopt) {
                        fmt = (opt->flags & VSH_OFLAG_REQ)
                            ? _("{[--%s] <string>}...")
                            : _("[[--%s] <string>]...");
                    } else {
                        fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                            : _("[<%s>]...");
                    }
1354
                    break;
E
Eric Blake 已提交
1355 1356 1357
                case VSH_OT_ALIAS:
                    /* aliases are intentionally undocumented */
                    continue;
1358
                }
1359
                fputc(' ', stdout);
E
Eric Blake 已提交
1360
                fprintf(stdout, fmt, opt->name);
1361
            }
K
Karel Zak 已提交
1362
        }
1363 1364 1365
        fputc('\n', stdout);

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

1371
        if (def->opts && def->opts->name) {
1372
            const vshCmdOptDef *opt;
1373
            fputs(_("\n  OPTIONS\n"), stdout);
1374
            for (opt = def->opts; opt->name; opt++) {
1375 1376
                switch (opt->type) {
                case VSH_OT_BOOL:
K
Karel Zak 已提交
1377
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1378 1379
                    break;
                case VSH_OT_INT:
1380
                    snprintf(buf, sizeof(buf),
E
Eric Blake 已提交
1381
                             (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
1382
                             : _("--%s <number>"), opt->name);
1383 1384
                    break;
                case VSH_OT_STRING:
1385
                    /* OT_STRING should never be VSH_OFLAG_REQ */
1386 1387 1388 1389 1390 1391
                    if (opt->flags & VSH_OFLAG_REQ) {
                        vshError(ctl,
                                 _("internal error: bad options in command: '%s'"),
                                 def->name);
                        return false;
                    }
1392
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
1393 1394
                    break;
                case VSH_OT_DATA:
1395 1396
                    snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                             opt->name);
1397 1398
                    break;
                case VSH_OT_ARGV:
1399 1400 1401
                    snprintf(buf, sizeof(buf),
                             shortopt ? _("[--%s] <string>") : _("<%s>"),
                             opt->name);
1402
                    break;
E
Eric Blake 已提交
1403 1404
                case VSH_OT_ALIAS:
                    continue;
1405
                }
1406

E
Eric Blake 已提交
1407
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
1408
            }
K
Karel Zak 已提交
1409 1410 1411
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
1412
    return true;
K
Karel Zak 已提交
1413 1414 1415 1416 1417 1418
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1419 1420 1421
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1422 1423
    vshCmdOpt *a = arg;

1424
    while (a) {
K
Karel Zak 已提交
1425
        vshCmdOpt *tmp = a;
1426

K
Karel Zak 已提交
1427 1428
        a = a->next;

1429 1430
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
1431 1432 1433 1434
    }
}

static void
1435
vshCommandFree(vshCmd *cmd)
1436
{
K
Karel Zak 已提交
1437 1438
    vshCmd *c = cmd;

1439
    while (c) {
K
Karel Zak 已提交
1440
        vshCmd *tmp = c;
1441

K
Karel Zak 已提交
1442 1443 1444 1445
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
1446
        VIR_FREE(tmp);
K
Karel Zak 已提交
1447 1448 1449
    }
}

E
Eric Blake 已提交
1450 1451 1452 1453 1454
/**
 * vshCommandOpt:
 * @cmd: parsed command line to search
 * @name: option name to search for
 * @opt: result of the search
1455
 * @needData: true if option must be non-boolean
E
Eric Blake 已提交
1456 1457 1458 1459
 *
 * 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
1460 1461 1462
 * the option is required but not present, and assert if NAME is not
 * valid (which indicates a programming error).  No error messages are
 * issued if a value is returned.
K
Karel Zak 已提交
1463
 */
1464 1465 1466
static int
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt,
              bool needData)
1467
{
E
Eric Blake 已提交
1468 1469
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
    int ret = 0;

    /* See if option is valid and/or required.  */
    *opt = NULL;
    while (valid) {
        assert(valid->name);
        if (STREQ(name, valid->name))
            break;
        valid++;
    }
    assert(!needData || valid->type != VSH_OT_BOOL);
    if (valid->flags & VSH_OFLAG_REQ)
        ret = -1;
1483

E
Eric Blake 已提交
1484 1485 1486 1487
    /* See if option is present on command line.  */
    while (candidate) {
        if (STREQ(candidate->def->name, name)) {
            *opt = candidate;
1488 1489
            ret = 1;
            break;
E
Eric Blake 已提交
1490 1491
        }
        candidate = candidate->next;
K
Karel Zak 已提交
1492
    }
1493
    return ret;
K
Karel Zak 已提交
1494 1495
}

E
Eric Blake 已提交
1496 1497
/**
 * vshCommandOptInt:
1498 1499 1500 1501 1502 1503 1504
 * @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 已提交
1505
 * 0 if option not found and not required (@value untouched)
1506
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
1507
 */
E
Eric Blake 已提交
1508
int
1509
vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
1510
{
E
Eric Blake 已提交
1511 1512
    vshCmdOpt *arg;
    int ret;
1513

1514
    ret = vshCommandOpt(cmd, name, &arg, true);
E
Eric Blake 已提交
1515 1516 1517
    if (ret <= 0)
        return ret;

E
Eric Blake 已提交
1518 1519 1520
    if (virStrToLong_i(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
K
Karel Zak 已提交
1521 1522
}

1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
static int
vshCommandOptUIntInternal(const vshCmd *cmd,
                          const char *name,
                          unsigned int *value,
                          bool wrap)
{
    vshCmdOpt *arg;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;

    if (wrap) {
        if (virStrToLong_ui(arg->data, NULL, 10, value) < 0)
            return -1;
    } else {
        if (virStrToLong_uip(arg->data, NULL, 10, value) < 0)
            return -1;
    }

    return 1;
}
1545

E
Eric Blake 已提交
1546 1547 1548 1549 1550 1551
/**
 * vshCommandOptUInt:
 * @cmd command reference
 * @name option name
 * @value result
 *
1552
 * Convert option to unsigned int, reject negative numbers
1553 1554
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1555
int
1556 1557
vshCommandOptUInt(const vshCmd *cmd, const char *name, unsigned int *value)
{
1558 1559
    return vshCommandOptUIntInternal(cmd, name, value, false);
}
E
Eric Blake 已提交
1560

1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
/**
 * vshCommandOptUIntWrap:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to unsigned int, wraps negative numbers to positive
 * See vshCommandOptInt()
 */
int
vshCommandOptUIntWrap(const vshCmd *cmd, const char *name, unsigned int *value)
{
    return vshCommandOptUIntInternal(cmd, name, value, true);
1574 1575
}

1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
static int
vshCommandOptULInternal(const vshCmd *cmd,
                        const char *name,
                        unsigned long *value,
                        bool wrap)
{
    vshCmdOpt *arg;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;

    if (wrap) {
        if (virStrToLong_ul(arg->data, NULL, 10, value) < 0)
            return -1;
    } else {
        if (virStrToLong_ulp(arg->data, NULL, 10, value) < 0)
            return -1;
    }

    return 1;
}
1598

1599
/*
E
Eric Blake 已提交
1600 1601 1602 1603 1604
 * vshCommandOptUL:
 * @cmd command reference
 * @name option name
 * @value result
 *
1605 1606 1607
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1608
int
1609
vshCommandOptUL(const vshCmd *cmd, const char *name, unsigned long *value)
1610
{
1611 1612
    return vshCommandOptULInternal(cmd, name, value, false);
}
E
Eric Blake 已提交
1613

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
/**
 * vshCommandOptULWrap:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to unsigned long, wraps negative numbers to positive
 * See vshCommandOptInt()
 */
int
vshCommandOptULWrap(const vshCmd *cmd, const char *name, unsigned long *value)
{
    return vshCommandOptULInternal(cmd, name, value, true);
1627 1628
}

E
Eric Blake 已提交
1629 1630 1631 1632 1633 1634
/**
 * vshCommandOptString:
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
1635
 * Returns option as STRING
E
Eric Blake 已提交
1636 1637 1638 1639
 * 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 已提交
1640
 */
E
Eric Blake 已提交
1641
int
1642
vshCommandOptString(const vshCmd *cmd, const char *name, const char **value)
1643
{
E
Eric Blake 已提交
1644 1645 1646
    vshCmdOpt *arg;
    int ret;

1647
    ret = vshCommandOpt(cmd, name, &arg, true);
E
Eric Blake 已提交
1648 1649
    if (ret <= 0)
        return ret;
1650

1651
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK))
E
Eric Blake 已提交
1652 1653 1654
        return -1;
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
1655 1656
}

1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
/**
 * vshCommandOptStringReq:
 * @ctl virsh control structure
 * @cmd command structure
 * @name option name
 * @value result (updated to NULL or the option argument)
 *
 * Gets a option argument as string.
 *
 * Returns 0 on success or when the option is not present and not
 * required, *value is set to the option argument. On error -1 is
 * returned and error message printed.
 */
int
vshCommandOptStringReq(vshControl *ctl,
                       const vshCmd *cmd,
                       const char *name,
                       const char **value)
{
    vshCmdOpt *arg;
    int ret;
    const char *error = NULL;

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

1683
    ret = vshCommandOpt(cmd, name, &arg, true);
1684 1685 1686 1687 1688 1689
    /* option is not required and not present */
    if (ret == 0)
        return 0;
    /* this should not be propagated here, just to be sure */
    if (ret == -1)
        error = N_("Mandatory option not present");
1690
    else if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK))
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
        error = N_("Option argument is empty");

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

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

E
Eric Blake 已提交
1702 1703 1704 1705 1706 1707
/**
 * vshCommandOptLongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
1708
 * Returns option as long long
1709
 * See vshCommandOptInt()
1710
 */
E
Eric Blake 已提交
1711
int
1712 1713
vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                      long long *value)
1714
{
E
Eric Blake 已提交
1715 1716
    vshCmdOpt *arg;
    int ret;
1717

1718
    ret = vshCommandOpt(cmd, name, &arg, true);
E
Eric Blake 已提交
1719 1720 1721
    if (ret <= 0)
        return ret;

E
Eric Blake 已提交
1722 1723 1724
    if (virStrToLong_ll(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1725 1726
}

1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
static int
vshCommandOptULongLongInternal(const vshCmd *cmd,
                               const char *name,
                               unsigned long long *value,
                               bool wrap)
{
    vshCmdOpt *arg;
    int ret;

    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
        return ret;

    if (wrap) {
        if (virStrToLong_ull(arg->data, NULL, 10, value) < 0)
            return -1;
    } else {
        if (virStrToLong_ullp(arg->data, NULL, 10, value) < 0)
            return -1;
    }

    return 1;
}

E
Eric Blake 已提交
1750 1751 1752 1753 1754 1755
/**
 * vshCommandOptULongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
1756
 * Returns option as long long, rejects negative numbers
E
Eric Blake 已提交
1757 1758
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1759
int
1760 1761 1762
vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                       unsigned long long *value)
{
1763
    return vshCommandOptULongLongInternal(cmd, name, value, false);
1764 1765
}

1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
/**
 * vshCommandOptULongLongWrap:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long, wraps negative numbers to positive
 * See vshCommandOptInt()
 */
int
vshCommandOptULongLongWrap(const vshCmd *cmd, const char *name,
                       unsigned long long *value)
{
    return vshCommandOptULongLongInternal(cmd, name, value, true);
}
1781

E
Eric Blake 已提交
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
/**
 * 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 已提交
1793
int
E
Eric Blake 已提交
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
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 已提交
1812 1813 1814 1815 1816 1817 1818 1819 1820
/**
 * 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 已提交
1821
 */
E
Eric Blake 已提交
1822
bool
1823
vshCommandOptBool(const vshCmd *cmd, const char *name)
1824
{
E
Eric Blake 已提交
1825 1826
    vshCmdOpt *dummy;

1827
    return vshCommandOpt(cmd, name, &dummy, false) == 1;
K
Karel Zak 已提交
1828 1829
}

E
Eric Blake 已提交
1830 1831 1832 1833 1834
/**
 * vshCommandOptArgv:
 * @cmd command reference
 * @opt starting point for the search
 *
1835 1836
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
1837
 *
1838
 * Requires that a VSH_OT_ARGV option be last in the
1839 1840
 * list of supported options in CMD->def->opts.
 */
E
Eric Blake 已提交
1841
const vshCmdOpt *
1842
vshCommandOptArgv(const vshCmd *cmd, const vshCmdOpt *opt)
1843
{
1844
    opt = opt ? opt->next : cmd->opts;
1845 1846

    while (opt) {
1847
        if (opt->def->type == VSH_OT_ARGV)
1848
            return opt;
1849 1850 1851 1852 1853
        opt = opt->next;
    }
    return NULL;
}

J
Jim Meyering 已提交
1854 1855 1856
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
1857 1858
bool
vshCmdHasOption(vshControl *ctl, const vshCmd *cmd, const char *optname)
J
Jim Meyering 已提交
1859 1860 1861 1862 1863 1864
{
    /* 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) {
1865
        if (STREQ(opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
J
Jim Meyering 已提交
1866 1867 1868 1869 1870 1871
            found = true;
            break;
        }
    }

    if (!found)
1872
        vshError(ctl, _("internal error: virsh %s: no %s VSH_OT_DATA option"),
J
Jim Meyering 已提交
1873 1874 1875
                 cmd->def->name, optname);
    return found;
}
1876

1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
/* Parse an optional --timeout parameter in seconds, but store the
 * value of the timeout in milliseconds.  Return -1 on error, 0 if
 * no timeout was requested, and 1 if timeout was set.  */
int
vshCommandOptTimeoutToMs(vshControl *ctl, const vshCmd *cmd, int *timeout)
{
    int rv = vshCommandOptInt(cmd, "timeout", timeout);

    if (rv < 0 || (rv > 0 && *timeout < 1)) {
        vshError(ctl, "%s", _("invalid timeout"));
        return -1;
    }
    if (rv > 0) {
        /* Ensure that we can multiply by 1000 without overflowing. */
        if (*timeout > INT_MAX / 1000) {
            vshError(ctl, "%s", _("timeout is too big"));
            return -1;
        }
        *timeout *= 1000;
    }
    return rv;
}


1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
static bool
vshConnectionUsability(vshControl *ctl, virConnectPtr conn)
{
    if (!conn ||
        virConnectIsAlive(conn) == 0) {
        vshError(ctl, "%s", _("no valid connection"));
        return false;
    }

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

    return true;
}

K
Karel Zak 已提交
1918 1919 1920
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
1921
static bool
1922
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
1923
{
E
Eric Blake 已提交
1924
    bool ret = true;
1925 1926

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

1930 1931
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
1932 1933
            vshReconnect(ctl);

1934 1935 1936
        if (enable_timing)
            GETTIMEOFDAY(&before);

1937 1938 1939 1940 1941 1942 1943
        if ((cmd->def->flags & VSH_CMD_FLAG_NOCONNECT) ||
            vshConnectionUsability(ctl, ctl->conn)) {
            ret = cmd->def->handler(ctl, cmd);
        } else {
            /* connection is not usable, return error */
            ret = false;
        }
1944

1945 1946 1947
        if (enable_timing)
            GETTIMEOFDAY(&after);

1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
        /* 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++;

1958
        if (!ret)
E
Eric Blake 已提交
1959
            vshReportError(ctl);
J
John Levon 已提交
1960

1961 1962
        if (STREQ(cmd->def->name, "quit") ||
            STREQ(cmd->def->name, "exit"))        /* hack ... */
K
Karel Zak 已提交
1963 1964
            return ret;

E
Eric Blake 已提交
1965
        if (enable_timing) {
1966
            double diff_ms = (((after.tv_sec - before.tv_sec) * 1000.0) +
E
Eric Blake 已提交
1967 1968 1969 1970
                              ((after.tv_usec - before.tv_usec) / 1000.0));

            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"), diff_ms);
        } else {
K
Karel Zak 已提交
1971
            vshPrintExtra(ctl, "\n");
E
Eric Blake 已提交
1972
        }
K
Karel Zak 已提交
1973 1974 1975 1976 1977 1978
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
1979
 * Command parsing
K
Karel Zak 已提交
1980 1981 1982
 * ---------------
 */

1983 1984 1985 1986 1987 1988 1989
typedef enum {
    VSH_TK_ERROR, /* Failed to parse a token */
    VSH_TK_ARG, /* Arbitrary argument, might be option or empty */
    VSH_TK_SUBCMD_END, /* Separation between commands */
    VSH_TK_END /* No more commands */
} vshCommandToken;

E
Eric Blake 已提交
1990 1991 1992 1993
typedef struct _vshCommandParser vshCommandParser;
struct _vshCommandParser {
    vshCommandToken(*getNextArg)(vshControl *, vshCommandParser *,
                                 char **);
L
Lai Jiangshan 已提交
1994
    /* vshCommandStringGetArg() */
1995
    char *pos;
L
Lai Jiangshan 已提交
1996 1997 1998
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
E
Eric Blake 已提交
1999
};
2000

E
Eric Blake 已提交
2001
static bool
2002
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
2003
{
K
Karel Zak 已提交
2004 2005 2006
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
2007

K
Karel Zak 已提交
2008 2009 2010 2011
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
2012

2013
    while (1) {
K
Karel Zak 已提交
2014
        vshCmdOpt *last = NULL;
2015
        const vshCmdDef *cmd = NULL;
2016
        vshCommandToken tk;
L
Lai Jiangshan 已提交
2017
        bool data_only = false;
2018 2019 2020
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
2021

K
Karel Zak 已提交
2022
        first = NULL;
2023

2024
        while (1) {
2025
            const vshCmdOptDef *opt = NULL;
2026

K
Karel Zak 已提交
2027
            tkdata = NULL;
2028
            tk = parser->getNextArg(ctl, parser, &tkdata);
2029 2030

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2031
                goto syntaxError;
H
Hu Tao 已提交
2032 2033
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
2034
                break;
H
Hu Tao 已提交
2035
            }
2036 2037

            if (cmd == NULL) {
K
Karel Zak 已提交
2038 2039
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
2040
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
2041
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
2042
                }
2043 2044 2045 2046 2047 2048 2049
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
2050
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
2051 2052 2053 2054
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
2055
                char *optstr = strchr(tkdata + 2, '=');
C
Cole Robinson 已提交
2056
                int opt_index = 0;
2057

2058 2059 2060 2061
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
2062
                /* Special case 'help' to ignore all spurious options */
2063
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
2064 2065
                                               &opts_seen, &opt_index,
                                               &optstr))) {
2066
                    VIR_FREE(optstr);
2067 2068
                    if (STREQ(cmd->name, "help"))
                        continue;
K
Karel Zak 已提交
2069 2070
                    goto syntaxError;
                }
2071
                VIR_FREE(tkdata);
K
Karel Zak 已提交
2072 2073 2074

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
2075 2076 2077
                    if (optstr)
                        tkdata = optstr;
                    else
2078
                        tk = parser->getNextArg(ctl, parser, &tkdata);
2079
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2080
                        goto syntaxError;
2081
                    if (tk != VSH_TK_ARG) {
2082
                        vshError(ctl,
2083
                                 _("expected syntax: --%s <%s>"),
2084 2085
                                 opt->name,
                                 opt->type ==
2086
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
2087 2088
                        goto syntaxError;
                    }
2089 2090
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
2091 2092 2093 2094
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
2095
                                 opt->name);
2096 2097 2098
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
2099
                }
L
Lai Jiangshan 已提交
2100 2101 2102 2103
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
2104
            } else {
2105
 get_data:
2106
                /* Special case 'help' to ignore spurious data */
2107
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
2108 2109
                                             &opts_seen)) &&
                     STRNEQ(cmd->name, "help")) {
2110
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
2111 2112 2113 2114 2115
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
2116
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
2117

K
Karel Zak 已提交
2118 2119 2120 2121
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
2122

K
Karel Zak 已提交
2123 2124 2125 2126 2127
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
2128

2129
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
2130 2131
                         cmd->name,
                         opt->name,
2132 2133
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
2134 2135
            }
        }
2136

D
Daniel Veillard 已提交
2137
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
2138
        if (cmd) {
2139
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
            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;
            }
2159

K
Karel Zak 已提交
2160 2161 2162 2163
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

2164
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
2165
                VIR_FREE(c);
2166
                goto syntaxError;
2167
            }
2168

K
Karel Zak 已提交
2169 2170 2171 2172 2173 2174
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
2175 2176 2177

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
2178
    }
2179

E
Eric Blake 已提交
2180
    return true;
K
Karel Zak 已提交
2181

2182
 syntaxError:
2183
    if (ctl->cmd) {
K
Karel Zak 已提交
2184
        vshCommandFree(ctl->cmd);
2185 2186
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
2187 2188
    if (first)
        vshCommandOptFree(first);
2189
    VIR_FREE(tkdata);
E
Eric Blake 已提交
2190
    return false;
K
Karel Zak 已提交
2191 2192
}

2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
/* --------------------
 * 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 已提交
2211 2212
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
2213 2214 2215 2216
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
2217
        return false;
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289

    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 已提交
2290 2291
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
2292 2293 2294 2295
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
2296
        return false;
2297 2298 2299 2300 2301 2302

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

K
Karel Zak 已提交
2303
/* ---------------
2304
 * Misc utils
K
Karel Zak 已提交
2305 2306
 * ---------------
 */
E
Eric Blake 已提交
2307
int
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
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;
}

2335 2336
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
E
Eric Blake 已提交
2337
char *
2338 2339 2340 2341 2342
vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
{
    int ret = 0;
    char *str = NULL;

2343
    switch (item->type) {
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
    case VIR_TYPED_PARAM_INT:
        ret = virAsprintf(&str, "%d", item->value.i);
        break;

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

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

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

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

    case VIR_TYPED_PARAM_BOOLEAN:
E
Eric Blake 已提交
2365
        str = vshStrdup(ctl, item->value.b ? _("yes") : _("no"));
2366 2367
        break;

2368 2369 2370 2371
    case VIR_TYPED_PARAM_STRING:
        str = vshStrdup(ctl, item->value.s);
        break;

2372
    default:
2373
        vshError(ctl, _("unimplemented parameter type %d"), item->type);
2374 2375
    }

2376
    if (ret < 0) {
2377
        vshError(ctl, "%s", _("Out of memory"));
2378 2379
        exit(EXIT_FAILURE);
    }
2380 2381 2382
    return str;
}

E
Eric Blake 已提交
2383
void
2384
vshDebug(vshControl *ctl, int level, const char *format, ...)
2385
{
K
Karel Zak 已提交
2386
    va_list ap;
2387
    char *str;
K
Karel Zak 已提交
2388

2389 2390 2391 2392 2393 2394 2395
    /* Aligning log levels to that of libvirt.
     * Traces with levels >=  user-specified-level
     * gets logged into file
     */
    if (level < ctl->debug)
        return;

2396
    va_start(ap, format);
2397
    vshOutputLogFile(ctl, level, format, ap);
2398 2399
    va_end(ap);

K
Karel Zak 已提交
2400
    va_start(ap, format);
2401 2402 2403 2404 2405
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2406
    va_end(ap);
2407 2408
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
2409 2410
}

E
Eric Blake 已提交
2411
void
2412
vshPrintExtra(vshControl *ctl, const char *format, ...)
2413
{
K
Karel Zak 已提交
2414
    va_list ap;
2415
    char *str;
2416

2417
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
2418
        return;
2419

K
Karel Zak 已提交
2420
    va_start(ap, format);
2421 2422 2423 2424 2425
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2426
    va_end(ap);
2427
    fputs(str, stdout);
2428
    VIR_FREE(str);
K
Karel Zak 已提交
2429 2430
}

K
Karel Zak 已提交
2431

2432
bool
2433 2434
vshTTYIsInterruptCharacter(vshControl *ctl ATTRIBUTE_UNUSED,
                           const char chr ATTRIBUTE_UNUSED)
2435
{
2436
#ifndef WIN32
2437 2438 2439
    if (ctl->istty &&
        ctl->termattr.c_cc[VINTR] == chr)
        return true;
2440
#endif
2441 2442 2443 2444 2445

    return false;
}


2446 2447 2448 2449 2450 2451 2452
bool
vshTTYAvailable(vshControl *ctl)
{
    return ctl->istty;
}


2453
int
2454
vshTTYDisableInterrupt(vshControl *ctl ATTRIBUTE_UNUSED)
2455
{
2456
#ifndef WIN32
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
    struct termios termset = ctl->termattr;

    if (!ctl->istty)
        return -1;

    /* check if we need to set the terminal */
    if (termset.c_cc[VINTR] == _POSIX_VDISABLE)
        return 0;

    termset.c_cc[VINTR] = _POSIX_VDISABLE;
    termset.c_lflag &= ~ICANON;

    if (tcsetattr(STDIN_FILENO, TCSANOW, &termset) < 0)
        return -1;
2471
#endif
2472 2473 2474 2475 2476 2477

    return 0;
}


int
2478
vshTTYRestore(vshControl *ctl ATTRIBUTE_UNUSED)
2479
{
2480
#ifndef WIN32
2481 2482 2483 2484 2485
    if (!ctl->istty)
        return 0;

    if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &ctl->termattr) < 0)
        return -1;
2486
#endif
2487 2488 2489 2490 2491

    return 0;
}


2492
#if !defined(WIN32) && !defined(HAVE_CFMAKERAW)
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
/* provide fallback in case cfmakeraw isn't available */
static void
cfmakeraw(struct termios *attr)
{
    attr->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
                         | INLCR | IGNCR | ICRNL | IXON);
    attr->c_oflag &= ~OPOST;
    attr->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    attr->c_cflag &= ~(CSIZE | PARENB);
    attr->c_cflag |= CS8;
}
2504
#endif /* !WIN32 && !HAVE_CFMAKERAW */
2505 2506 2507


int
2508 2509
vshTTYMakeRaw(vshControl *ctl ATTRIBUTE_UNUSED,
              bool report_errors ATTRIBUTE_UNUSED)
2510
{
2511
#ifndef WIN32
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
    struct termios rawattr = ctl->termattr;
    char ebuf[1024];

    if (!ctl->istty) {
        if (report_errors) {
            vshError(ctl, "%s",
                     _("unable to make terminal raw: console isn't a tty"));
        }

        return -1;
    }

    cfmakeraw(&rawattr);

    if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &rawattr) < 0) {
        if (report_errors)
            vshError(ctl, _("unable to set tty attributes: %s"),
                     virStrerror(errno, ebuf, sizeof(ebuf)));
        return -1;
    }
2532
#endif
2533 2534 2535 2536 2537

    return 0;
}


E
Eric Blake 已提交
2538
void
2539
vshError(vshControl *ctl, const char *format, ...)
2540
{
K
Karel Zak 已提交
2541
    va_list ap;
2542
    char *str;
2543

2544 2545 2546 2547 2548
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
2549

2550 2551 2552 2553
    /* 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);
2554
    fputs(_("error: "), stderr);
2555

K
Karel Zak 已提交
2556
    va_start(ap, format);
2557 2558 2559
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
2560 2561
    va_end(ap);

2562
    fprintf(stderr, "%s\n", NULLSTR(str));
2563
    fflush(stderr);
2564
    VIR_FREE(str);
K
Karel Zak 已提交
2565 2566
}

2567

J
Jiri Denemark 已提交
2568 2569 2570 2571 2572
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
E
Eric Blake 已提交
2583
            vshReportError(ctl);
J
Jiri Denemark 已提交
2584 2585 2586 2587
    }
}


2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
/*
 * Helpers for waiting for a libvirt event.
 */

/* We want to use SIGINT to cancel a wait; but as signal handlers
 * don't have an opaque argument, we have to use static storage.  */
static int vshEventFd = -1;
static struct sigaction vshEventOldAction;


/* Signal handler installed in vshEventStart, removed in vshEventCleanup.  */
static void
vshEventInt(int sig ATTRIBUTE_UNUSED,
            siginfo_t *siginfo ATTRIBUTE_UNUSED,
            void *context ATTRIBUTE_UNUSED)
{
    char reason = VSH_EVENT_INTERRUPT;
    if (vshEventFd >= 0)
        ignore_value(safewrite(vshEventFd, &reason, 1));
}


/* Event loop handler used to limit length of waiting for any other event. */
static void
vshEventTimeout(int timer ATTRIBUTE_UNUSED,
                void *opaque)
{
    vshControl *ctl = opaque;
    char reason = VSH_EVENT_TIMEOUT;

    if (ctl->eventPipe[1] >= 0)
        ignore_value(safewrite(ctl->eventPipe[1], &reason, 1));
}


/**
 * vshEventStart:
 * @ctl virsh command struct
 * @timeout_ms max wait time in milliseconds, or 0 for indefinite
 *
 * Set up a wait for a libvirt event.  The wait can be canceled by
 * SIGINT or by calling vshEventDone() in your event handler.  If
 * @timeout_ms is positive, the wait will also end if the timeout
 * expires.  Call vshEventWait() to block the main thread (the event
 * handler runs in the event loop thread).  When done (including if
 * there was an error registering for an event), use vshEventCleanup()
 * to quit waiting.  Returns 0 on success, -1 on failure.  */
int
vshEventStart(vshControl *ctl, int timeout_ms)
{
    struct sigaction action;

    assert(ctl->eventPipe[0] == -1 && ctl->eventPipe[1] == -1 &&
           vshEventFd == -1 && ctl->eventTimerId >= 0);
    if (pipe2(ctl->eventPipe, O_CLOEXEC) < 0) {
        char ebuf[1024];

        vshError(ctl, _("failed to create pipe: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)));
        return -1;
    }
    vshEventFd = ctl->eventPipe[1];

    action.sa_sigaction = vshEventInt;
    action.sa_flags = SA_SIGINFO;
    sigemptyset(&action.sa_mask);
    sigaction(SIGINT, &action, &vshEventOldAction);

    if (timeout_ms)
        virEventUpdateTimeout(ctl->eventTimerId, timeout_ms);

    return 0;
}


/**
 * vshEventDone:
 * @ctl virsh command struct
 *
 * Call this from an event callback to let the main thread quit
 * blocking on further events.
 */
void
vshEventDone(vshControl *ctl)
{
    char reason = VSH_EVENT_DONE;

    if (ctl->eventPipe[1] >= 0)
        ignore_value(safewrite(ctl->eventPipe[1], &reason, 1));
}


/**
 * vshEventWait:
 * @ctl virsh command struct
 *
 * Call this in the main thread after calling vshEventStart() then
 * registering for one or more events.  This call will block until
 * SIGINT, the timeout registered at the start, or until one of your
 * event handlers calls vshEventDone().  Returns an enum VSH_EVENT_*
 * stating how the wait concluded, or -1 on error.
 */
int
vshEventWait(vshControl *ctl)
{
    char buf;
    int rv;

    assert(ctl->eventPipe[0] >= 0);
    while ((rv = read(ctl->eventPipe[0], &buf, 1)) < 0 && errno == EINTR);
    if (rv != 1) {
        char ebuf[1024];

        if (!rv)
            errno = EPIPE;
        vshError(ctl, _("failed to determine loop exit status: %s"),
                 virStrerror(errno, ebuf, sizeof(ebuf)));
        return -1;
    }
    return buf;
}


/**
 * vshEventCleanup:
 * @ctl virsh command struct
 *
 * Call at the end of any function that has used vshEventStart(), to
 * tear down any remaining SIGINT or timeout handlers.
 */
void
vshEventCleanup(vshControl *ctl)
{
    if (vshEventFd >= 0) {
        sigaction(SIGINT, &vshEventOldAction, NULL);
        vshEventFd = -1;
    }
    VIR_FORCE_CLOSE(ctl->eventPipe[0]);
    VIR_FORCE_CLOSE(ctl->eventPipe[1]);
    virEventUpdateTimeout(ctl->eventTimerId, -1);
}


K
Karel Zak 已提交
2731
/*
M
Martin Kletzander 已提交
2732
 * Initialize debug settings.
K
Karel Zak 已提交
2733
 */
M
Martin Kletzander 已提交
2734 2735
static void
vshInitDebug(vshControl *ctl)
2736
{
2737
    const char *debugEnv;
2738

J
Jiri Denemark 已提交
2739
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
2740
        /* log level not set from commandline, check env variable */
2741
        debugEnv = virGetEnvAllowSUID("VIRSH_DEBUG");
2742
        if (debugEnv) {
J
Jiri Denemark 已提交
2743 2744 2745
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
2746 2747
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
2748 2749
            } else {
                ctl->debug = debug;
2750 2751 2752 2753 2754 2755
            }
        }
    }

    if (ctl->logfile == NULL) {
        /* log file not set from cmdline */
2756
        debugEnv = virGetEnvBlockSUID("VIRSH_LOG_FILE");
2757 2758
        if (debugEnv && *debugEnv) {
            ctl->logfile = vshStrdup(ctl, debugEnv);
M
Martin Kletzander 已提交
2759
            vshOpenLogFile(ctl);
2760 2761
        }
    }
M
Martin Kletzander 已提交
2762 2763 2764 2765 2766 2767 2768 2769
}

/*
 * Initialize connection.
 */
static bool
vshInit(vshControl *ctl)
{
M
Martin Kletzander 已提交
2770 2771 2772 2773
    /* Since we have the commandline arguments parsed, we need to
     * re-initialize all the debugging to make it work properly */
    vshInitDebug(ctl);

M
Martin Kletzander 已提交
2774 2775
    if (ctl->conn)
        return false;
2776

2777 2778
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2779

2780
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
2781
        return false;
2782

J
Jiri Denemark 已提交
2783 2784 2785 2786
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

2787 2788 2789 2790
    if ((ctl->eventTimerId = virEventAddTimeout(-1, vshEventTimeout, ctl,
                                                NULL)) < 0)
        return false;

2791
    if (ctl->name) {
2792
        vshReconnect(ctl);
2793 2794 2795 2796 2797 2798 2799
        /* Connecting to a named connection must succeed, but we delay
         * connecting to the default connection until we need it
         * (since the first command might be 'connect' which allows a
         * non-default connection, or might be 'help' which needs no
         * connection).
         */
        if (!ctl->conn) {
E
Eric Blake 已提交
2800
            vshReportError(ctl);
2801 2802
            return false;
        }
2803
    }
K
Karel Zak 已提交
2804

E
Eric Blake 已提交
2805
    return true;
K
Karel Zak 已提交
2806 2807
}

2808 2809
#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

2810 2811 2812 2813 2814
/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
E
Eric Blake 已提交
2815
void
2816 2817 2818 2819 2820
vshOpenLogFile(vshControl *ctl)
{
    if (ctl->logfile == NULL)
        return;

2821
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
2822
        vshError(ctl, "%s",
J
Jim Meyering 已提交
2823
                 _("failed to open the log file. check the log file path"));
2824
        exit(EXIT_FAILURE);
2825 2826 2827 2828 2829 2830 2831 2832
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
E
Eric Blake 已提交
2833
void
2834 2835
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
2836
{
2837
    virBuffer buf = VIR_BUFFER_INITIALIZER;
J
John Ferlan 已提交
2838
    char *str = NULL;
2839
    size_t len;
2840
    const char *lvl = "";
2841
    time_t stTime;
2842
    struct tm stTm;
2843 2844 2845 2846 2847 2848 2849 2850 2851

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

    /**
     * create log format
     *
     * [YYYY.MM.DD HH:MM:SS SIGNATURE PID] LOG_LEVEL message
    */
2852 2853
    time(&stTime);
    localtime_r(&stTime, &stTm);
2854
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
2855 2856 2857 2858 2859 2860
                      (1900 + stTm.tm_year),
                      (1 + stTm.tm_mon),
                      stTm.tm_mday,
                      stTm.tm_hour,
                      stTm.tm_min,
                      stTm.tm_sec,
2861 2862
                      SIGN_NAME,
                      (int) getpid());
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
    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;
    }
2883 2884 2885
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
2886

2887 2888
    if (virBufferError(&buf))
        goto error;
2889

2890 2891 2892 2893 2894
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
2895
    }
2896

2897 2898 2899 2900
    /* write log */
    if (safewrite(ctl->log_fd, str, len) < 0)
        goto error;

2901
    VIR_FREE(str);
2902 2903
    return;

2904
 error:
2905 2906 2907 2908
    vshCloseLogFile(ctl);
    vshError(ctl, "%s", _("failed to write the log file"));
    virBufferFreeAndReset(&buf);
    VIR_FREE(str);
2909 2910 2911 2912 2913 2914 2915
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
E
Eric Blake 已提交
2916
void
2917 2918
vshCloseLogFile(vshControl *ctl)
{
2919 2920
    char ebuf[1024];

2921
    /* log file close */
2922 2923
    if (VIR_CLOSE(ctl->log_fd) < 0) {
        vshError(ctl, _("%s: failed to write log file: %s"),
2924 2925
                 ctl->logfile ? ctl->logfile : "?",
                 virStrerror(errno, ebuf, sizeof(ebuf)));
2926 2927 2928
    }

    if (ctl->logfile) {
2929
        VIR_FREE(ctl->logfile);
2930 2931 2932 2933
        ctl->logfile = NULL;
    }
}

2934
#if WITH_READLINE
2935

K
Karel Zak 已提交
2936 2937 2938 2939 2940
/* -----------------
 * Readline stuff
 * -----------------
 */

2941
/*
K
Karel Zak 已提交
2942 2943
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
2944
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
2945 2946
 */
static char *
2947 2948
vshReadlineCommandGenerator(const char *text, int state)
{
2949
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
2950
    const char *name;
2951 2952
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
2953 2954

    if (!state) {
2955 2956
        grp_list_index = 0;
        cmd_list_index = 0;
2957
        len = strlen(text);
K
Karel Zak 已提交
2958 2959
    }

2960 2961
    grp = cmdGroups;

K
Karel Zak 已提交
2962
    /* Return the next name which partially matches from the
2963
     * command list.
K
Karel Zak 已提交
2964
     */
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978
    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 已提交
2979 2980 2981 2982 2983 2984 2985
    }

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

static char *
2986 2987
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2988
    static int list_index, len;
2989
    static const vshCmdDef *cmd;
K
Karel Zak 已提交
2990
    const char *name;
K
Karel Zak 已提交
2991 2992 2993 2994 2995 2996 2997 2998 2999

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

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

3000
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
3001
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
3002 3003 3004

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
3005
        len = strlen(text);
3006
        VIR_FREE(cmdname);
K
Karel Zak 已提交
3007 3008 3009 3010
    }

    if (!cmd)
        return NULL;
3011

3012 3013 3014
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
3015
    while ((name = cmd->opts[list_index].name)) {
3016
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
3017
        char *res;
3018

K
Karel Zak 已提交
3019
        list_index++;
3020

3021
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
3022 3023
            /* ignore non --option */
            continue;
3024

K
Karel Zak 已提交
3025
        if (len > 2) {
3026
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
3027 3028
                continue;
        }
3029
        res = vshMalloc(NULL, strlen(name) + 3);
3030
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
3031 3032 3033 3034 3035 3036 3037 3038
        return res;
    }

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

static char **
3039 3040 3041
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
3042 3043
    char **matches = (char **) NULL;

3044
    if (start == 0)
K
Karel Zak 已提交
3045
        /* command name generator */
3046
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
3047 3048
    else
        /* commands options */
3049
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
3050 3051 3052
    return matches;
}

3053
# define VIRSH_HISTSIZE_MAX 500000
K
Karel Zak 已提交
3054

3055 3056
static int
vshReadlineInit(vshControl *ctl)
3057
{
3058
    char *userdir = NULL;
3059 3060
    int max_history = 500;
    const char *histsize_str;
3061

3062 3063 3064 3065 3066
    /* Allow conditional parsing of the ~/.inputrc file.
     * Work around ancient readline 4.1 (hello Mac OS X),
     * which declared it as 'char *' instead of 'const char *'.
     */
    rl_readline_name = (char *) "virsh";
K
Karel Zak 已提交
3067 3068 3069

    /* Tell the completer that we want a crack first. */
    rl_attempted_completion_function = vshReadlineCompletion;
3070 3071

    /* Limit the total size of the history buffer */
3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084
    if ((histsize_str = virGetEnvBlockSUID("VIRSH_HISTSIZE"))) {
        if (virStrToLong_i(histsize_str, NULL, 10, &max_history) < 0) {
            vshError(ctl, "%s", _("Bad $VIRSH_HISTSIZE value."));
            VIR_FREE(userdir);
            return -1;
        } else if (max_history > VIRSH_HISTSIZE_MAX || max_history < 0) {
            vshError(ctl, _("$VIRSH_HISTSIZE value should be between 0 and %d"),
                     VIRSH_HISTSIZE_MAX);
            VIR_FREE(userdir);
            return -1;
        }
    }
    stifle_history(max_history);
3085

3086
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
3087
    userdir = virGetUserCacheDirectory();
3088

3089 3090
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
3091
        return -1;
3092
    }
3093

3094
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
3095
        vshError(ctl, "%s", _("Out of memory"));
3096
        VIR_FREE(userdir);
3097 3098 3099 3100 3101
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
3102
        VIR_FREE(userdir);
3103 3104 3105
        return -1;
    }

3106
    VIR_FREE(userdir);
3107 3108 3109 3110 3111 3112 3113

    read_history(ctl->historyfile);

    return 0;
}

static void
3114
vshReadlineDeinit(vshControl *ctl)
3115 3116
{
    if (ctl->historyfile != NULL) {
3117 3118
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
3119 3120
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
3121
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
3122
        } else {
3123
            write_history(ctl->historyfile);
E
Eric Blake 已提交
3124
        }
3125 3126
    }

3127 3128
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
3129 3130
}

3131
static char *
3132
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
3133
{
3134
    return readline(prompt);
3135 3136
}

3137
#else /* !WITH_READLINE */
3138

3139
static int
3140
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
3141 3142 3143 3144 3145
{
    /* empty */
    return 0;
}

3146
static void
3147
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
3148 3149 3150 3151 3152
{
    /* empty */
}

static char *
3153
vshReadline(vshControl *ctl, const char *prompt)
3154 3155 3156 3157 3158
{
    char line[1024];
    char *r;
    int len;

3159 3160
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
3161 3162 3163
    if (r == NULL) return NULL; /* EOF */

    /* Chomp trailing \n */
3164
    len = strlen(r);
3165 3166 3167
    if (len > 0 && r[len-1] == '\n')
        r[len-1] = '\0';

3168
    return vshStrdup(ctl, r);
3169 3170
}

3171
#endif /* !WITH_READLINE */
3172

3173 3174 3175 3176 3177 3178
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
3179
/*
J
Jim Meyering 已提交
3180
 * Deinitialize virsh
K
Karel Zak 已提交
3181
 */
E
Eric Blake 已提交
3182
static bool
3183
vshDeinit(vshControl *ctl)
3184
{
3185
    vshReadlineDeinit(ctl);
3186
    vshCloseLogFile(ctl);
3187
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
3188
    if (ctl->conn) {
3189
        int ret;
3190 3191 3192 3193 3194 3195 3196
        virConnectUnregisterCloseCallback(ctl->conn, vshCatchDisconnect);
        ret = virConnectClose(ctl->conn);
        if (ret < 0)
            vshError(ctl, "%s", _("Failed to disconnect from the hypervisor"));
        else if (ret > 0)
            vshError(ctl, "%s", _("One or more references were leaked after "
                                  "disconnect from the hypervisor"));
K
Karel Zak 已提交
3197
    }
D
Daniel P. Berrange 已提交
3198 3199
    virResetLastError();

J
Jiri Denemark 已提交
3200
    if (ctl->eventLoopStarted) {
3201 3202 3203 3204
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
3205
        /* HACK: Add a dummy timeout to break event loop */
3206 3207 3208 3209 3210
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
3211 3212 3213
        if (timer != -1)
            virEventRemoveTimeout(timer);

3214 3215 3216
        if (ctl->eventTimerId != -1)
            virEventRemoveTimeout(ctl->eventTimerId);

J
Jiri Denemark 已提交
3217 3218 3219
        ctl->eventLoopStarted = false;
    }

3220 3221
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
3222
    return true;
K
Karel Zak 已提交
3223
}
3224

K
Karel Zak 已提交
3225 3226 3227
/*
 * Print usage
 */
E
Eric Blake 已提交
3228
static void
3229
vshUsage(void)
3230
{
3231
    const vshCmdGrp *grp;
3232
    const vshCmdDef *cmd;
3233

L
Lai Jiangshan 已提交
3234 3235
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
3236
                      "  options:\n"
3237 3238
                      "    -c | --connect=URI      hypervisor connection URI\n"
                      "    -d | --debug=NUM        debug level [0-4]\n"
3239
                      "    -e | --escape <char>    set escape sequence for console\n"
3240
                      "    -h | --help             this help\n"
3241 3242 3243 3244
                      "    -k | --keepalive-interval=NUM\n"
                      "                            keepalive interval in seconds, 0 for disable\n"
                      "    -K | --keepalive-count=NUM\n"
                      "                            number of possible missed keepalive messages\n"
3245
                      "    -l | --log=FILE         output logging to file\n"
3246
                      "    -q | --quiet            quiet mode\n"
3247
                      "    -r | --readonly         connect readonly\n"
3248
                      "    -t | --timing           print timing information\n"
3249 3250 3251
                      "    -v                      short version\n"
                      "    -V                      long version\n"
                      "         --version[=TYPE]   version, TYPE is short or long (default short)\n"
3252
                      "  commands (non interactive mode):\n\n"), progname, progname);
3253

3254
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
3255 3256 3257 3258 3259
        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;
3260
            fprintf(stdout,
E
Eric Blake 已提交
3261 3262 3263
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
3264 3265 3266 3267 3268
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
3269 3270 3271
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
3272 3273
}

3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
/*
 * 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 已提交
3284 3285
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
3286
#ifdef WITH_QEMU
3287
    vshPrint(ctl, " QEMU/KVM");
3288
#endif
D
Doug Goldstein 已提交
3289 3290 3291
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
3292 3293 3294
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
3295 3296 3297 3298 3299 3300
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
3301 3302 3303
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
3304 3305
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
3306
#endif
D
Doug Goldstein 已提交
3307 3308
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
3309
#endif
D
Doug Goldstein 已提交
3310 3311
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
3312 3313 3314 3315
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
3316 3317
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
3318
#endif
D
Doug Goldstein 已提交
3319 3320
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
3321
#endif
3322 3323 3324
#ifdef WITH_BHYVE
    vshPrint(ctl, " Bhyve");
#endif
3325 3326 3327 3328 3329
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
3330
    vshPrint(ctl, "%s", _(" Networking:"));
3331 3332 3333 3334 3335 3336 3337 3338 3339
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
3340
#if defined(WITH_INTERFACE)
D
Doug Goldstein 已提交
3341
    vshPrint(ctl, " Interface");
3342 3343
# if defined(WITH_NETCF)
    vshPrint(ctl, " netcf");
3344
# elif defined(WITH_UDEV)
3345
    vshPrint(ctl, " udev");
3346
# endif
3347 3348 3349 3350 3351 3352 3353 3354 3355
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
3356
    vshPrint(ctl, "%s", _(" Storage:"));
3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
#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");
3377 3378 3379
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
3380 3381 3382
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
3383 3384 3385
#endif
#ifdef WITH_STORAGE_GLUSTER
    vshPrint(ctl, " Gluster");
3386 3387 3388
#endif
    vshPrint(ctl, "\n");

3389
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
3390 3391 3392
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410
#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
3411
#if WITH_READLINE
3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
    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 已提交
3434
static bool
3435 3436
vshParseArgv(vshControl *ctl, int argc, char **argv)
{
3437
    int arg, len, debug, keepalive;
3438
    size_t i;
3439
    int longindex = -1;
3440
    struct option opt[] = {
3441
        {"connect", required_argument, NULL, 'c'},
3442
        {"debug", required_argument, NULL, 'd'},
3443
        {"escape", required_argument, NULL, 'e'},
3444
        {"help", no_argument, NULL, 'h'},
3445 3446
        {"keepalive-interval", required_argument, NULL, 'k'},
        {"keepalive-count", required_argument, NULL, 'K'},
3447
        {"log", required_argument, NULL, 'l'},
3448
        {"quiet", no_argument, NULL, 'q'},
3449
        {"readonly", no_argument, NULL, 'r'},
3450 3451 3452 3453 3454 3455 3456 3457
        {"timing", no_argument, NULL, 't'},
        {"version", optional_argument, NULL, 'v'},
        {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. */
3458
    while ((arg = getopt_long(argc, argv, "+:c:d:e:hk:K:l:qrtvV", opt, &longindex)) != -1) {
3459
        switch (arg) {
3460 3461 3462 3463
        case 'c':
            VIR_FREE(ctl->name);
            ctl->name = vshStrdup(ctl, optarg);
            break;
3464
        case 'd':
3465
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
3466 3467
                vshError(ctl, _("option %s takes a numeric argument"),
                         longindex == -1 ? "-d" : "--debug");
3468 3469
                exit(EXIT_FAILURE);
            }
3470 3471 3472 3473 3474
            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;
3475
            break;
3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488
        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;
3489 3490 3491 3492
        case 'h':
            vshUsage();
            exit(EXIT_SUCCESS);
            break;
3493
        case 'k':
E
Erik Skultety 已提交
3494 3495 3496 3497 3498 3499 3500 3501 3502 3503
            if (virStrToLong_i(optarg, NULL, 0, &keepalive) < 0) {
                vshError(ctl,
                         _("Invalid value for option %s"),
                         longindex == -1 ? "-k" : "--keepalive-interval");
                exit(EXIT_FAILURE);
            }

            if (keepalive < 0) {
                vshError(ctl,
                         _("option %s requires a positive integer argument"),
3504 3505 3506 3507 3508 3509
                         longindex == -1 ? "-k" : "--keepalive-interval");
                exit(EXIT_FAILURE);
            }
            ctl->keepalive_interval = keepalive;
            break;
        case 'K':
E
Erik Skultety 已提交
3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
            if (virStrToLong_i(optarg, NULL, 0, &keepalive) < 0) {
                vshError(ctl,
                         _("Invalid value for option %s"),
                         longindex == -1 ? "-K" : "--keepalive-count");
                exit(EXIT_FAILURE);
            }

            if (keepalive < 0) {
                vshError(ctl,
                         _("option %s requires a positive integer argument"),
3520 3521 3522 3523 3524
                         longindex == -1 ? "-K" : "--keepalive-count");
                exit(EXIT_FAILURE);
            }
            ctl->keepalive_count = keepalive;
            break;
3525 3526 3527 3528 3529
        case 'l':
            vshCloseLogFile(ctl);
            ctl->logfile = vshStrdup(ctl, optarg);
            vshOpenLogFile(ctl);
            break;
3530 3531 3532 3533 3534 3535
        case 'q':
            ctl->quiet = true;
            break;
        case 't':
            ctl->timing = true;
            break;
3536 3537
        case 'r':
            ctl->readonly = true;
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
            /* fall through */
        case 'V':
            vshShowVersion(ctl);
            exit(EXIT_SUCCESS);
3548
        case ':':
3549
            for (i = 0; opt[i].name != NULL; i++) {
3550 3551
                if (opt[i].val == optopt)
                    break;
3552
            }
3553 3554 3555 3556 3557 3558
            if (opt[i].name)
                vshError(ctl, _("option '-%c'/'--%s' requires an argument"),
                         optopt, opt[i].name);
            else
                vshError(ctl, _("option '-%c' requires an argument"), optopt);
            exit(EXIT_FAILURE);
3559
        case '?':
3560 3561 3562 3563
            if (optopt)
                vshError(ctl, _("unsupported option '-%c'. See --help."), optopt);
            else
                vshError(ctl, _("unsupported option '%s'. See --help."), argv[optind - 1]);
3564
            exit(EXIT_FAILURE);
3565
        default:
3566
            vshError(ctl, _("unknown option"));
3567 3568
            exit(EXIT_FAILURE);
        }
3569
        longindex = -1;
3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
    }

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

static const vshCmdDef virshCmds[] = {
3586 3587 3588 3589 3590
    {.name = "cd",
     .handler = cmdCd,
     .opts = opts_cd,
     .info = info_cd,
     .flags = VSH_CMD_FLAG_NOCONNECT
3591 3592 3593 3594 3595 3596
    },
    {.name = "connect",
     .handler = cmdConnect,
     .opts = opts_connect,
     .info = info_connect,
     .flags = VSH_CMD_FLAG_NOCONNECT
3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628
    },
    {.name = "echo",
     .handler = cmdEcho,
     .opts = opts_echo,
     .info = info_echo,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "exit",
     .handler = cmdQuit,
     .opts = NULL,
     .info = info_quit,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "help",
     .handler = cmdHelp,
     .opts = opts_help,
     .info = info_help,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "pwd",
     .handler = cmdPwd,
     .opts = NULL,
     .info = info_pwd,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = "quit",
     .handler = cmdQuit,
     .opts = NULL,
     .info = info_quit,
     .flags = VSH_CMD_FLAG_NOCONNECT
    },
    {.name = NULL}
3629
};
3630

3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645
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 已提交
3646

3647 3648 3649 3650
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
3651
    const char *defaultConn;
E
Eric Blake 已提交
3652
    bool ret = true;
K
Karel Zak 已提交
3653

3654 3655 3656
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
3657
    ctl->debug = VSH_DEBUG_DEFAULT;
E
Eric Blake 已提交
3658
    ctl->escapeChar = "^]";     /* Same default as telnet */
3659 3660 3661 3662 3663

    /* In order to distinguish default from setting to 0 */
    ctl->keepalive_interval = -1;
    ctl->keepalive_count = -1;

3664 3665 3666
    ctl->eventPipe[0] = -1;
    ctl->eventPipe[1] = -1;
    ctl->eventTimerId = -1;
3667

3668 3669
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
3670
        /* failure to setup locale is not fatal */
3671
    }
3672
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
3673
        perror("bindtextdomain");
E
Eric Blake 已提交
3674
        return EXIT_FAILURE;
3675
    }
3676
    if (!textdomain(PACKAGE)) {
3677
        perror("textdomain");
E
Eric Blake 已提交
3678
        return EXIT_FAILURE;
3679 3680
    }

3681 3682 3683
    if (isatty(STDIN_FILENO)) {
        ctl->istty = true;

3684
#ifndef WIN32
3685 3686
        if (tcgetattr(STDIN_FILENO, &ctl->termattr) < 0)
            ctl->istty = false;
3687
#endif
3688 3689
    }

3690 3691 3692 3693 3694
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

3695 3696 3697 3698 3699
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

3700 3701
    virFileActivateDirOverride(argv[0]);

3702
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
3703 3704 3705
        progname = argv[0];
    else
        progname++;
3706

3707
    if ((defaultConn = virGetEnvBlockSUID("VIRSH_DEFAULT_CONNECT_URI")))
E
Eric Blake 已提交
3708
        ctl->name = vshStrdup(ctl, defaultConn);
3709

M
Martin Kletzander 已提交
3710
    vshInitDebug(ctl);
3711

M
Martin Kletzander 已提交
3712 3713
    if (!vshParseArgv(ctl, argc, argv) ||
        !vshInit(ctl)) {
D
Daniel P. Berrange 已提交
3714
        vshDeinit(ctl);
K
Karel Zak 已提交
3715
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3716
    }
3717

K
Karel Zak 已提交
3718
    if (!ctl->imode) {
3719
        ret = vshCommandRun(ctl, ctl->cmd);
3720
    } else {
K
Karel Zak 已提交
3721 3722
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
3723
            vshPrint(ctl,
3724
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
3725
                     progname);
J
Jim Meyering 已提交
3726
            vshPrint(ctl, "%s",
3727
                     _("Type:  'help' for help with commands\n"
3728
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
3729
        }
3730 3731 3732 3733 3734 3735

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

K
Karel Zak 已提交
3736
        do {
3737
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
3738
            ctl->cmdstr =
3739
                vshReadline(ctl, prompt);
3740 3741
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
3742
            if (*ctl->cmdstr) {
3743
#if WITH_READLINE
K
Karel Zak 已提交
3744
                add_history(ctl->cmdstr);
3745
#endif
3746
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
3747 3748
                    vshCommandRun(ctl, ctl->cmd);
            }
3749
            VIR_FREE(ctl->cmdstr);
3750
        } while (ctl->imode);
K
Karel Zak 已提交
3751

3752 3753
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
3754
    }
3755

K
Karel Zak 已提交
3756 3757
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
3758
}