virsh.c 99.2 KB
Newer Older
1
/*
2
 * virsh.c: a shell to exercise the libvirt API
3
 *
4
 * Copyright (C) 2005, 2007-2015 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
#if WITH_READLINE
48 49
# include <readline/readline.h>
# include <readline/history.h>
50
#endif
K
Karel Zak 已提交
51

52
#include "internal.h"
53
#include "virerror.h"
54
#include "virbuffer.h"
55
#include "viralloc.h"
56 57
#include <libvirt/libvirt-qemu.h>
#include <libvirt/libvirt-lxc.h>
E
Eric Blake 已提交
58
#include "virfile.h"
59
#include "configmake.h"
60
#include "virthread.h"
61
#include "vircommand.h"
H
Hu Tao 已提交
62
#include "conf/domain_conf.h"
63
#include "virtypedparam.h"
64
#include "virstring.h"
K
Karel Zak 已提交
65

66
#include "virsh-console.h"
E
Eric Blake 已提交
67
#include "virsh-domain.h"
68
#include "virsh-domain-monitor.h"
E
Eric Blake 已提交
69
#include "virsh-host.h"
E
Eric Blake 已提交
70
#include "virsh-interface.h"
E
Eric Blake 已提交
71
#include "virsh-network.h"
E
Eric Blake 已提交
72
#include "virsh-nodedev.h"
E
Eric Blake 已提交
73
#include "virsh-nwfilter.h"
E
Eric Blake 已提交
74
#include "virsh-pool.h"
E
Eric Blake 已提交
75
#include "virsh-secret.h"
E
Eric Blake 已提交
76
#include "virsh-snapshot.h"
E
Eric Blake 已提交
77
#include "virsh-volume.h"
E
Eric Blake 已提交
78

79 80 81 82 83
/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

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

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

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

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

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

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

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

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

122
    if (VIR_STRDUP(x, s) >= 0)
E
Eric Blake 已提交
123 124 125 126 127 128 129 130
        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
131

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

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

E
Eric Blake 已提交
141
double
E
Eric Blake 已提交
142
vshPrettyCapacity(unsigned long long val, const char **unit)
E
Eric Blake 已提交
143
{
144 145 146
    double limit = 1024;

    if (val < limit) {
147
        *unit = "B";
148 149 150 151
        return val;
    }
    limit *= 1024;
    if (val < limit) {
152
        *unit = "KiB";
153 154 155 156
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
157
        *unit = "MiB";
158 159 160 161
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
162
        *unit = "GiB";
163 164 165 166
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
167
        *unit = "TiB";
168 169 170 171 172 173
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val < limit) {
        *unit = "PiB";
        return val / (limit / 1024);
174
    }
175 176 177
    limit *= 1024;
    *unit = "EiB";
    return val / (limit / 1024);
178 179
}

180
/*
181 182 183
 * 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.
184 185 186 187 188
 *
 * Returns the length of the filled array on success, or -1
 * on error.
 */
int
189
vshStringToArray(const char *str,
190 191
                 char ***array)
{
192
    char *str_copied = vshStrdup(NULL, str);
193
    char *str_tok = NULL;
E
Eric Blake 已提交
194
    char *tmp;
195 196
    unsigned int nstr_tokens = 0;
    char **arr = NULL;
E
Eric Blake 已提交
197
    size_t len = strlen(str_copied);
198

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

E
Eric Blake 已提交
202 203 204 205 206
    /* 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] == ',')
207
            str_tok++;
E
Eric Blake 已提交
208 209 210 211
        else
            nstr_tokens++;
        str_tok++;
    }
212

213 214
    /* reserve the NULL element at the end */
    if (VIR_ALLOC_N(arr, nstr_tokens + 1) < 0) {
E
Eric Blake 已提交
215 216 217
        VIR_FREE(str_copied);
        return -1;
    }
218

E
Eric Blake 已提交
219 220 221 222 223 224 225 226 227 228 229
    /* 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';
230
        arr[nstr_tokens++] = vshStrdup(NULL, str_tok);
E
Eric Blake 已提交
231
        str_tok = tmp;
232
    }
233
    arr[nstr_tokens++] = vshStrdup(NULL, str_tok);
234 235

    *array = arr;
236
    VIR_FREE(str_copied);
237 238
    return nstr_tokens;
}
239

E
Eric Blake 已提交
240
virErrorPtr last_error;
J
John Levon 已提交
241 242 243 244 245 246 247 248 249

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

254 255 256 257 258 259 260 261 262
/* 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();
}

263 264 265
/*
 * Reset libvirt error on graceful fallback paths
 */
E
Eric Blake 已提交
266
void
267 268 269 270 271 272
vshResetLibvirtError(void)
{
    virFreeError(last_error);
    last_error = NULL;
}

J
John Levon 已提交
273 274 275 276 277 278 279 280
/*
 * 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 已提交
281
void
E
Eric Blake 已提交
282
vshReportError(vshControl *ctl)
J
John Levon 已提交
283
{
284 285 286 287 288 289 290 291
    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)
292
            goto out;
293
    }
J
John Levon 已提交
294 295

    if (last_error->code == VIR_ERR_OK) {
296
        vshError(ctl, "%s", _("unknown error"));
J
John Levon 已提交
297 298 299
        goto out;
    }

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

302
 out:
303
    vshResetLibvirtError();
J
John Levon 已提交
304 305
}

306 307 308
/*
 * Detection of disconnections and automatic reconnection support
 */
309
static int disconnected; /* we may have been disconnected */
310 311 312 313

/*
 * vshCatchDisconnect:
 *
314 315
 * We get here when the connection was closed.  We can't do much in the
 * handler, just save the fact it was raised.
316
 */
L
Laine Stump 已提交
317
static void
318 319 320 321 322 323
vshCatchDisconnect(virConnectPtr conn ATTRIBUTE_UNUSED,
                   int reason,
                   void *opaque ATTRIBUTE_UNUSED)
{
    if (reason != VIR_CONNECT_CLOSE_REASON_CLIENT)
        disconnected++;
324 325
}

326 327 328 329 330 331 332 333 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
/* 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;
}

366 367 368
/*
 * vshReconnect:
 *
L
Laine Stump 已提交
369
 * Reconnect after a disconnect from libvirtd
370 371
 *
 */
L
Laine Stump 已提交
372
static void
373 374 375 376
vshReconnect(vshControl *ctl)
{
    bool connected = false;

377 378 379
    if (ctl->conn) {
        int ret;

380
        connected = true;
381 382 383 384 385 386 387 388

        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"));
389
    }
390

391 392
    ctl->conn = vshConnect(ctl, ctl->name, ctl->readonly);

393
    if (!ctl->conn) {
394 395 396 397
        if (disconnected)
            vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
        else
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
398 399 400 401 402 403 404
    } 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"));
    }
405
    disconnected = 0;
406
    ctl->useGetInfo = false;
407
    ctl->useSnapshotOld = false;
408
    ctl->blockJobNoBytes = false;
409
}
410

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

/*
 * "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",
428
     .type = VSH_OT_STRING,
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
     .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;
447 448 449 450 451 452 453 454

        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"));
455 456 457 458 459 460 461 462 463 464 465
        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;
466
    ctl->blockJobNoBytes = false;
467 468
    ctl->readonly = ro;

469
    ctl->conn = vshConnect(ctl, ctl->name, ctl->readonly);
470

471
    if (!ctl->conn) {
472
        vshError(ctl, "%s", _("Failed to connect to the hypervisor"));
473 474 475 476 477 478
        return false;
    }

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

480
    return true;
481 482 483
}


484
#ifndef WIN32
485 486 487 488 489 490 491
static void
vshPrintRaw(vshControl *ctl, ...)
{
    va_list ap;
    char *key;

    va_start(ap, ctl);
492
    while ((key = va_arg(ap, char *)) != NULL)
493 494 495 496
        vshPrint(ctl, "%s\r\n", key);
    va_end(ap);
}

497 498 499 500 501 502 503 504 505
/**
 * vshAskReedit:
 * @msg: Question to ask user
 *
 * Ask user if he wants to return to previously
 * edited file.
 *
 * Returns 'y' if he wants to
 *         'n' if he doesn't want to
506 507
 *         'i' if he wants to try defining it again while ignoring validation
 *         'f' if he forcibly wants to
508 509 510
 *         -1  on error
 *          0  otherwise
 */
E
Eric Blake 已提交
511
int
512
vshAskReedit(vshControl *ctl, const char *msg, bool relax_avail)
513 514 515 516 517 518
{
    int c = -1;

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

E
Eric Blake 已提交
519
    vshReportError(ctl);
520

521
    if (vshTTYMakeRaw(ctl, false) < 0)
522 523 524
        return -1;

    while (true) {
525 526
        vshPrint(ctl, "\r%s %s %s: ", msg, _("Try again?"),
                 relax_avail ? "[y,n,i,f,?]" : "[y,n,f,?]");
527 528 529
        c = c_tolower(getchar());

        if (c == '?') {
530 531 532 533
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
534 535 536 537 538 539 540 541 542
                        NULL);

            if (relax_avail) {
                vshPrintRaw(ctl,
                            _("i - turn off validation and try to redefine again"),
                            NULL);
            }

            vshPrintRaw(ctl,
543 544 545
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
546
            continue;
547 548
        } else if (c == 'y' || c == 'n' || c == 'f' ||
                   (relax_avail && c == 'i')) {
549 550 551 552
            break;
        }
    }

553
    vshTTYRestore(ctl);
554 555 556

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

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

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

K
Karel Zak 已提交
578 579 580 581 582 583
/* ---------------
 * Commands
 * ---------------
 */

/*
584
 * "help" command
K
Karel Zak 已提交
585
 */
586
static const vshCmdInfo info_help[] = {
587 588 589 590 591 592 593 594
    {.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 已提交
595 596
};

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

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

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

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

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

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

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
630
        return true;
631
    }
632

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

643 644 645 646 647 648 649 650 651 652 653
/* Tree listing helpers.  */

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

660
    if (virBufferError(indent))
661 662
        goto cleanup;

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

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

679 680 681
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
682

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

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

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

702 703 704 705
    /* 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));
706

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

843

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

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

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

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

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

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

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

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

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

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

923
    return ret;
P
Paolo Bonzini 已提交
924 925
}

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

static const vshCmdOptDef opts_echo[] = {
940 941 942 943 944 945 946 947 948 949 950 951
    {.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"
    },
952 953 954 955
    {.name = "hi",
     .type = VSH_OT_ALIAS,
     .help = "string=hello"
    },
956 957 958 959 960
    {.name = "string",
     .type = VSH_OT_ARGV,
     .help = N_("arguments to echo")
    },
    {.name = NULL}
E
Eric Blake 已提交
961 962 963 964 965
};

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

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

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

985
        arg = opt->data;
986

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

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

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

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

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

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

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

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

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

1064 1065
    *opts_need_arg = 0;
    *opts_required = 0;
1066

1067 1068
    if (!cmd->opts)
        return 0;
1069

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

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

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

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

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

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

1142
    if (STREQ(name, helpopt.name))
1143 1144
        return &helpopt;

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

1148
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
1149
            if (opt->type == VSH_OT_ALIAS) {
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
                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 已提交
1170 1171
                continue;
            }
1172
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
1173
                vshError(ctl, _("option --%s already seen"), name);
1174
                goto cleanup;
1175
            }
1176 1177
            *opts_seen |= 1 << i;
            *opt_index = i;
1178 1179
            ret = opt;
            goto cleanup;
1180 1181 1182
        }
    }

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

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

1199 1200 1201 1202
    if (!*opts_need_arg)
        return NULL;

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

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

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

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

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

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

K
Karel Zak 已提交
1252 1253 1254
    return NULL;
}

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

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

    return NULL;
}

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

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

E
Eric Blake 已提交
1289
    return true;
1290 1291
}

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

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

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

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

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

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

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

E
Eric Blake 已提交
1416
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
1417
            }
K
Karel Zak 已提交
1418 1419 1420
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
1421
    return true;
K
Karel Zak 已提交
1422 1423 1424 1425 1426 1427
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1428 1429 1430
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1431 1432
    vshCmdOpt *a = arg;

1433
    while (a) {
K
Karel Zak 已提交
1434
        vshCmdOpt *tmp = a;
1435

K
Karel Zak 已提交
1436 1437
        a = a->next;

1438 1439
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
1440 1441 1442 1443
    }
}

static void
1444
vshCommandFree(vshCmd *cmd)
1445
{
K
Karel Zak 已提交
1446 1447
    vshCmd *c = cmd;

1448
    while (c) {
K
Karel Zak 已提交
1449
        vshCmd *tmp = c;
1450

K
Karel Zak 已提交
1451 1452 1453 1454
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
1455
        VIR_FREE(tmp);
K
Karel Zak 已提交
1456 1457 1458
    }
}

E
Eric Blake 已提交
1459 1460 1461 1462 1463
/**
 * vshCommandOpt:
 * @cmd: parsed command line to search
 * @name: option name to search for
 * @opt: result of the search
1464
 * @needData: true if option must be non-boolean
E
Eric Blake 已提交
1465 1466 1467 1468
 *
 * 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
1469 1470 1471
 * 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 已提交
1472
 */
1473 1474 1475
static int
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt,
              bool needData)
1476
{
E
Eric Blake 已提交
1477 1478
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
    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;
1492

E
Eric Blake 已提交
1493 1494 1495 1496
    /* See if option is present on command line.  */
    while (candidate) {
        if (STREQ(candidate->def->name, name)) {
            *opt = candidate;
1497 1498
            ret = 1;
            break;
E
Eric Blake 已提交
1499 1500
        }
        candidate = candidate->next;
K
Karel Zak 已提交
1501
    }
1502
    return ret;
K
Karel Zak 已提交
1503 1504
}

E
Eric Blake 已提交
1505 1506
/**
 * vshCommandOptInt:
1507
 * @ctl virsh control structure
1508 1509 1510 1511
 * @cmd command reference
 * @name option name
 * @value result
 *
1512 1513 1514
 * Convert option to int.
 * On error, a message is displayed.
 *
1515 1516
 * Return value:
 * >0 if option found and valid (@value updated)
E
Eric Blake 已提交
1517
 * 0 if option not found and not required (@value untouched)
1518
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
1519
 */
E
Eric Blake 已提交
1520
int
1521
vshCommandOptInt(vshControl *ctl, const vshCmd *cmd,
1522
                 const char *name, int *value)
1523
{
E
Eric Blake 已提交
1524 1525
    vshCmdOpt *arg;
    int ret;
1526

1527
    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
E
Eric Blake 已提交
1528 1529
        return ret;

1530 1531 1532 1533 1534 1535 1536 1537
    if ((ret = virStrToLong_i(arg->data, NULL, 10, value)) < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;

    return ret;
K
Karel Zak 已提交
1538 1539
}

1540
static int
1541
vshCommandOptUIntInternal(vshControl *ctl,
1542
                          const vshCmd *cmd,
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
                          const char *name,
                          unsigned int *value,
                          bool wrap)
{
    vshCmdOpt *arg;
    int ret;

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

1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
    if (wrap)
        ret = virStrToLong_ui(arg->data, NULL, 10, value);
    else
        ret = virStrToLong_uip(arg->data, NULL, 10, value);
    if (ret < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;
1563

1564
    return ret;
1565
}
1566

E
Eric Blake 已提交
1567 1568
/**
 * vshCommandOptUInt:
1569
 * @ctl virsh control structure
E
Eric Blake 已提交
1570 1571 1572 1573
 * @cmd command reference
 * @name option name
 * @value result
 *
1574
 * Convert option to unsigned int, reject negative numbers
1575 1576
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1577
int
1578 1579
vshCommandOptUInt(vshControl *ctl, const vshCmd *cmd,
                  const char *name, unsigned int *value)
1580
{
1581
    return vshCommandOptUIntInternal(ctl, cmd, name, value, false);
1582
}
E
Eric Blake 已提交
1583

1584 1585
/**
 * vshCommandOptUIntWrap:
1586
 * @ctl virsh control structure
1587 1588 1589 1590 1591 1592 1593 1594
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to unsigned int, wraps negative numbers to positive
 * See vshCommandOptInt()
 */
int
1595 1596
vshCommandOptUIntWrap(vshControl *ctl, const vshCmd *cmd,
                      const char *name, unsigned int *value)
1597
{
1598
    return vshCommandOptUIntInternal(ctl, cmd, name, value, true);
1599 1600
}

1601
static int
1602
vshCommandOptULInternal(vshControl *ctl,
1603
                        const vshCmd *cmd,
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
                        const char *name,
                        unsigned long *value,
                        bool wrap)
{
    vshCmdOpt *arg;
    int ret;

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

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
    if (wrap)
        ret = virStrToLong_ul(arg->data, NULL, 10, value);
    else
        ret = virStrToLong_ulp(arg->data, NULL, 10, value);
    if (ret < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;
1624

1625
    return ret;
1626
}
1627

1628
/*
E
Eric Blake 已提交
1629
 * vshCommandOptUL:
1630
 * @ctl virsh control structure
E
Eric Blake 已提交
1631 1632 1633 1634
 * @cmd command reference
 * @name option name
 * @value result
 *
1635 1636 1637
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1638
int
1639 1640
vshCommandOptUL(vshControl *ctl, const vshCmd *cmd,
                const char *name, unsigned long *value)
1641
{
1642
    return vshCommandOptULInternal(ctl, cmd, name, value, false);
1643
}
E
Eric Blake 已提交
1644

1645 1646
/**
 * vshCommandOptULWrap:
1647
 * @ctl virsh control structure
1648 1649 1650 1651 1652 1653 1654 1655
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to unsigned long, wraps negative numbers to positive
 * See vshCommandOptInt()
 */
int
1656 1657
vshCommandOptULWrap(vshControl *ctl, const vshCmd *cmd,
                    const char *name, unsigned long *value)
1658
{
1659
    return vshCommandOptULInternal(ctl, cmd, name, value, true);
1660 1661
}

E
Eric Blake 已提交
1662 1663
/**
 * vshCommandOptString:
1664
 * @ctl virsh control structure
E
Eric Blake 已提交
1665 1666 1667 1668
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
1669
 * Returns option as STRING
E
Eric Blake 已提交
1670 1671 1672 1673
 * 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 已提交
1674
 */
E
Eric Blake 已提交
1675
int
1676 1677
vshCommandOptString(vshControl *ctl ATTRIBUTE_UNUSED, const vshCmd *cmd,
                    const char *name, const char **value)
1678
{
E
Eric Blake 已提交
1679 1680 1681
    vshCmdOpt *arg;
    int ret;

1682
    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
E
Eric Blake 已提交
1683
        return ret;
1684

1685
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK))
E
Eric Blake 已提交
1686 1687 1688
        return -1;
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
1689 1690
}

1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
/**
 * 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;

1717
    ret = vshCommandOpt(cmd, name, &arg, true);
1718 1719 1720 1721 1722 1723
    /* 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");
1724
    else if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK))
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
        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 已提交
1736 1737
/**
 * vshCommandOptLongLong:
1738
 * @ctl virsh control structure
E
Eric Blake 已提交
1739 1740 1741 1742
 * @cmd command reference
 * @name option name
 * @value result
 *
1743
 * Returns option as long long
1744
 * See vshCommandOptInt()
1745
 */
E
Eric Blake 已提交
1746
int
1747
vshCommandOptLongLong(vshControl *ctl, const vshCmd *cmd,
1748
                      const char *name, long long *value)
1749
{
E
Eric Blake 已提交
1750 1751
    vshCmdOpt *arg;
    int ret;
1752

1753
    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
E
Eric Blake 已提交
1754 1755
        return ret;

1756 1757 1758 1759 1760 1761 1762 1763
    if ((ret = virStrToLong_ll(arg->data, NULL, 10, value)) < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;

    return ret;
1764 1765
}

1766
static int
1767
vshCommandOptULongLongInternal(vshControl *ctl,
1768
                               const vshCmd *cmd,
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
                               const char *name,
                               unsigned long long *value,
                               bool wrap)
{
    vshCmdOpt *arg;
    int ret;

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

1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
    if (wrap)
        ret = virStrToLong_ull(arg->data, NULL, 10, value);
    else
        ret = virStrToLong_ullp(arg->data, NULL, 10, value);
    if (ret < 0)
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
    else
        ret = 1;
1789

1790
    return ret;
1791 1792
}

E
Eric Blake 已提交
1793 1794
/**
 * vshCommandOptULongLong:
1795
 * @ctl virsh control structure
E
Eric Blake 已提交
1796 1797 1798 1799
 * @cmd command reference
 * @name option name
 * @value result
 *
1800
 * Returns option as long long, rejects negative numbers
E
Eric Blake 已提交
1801 1802
 * See vshCommandOptInt()
 */
E
Eric Blake 已提交
1803
int
1804 1805
vshCommandOptULongLong(vshControl *ctl, const vshCmd *cmd,
                       const char *name, unsigned long long *value)
1806
{
1807
    return vshCommandOptULongLongInternal(ctl, cmd, name, value, false);
1808 1809
}

1810 1811
/**
 * vshCommandOptULongLongWrap:
1812
 * @ctl virsh control structure
1813 1814 1815 1816 1817 1818 1819 1820
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long, wraps negative numbers to positive
 * See vshCommandOptInt()
 */
int
1821 1822
vshCommandOptULongLongWrap(vshControl *ctl, const vshCmd *cmd,
                           const char *name, unsigned long long *value)
1823
{
1824
    return vshCommandOptULongLongInternal(ctl, cmd, name, value, true);
1825
}
1826

E
Eric Blake 已提交
1827 1828
/**
 * vshCommandOptScaledInt:
1829
 * @ctl virsh control structure
E
Eric Blake 已提交
1830 1831 1832 1833 1834 1835 1836 1837 1838
 * @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 已提交
1839
int
1840
vshCommandOptScaledInt(vshControl *ctl, const vshCmd *cmd,
1841 1842
                       const char *name, unsigned long long *value,
                       int scale, unsigned long long max)
E
Eric Blake 已提交
1843
{
1844
    vshCmdOpt *arg;
E
Eric Blake 已提交
1845
    char *end;
1846
    int ret;
E
Eric Blake 已提交
1847

1848
    if ((ret = vshCommandOpt(cmd, name, &arg, true)) <= 0)
E
Eric Blake 已提交
1849
        return ret;
1850
    if (virStrToLong_ullp(arg->data, &end, 10, value) < 0 ||
E
Eric Blake 已提交
1851
        virScaleInteger(value, end, scale, max) < 0)
1852 1853 1854 1855 1856 1857 1858 1859
    {
        vshError(ctl,
                 _("Numeric value '%s' for <%s> option is malformed or out of range"),
                 arg->data, name);
        ret = -1;
    } else {
        ret = 1;
    }
1860

1861
    return ret;
E
Eric Blake 已提交
1862 1863 1864
}


E
Eric Blake 已提交
1865 1866 1867 1868 1869 1870 1871 1872 1873
/**
 * 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 已提交
1874
 */
E
Eric Blake 已提交
1875
bool
1876
vshCommandOptBool(const vshCmd *cmd, const char *name)
1877
{
E
Eric Blake 已提交
1878 1879
    vshCmdOpt *dummy;

1880
    return vshCommandOpt(cmd, name, &dummy, false) == 1;
K
Karel Zak 已提交
1881 1882
}

E
Eric Blake 已提交
1883 1884
/**
 * vshCommandOptArgv:
1885
 * @ctl virsh control structure
E
Eric Blake 已提交
1886 1887 1888
 * @cmd command reference
 * @opt starting point for the search
 *
1889 1890
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
1891
 *
1892
 * Requires that a VSH_OT_ARGV option be last in the
1893 1894
 * list of supported options in CMD->def->opts.
 */
E
Eric Blake 已提交
1895
const vshCmdOpt *
1896 1897
vshCommandOptArgv(vshControl *ctl ATTRIBUTE_UNUSED, const vshCmd *cmd,
                  const vshCmdOpt *opt)
1898
{
1899
    opt = opt ? opt->next : cmd->opts;
1900 1901

    while (opt) {
1902
        if (opt->def->type == VSH_OT_ARGV)
1903
            return opt;
1904 1905 1906 1907 1908
        opt = opt->next;
    }
    return NULL;
}

1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
/*
 * vshCommandOptTimeoutToMs:
 * @ctl virsh control structure
 * @cmd command reference
 * @timeout result
 *
 * Parse an optional --timeout parameter in seconds, but store the
 * value of the timeout in milliseconds.
 * See vshCommandOptInt()
 */
1919 1920 1921
int
vshCommandOptTimeoutToMs(vshControl *ctl, const vshCmd *cmd, int *timeout)
{
1922 1923
    int ret;
    unsigned int utimeout;
1924

1925
    if ((ret = vshCommandOptUInt(ctl, cmd, "timeout", &utimeout)) <= 0)
1926 1927 1928 1929 1930 1931
        return ret;

    /* Ensure that the timeout is not zero and that we can convert
     * it from seconds to milliseconds without overflowing. */
    if (utimeout == 0 || utimeout > INT_MAX / 1000) {
        vshError(ctl,
1932 1933
                 _("Numeric value '%u' for <%s> option is malformed or out of range"),
                 utimeout,
1934 1935 1936 1937
                 "timeout");
        ret = -1;
    } else {
        *timeout = ((int) utimeout) * 1000;
1938 1939
    }

1940 1941
    return ret;
}
1942

1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
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 已提交
1960 1961 1962
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
1963
static bool
1964
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
1965
{
E
Eric Blake 已提交
1966
    bool ret = true;
1967 1968

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

1972 1973
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
1974 1975
            vshReconnect(ctl);

1976 1977 1978
        if (enable_timing)
            GETTIMEOFDAY(&before);

1979 1980 1981 1982 1983 1984 1985
        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;
        }
1986

1987 1988 1989
        if (enable_timing)
            GETTIMEOFDAY(&after);

1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
        /* 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++;

2000
        if (!ret)
E
Eric Blake 已提交
2001
            vshReportError(ctl);
J
John Levon 已提交
2002

2003 2004
        if (STREQ(cmd->def->name, "quit") ||
            STREQ(cmd->def->name, "exit"))        /* hack ... */
K
Karel Zak 已提交
2005 2006
            return ret;

E
Eric Blake 已提交
2007
        if (enable_timing) {
2008
            double diff_ms = (((after.tv_sec - before.tv_sec) * 1000.0) +
E
Eric Blake 已提交
2009 2010 2011 2012
                              ((after.tv_usec - before.tv_usec) / 1000.0));

            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"), diff_ms);
        } else {
K
Karel Zak 已提交
2013
            vshPrintExtra(ctl, "\n");
E
Eric Blake 已提交
2014
        }
K
Karel Zak 已提交
2015 2016 2017 2018 2019 2020
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
2021
 * Command parsing
K
Karel Zak 已提交
2022 2023 2024
 * ---------------
 */

2025 2026 2027 2028 2029 2030 2031
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 已提交
2032 2033 2034 2035
typedef struct _vshCommandParser vshCommandParser;
struct _vshCommandParser {
    vshCommandToken(*getNextArg)(vshControl *, vshCommandParser *,
                                 char **);
L
Lai Jiangshan 已提交
2036
    /* vshCommandStringGetArg() */
2037
    char *pos;
L
Lai Jiangshan 已提交
2038 2039 2040
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
E
Eric Blake 已提交
2041
};
2042

E
Eric Blake 已提交
2043
static bool
2044
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
2045
{
K
Karel Zak 已提交
2046 2047 2048
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
2049

K
Karel Zak 已提交
2050 2051 2052 2053
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
2054

2055
    while (1) {
K
Karel Zak 已提交
2056
        vshCmdOpt *last = NULL;
2057
        const vshCmdDef *cmd = NULL;
2058
        vshCommandToken tk;
L
Lai Jiangshan 已提交
2059
        bool data_only = false;
2060 2061 2062
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
2063

K
Karel Zak 已提交
2064
        first = NULL;
2065

2066
        while (1) {
2067
            const vshCmdOptDef *opt = NULL;
2068

K
Karel Zak 已提交
2069
            tkdata = NULL;
2070
            tk = parser->getNextArg(ctl, parser, &tkdata);
2071 2072

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2073
                goto syntaxError;
H
Hu Tao 已提交
2074 2075
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
2076
                break;
H
Hu Tao 已提交
2077
            }
2078 2079

            if (cmd == NULL) {
K
Karel Zak 已提交
2080 2081
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
2082
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
2083
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
2084
                }
2085 2086 2087 2088 2089 2090 2091
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
2092
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
2093 2094 2095 2096
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
2097
                char *optstr = strchr(tkdata + 2, '=');
C
Cole Robinson 已提交
2098
                int opt_index = 0;
2099

2100 2101 2102 2103
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
2104
                /* Special case 'help' to ignore all spurious options */
2105
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
2106 2107
                                               &opts_seen, &opt_index,
                                               &optstr))) {
2108
                    VIR_FREE(optstr);
2109 2110
                    if (STREQ(cmd->name, "help"))
                        continue;
K
Karel Zak 已提交
2111 2112
                    goto syntaxError;
                }
2113
                VIR_FREE(tkdata);
K
Karel Zak 已提交
2114 2115 2116

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
2117 2118 2119
                    if (optstr)
                        tkdata = optstr;
                    else
2120
                        tk = parser->getNextArg(ctl, parser, &tkdata);
2121
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2122
                        goto syntaxError;
2123
                    if (tk != VSH_TK_ARG) {
2124
                        vshError(ctl,
2125
                                 _("expected syntax: --%s <%s>"),
2126 2127
                                 opt->name,
                                 opt->type ==
2128
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
2129 2130
                        goto syntaxError;
                    }
2131 2132
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
2133 2134 2135 2136
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
2137
                                 opt->name);
2138 2139 2140
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
2141
                }
L
Lai Jiangshan 已提交
2142 2143 2144 2145
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
2146
            } else {
2147
 get_data:
2148
                /* Special case 'help' to ignore spurious data */
2149
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
2150 2151
                                             &opts_seen)) &&
                     STRNEQ(cmd->name, "help")) {
2152
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
2153 2154 2155 2156 2157
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
2158
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
2159

K
Karel Zak 已提交
2160 2161 2162 2163
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
2164

K
Karel Zak 已提交
2165 2166 2167 2168 2169
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
2170

2171
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
2172 2173
                         cmd->name,
                         opt->name,
2174 2175
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
2176 2177
            }
        }
2178

D
Daniel Veillard 已提交
2179
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
2180
        if (cmd) {
2181
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
            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;
            }
2201

K
Karel Zak 已提交
2202 2203 2204 2205
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

2206
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
2207
                VIR_FREE(c);
2208
                goto syntaxError;
2209
            }
2210

K
Karel Zak 已提交
2211 2212 2213 2214 2215 2216
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
2217 2218 2219

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
2220
    }
2221

E
Eric Blake 已提交
2222
    return true;
K
Karel Zak 已提交
2223

2224
 syntaxError:
2225
    if (ctl->cmd) {
K
Karel Zak 已提交
2226
        vshCommandFree(ctl->cmd);
2227 2228
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
2229 2230
    if (first)
        vshCommandOptFree(first);
2231
    VIR_FREE(tkdata);
E
Eric Blake 已提交
2232
    return false;
K
Karel Zak 已提交
2233 2234
}

2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
/* --------------------
 * 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 已提交
2253 2254
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
2255 2256 2257 2258
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
2259
        return false;
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 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331

    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 已提交
2332 2333
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
2334 2335 2336 2337
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
2338
        return false;
2339 2340 2341 2342 2343 2344

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

K
Karel Zak 已提交
2345
/* ---------------
2346
 * Misc utils
K
Karel Zak 已提交
2347 2348
 * ---------------
 */
E
Eric Blake 已提交
2349
int
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
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;
}

2377 2378
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
E
Eric Blake 已提交
2379
char *
2380 2381 2382 2383 2384
vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
{
    int ret = 0;
    char *str = NULL;

2385
    switch (item->type) {
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
    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 已提交
2407
        str = vshStrdup(ctl, item->value.b ? _("yes") : _("no"));
2408 2409
        break;

2410 2411 2412 2413
    case VIR_TYPED_PARAM_STRING:
        str = vshStrdup(ctl, item->value.s);
        break;

2414
    default:
2415
        vshError(ctl, _("unimplemented parameter type %d"), item->type);
2416 2417
    }

2418
    if (ret < 0) {
2419
        vshError(ctl, "%s", _("Out of memory"));
2420 2421
        exit(EXIT_FAILURE);
    }
2422 2423 2424
    return str;
}

E
Eric Blake 已提交
2425
void
2426
vshDebug(vshControl *ctl, int level, const char *format, ...)
2427
{
K
Karel Zak 已提交
2428
    va_list ap;
2429
    char *str;
K
Karel Zak 已提交
2430

2431 2432 2433 2434 2435 2436 2437
    /* Aligning log levels to that of libvirt.
     * Traces with levels >=  user-specified-level
     * gets logged into file
     */
    if (level < ctl->debug)
        return;

2438
    va_start(ap, format);
2439
    vshOutputLogFile(ctl, level, format, ap);
2440 2441
    va_end(ap);

K
Karel Zak 已提交
2442
    va_start(ap, format);
2443 2444 2445 2446 2447
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2448
    va_end(ap);
2449 2450
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
2451 2452
}

E
Eric Blake 已提交
2453
void
2454
vshPrintExtra(vshControl *ctl, const char *format, ...)
2455
{
K
Karel Zak 已提交
2456
    va_list ap;
2457
    char *str;
2458

2459
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
2460
        return;
2461

K
Karel Zak 已提交
2462
    va_start(ap, format);
2463 2464 2465 2466 2467
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2468
    va_end(ap);
2469
    fputs(str, stdout);
2470
    VIR_FREE(str);
K
Karel Zak 已提交
2471 2472
}

K
Karel Zak 已提交
2473

2474
bool
2475 2476
vshTTYIsInterruptCharacter(vshControl *ctl ATTRIBUTE_UNUSED,
                           const char chr ATTRIBUTE_UNUSED)
2477
{
2478
#ifndef WIN32
2479 2480 2481
    if (ctl->istty &&
        ctl->termattr.c_cc[VINTR] == chr)
        return true;
2482
#endif
2483 2484 2485 2486 2487

    return false;
}


2488 2489 2490 2491 2492 2493 2494
bool
vshTTYAvailable(vshControl *ctl)
{
    return ctl->istty;
}


2495
int
2496
vshTTYDisableInterrupt(vshControl *ctl ATTRIBUTE_UNUSED)
2497
{
2498
#ifndef WIN32
2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512
    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;
2513
#endif
2514 2515 2516 2517 2518 2519

    return 0;
}


int
2520
vshTTYRestore(vshControl *ctl ATTRIBUTE_UNUSED)
2521
{
2522
#ifndef WIN32
2523 2524 2525 2526 2527
    if (!ctl->istty)
        return 0;

    if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &ctl->termattr) < 0)
        return -1;
2528
#endif
2529 2530 2531 2532 2533

    return 0;
}


2534
#if !defined(WIN32) && !defined(HAVE_CFMAKERAW)
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
/* 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;
}
2546
#endif /* !WIN32 && !HAVE_CFMAKERAW */
2547 2548 2549


int
2550 2551
vshTTYMakeRaw(vshControl *ctl ATTRIBUTE_UNUSED,
              bool report_errors ATTRIBUTE_UNUSED)
2552
{
2553
#ifndef WIN32
2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
    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;
    }
2574
#endif
2575 2576 2577 2578 2579

    return 0;
}


E
Eric Blake 已提交
2580
void
2581
vshError(vshControl *ctl, const char *format, ...)
2582
{
K
Karel Zak 已提交
2583
    va_list ap;
2584
    char *str;
2585

2586 2587 2588 2589 2590
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
2591

2592 2593 2594 2595
    /* 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);
2596
    fputs(_("error: "), stderr);
2597

K
Karel Zak 已提交
2598
    va_start(ap, format);
2599 2600 2601
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
2602 2603
    va_end(ap);

2604
    fprintf(stderr, "%s\n", NULLSTR(str));
2605
    fflush(stderr);
2606
    VIR_FREE(str);
K
Karel Zak 已提交
2607 2608
}

2609

J
Jiri Denemark 已提交
2610 2611 2612 2613 2614
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
E
Eric Blake 已提交
2625
            vshReportError(ctl);
J
Jiri Denemark 已提交
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 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
/*
 * 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 已提交
2773
/*
M
Martin Kletzander 已提交
2774
 * Initialize debug settings.
K
Karel Zak 已提交
2775
 */
M
Martin Kletzander 已提交
2776 2777
static void
vshInitDebug(vshControl *ctl)
2778
{
2779
    const char *debugEnv;
2780

J
Jiri Denemark 已提交
2781
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
2782
        /* log level not set from commandline, check env variable */
2783
        debugEnv = virGetEnvAllowSUID("VIRSH_DEBUG");
2784
        if (debugEnv) {
J
Jiri Denemark 已提交
2785 2786 2787
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
2788 2789
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
2790 2791
            } else {
                ctl->debug = debug;
2792 2793 2794 2795 2796 2797
            }
        }
    }

    if (ctl->logfile == NULL) {
        /* log file not set from cmdline */
2798
        debugEnv = virGetEnvBlockSUID("VIRSH_LOG_FILE");
2799 2800
        if (debugEnv && *debugEnv) {
            ctl->logfile = vshStrdup(ctl, debugEnv);
M
Martin Kletzander 已提交
2801
            vshOpenLogFile(ctl);
2802 2803
        }
    }
M
Martin Kletzander 已提交
2804 2805 2806 2807 2808 2809 2810 2811
}

/*
 * Initialize connection.
 */
static bool
vshInit(vshControl *ctl)
{
M
Martin Kletzander 已提交
2812 2813 2814 2815
    /* 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 已提交
2816 2817
    if (ctl->conn)
        return false;
2818

2819 2820
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2821

2822
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
2823
        return false;
2824

J
Jiri Denemark 已提交
2825 2826 2827 2828
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

2829 2830 2831 2832
    if ((ctl->eventTimerId = virEventAddTimeout(-1, vshEventTimeout, ctl,
                                                NULL)) < 0)
        return false;

2833
    if (ctl->name) {
2834
        vshReconnect(ctl);
2835 2836 2837 2838 2839 2840 2841
        /* 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 已提交
2842
            vshReportError(ctl);
2843 2844
            return false;
        }
2845
    }
K
Karel Zak 已提交
2846

E
Eric Blake 已提交
2847
    return true;
K
Karel Zak 已提交
2848 2849
}

2850 2851
#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

2852 2853 2854 2855 2856
/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
E
Eric Blake 已提交
2857
void
2858 2859 2860 2861 2862
vshOpenLogFile(vshControl *ctl)
{
    if (ctl->logfile == NULL)
        return;

2863
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
2864
        vshError(ctl, "%s",
J
Jim Meyering 已提交
2865
                 _("failed to open the log file. check the log file path"));
2866
        exit(EXIT_FAILURE);
2867 2868 2869 2870 2871 2872 2873 2874
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
E
Eric Blake 已提交
2875
void
2876 2877
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
2878
{
2879
    virBuffer buf = VIR_BUFFER_INITIALIZER;
J
John Ferlan 已提交
2880
    char *str = NULL;
2881
    size_t len;
2882
    const char *lvl = "";
2883
    time_t stTime;
2884
    struct tm stTm;
2885 2886 2887 2888 2889 2890 2891 2892 2893

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

    /**
     * create log format
     *
     * [YYYY.MM.DD HH:MM:SS SIGNATURE PID] LOG_LEVEL message
    */
2894 2895
    time(&stTime);
    localtime_r(&stTime, &stTm);
2896
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
2897 2898 2899 2900 2901 2902
                      (1900 + stTm.tm_year),
                      (1 + stTm.tm_mon),
                      stTm.tm_mday,
                      stTm.tm_hour,
                      stTm.tm_min,
                      stTm.tm_sec,
2903 2904
                      SIGN_NAME,
                      (int) getpid());
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
    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;
    }
2925 2926 2927
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
2928

2929 2930
    if (virBufferError(&buf))
        goto error;
2931

2932 2933 2934 2935 2936
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
2937
    }
2938

2939 2940 2941 2942
    /* write log */
    if (safewrite(ctl->log_fd, str, len) < 0)
        goto error;

2943
    VIR_FREE(str);
2944 2945
    return;

2946
 error:
2947 2948 2949 2950
    vshCloseLogFile(ctl);
    vshError(ctl, "%s", _("failed to write the log file"));
    virBufferFreeAndReset(&buf);
    VIR_FREE(str);
2951 2952 2953 2954 2955 2956 2957
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
E
Eric Blake 已提交
2958
void
2959 2960
vshCloseLogFile(vshControl *ctl)
{
2961 2962
    char ebuf[1024];

2963
    /* log file close */
2964 2965
    if (VIR_CLOSE(ctl->log_fd) < 0) {
        vshError(ctl, _("%s: failed to write log file: %s"),
2966 2967
                 ctl->logfile ? ctl->logfile : "?",
                 virStrerror(errno, ebuf, sizeof(ebuf)));
2968 2969 2970
    }

    if (ctl->logfile) {
2971
        VIR_FREE(ctl->logfile);
2972 2973 2974 2975
        ctl->logfile = NULL;
    }
}

2976
#if WITH_READLINE
2977

K
Karel Zak 已提交
2978 2979 2980 2981 2982
/* -----------------
 * Readline stuff
 * -----------------
 */

2983
/*
K
Karel Zak 已提交
2984 2985
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
2986
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
2987 2988
 */
static char *
2989 2990
vshReadlineCommandGenerator(const char *text, int state)
{
2991
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
2992
    const char *name;
2993 2994
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
2995 2996

    if (!state) {
2997 2998
        grp_list_index = 0;
        cmd_list_index = 0;
2999
        len = strlen(text);
K
Karel Zak 已提交
3000 3001
    }

3002 3003
    grp = cmdGroups;

K
Karel Zak 已提交
3004
    /* Return the next name which partially matches from the
3005
     * command list.
K
Karel Zak 已提交
3006
     */
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
    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 已提交
3021 3022 3023 3024 3025 3026 3027
    }

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

static char *
3028 3029
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
3030
    static int list_index, len;
3031
    static const vshCmdDef *cmd;
K
Karel Zak 已提交
3032
    const char *name;
K
Karel Zak 已提交
3033 3034 3035 3036 3037 3038 3039 3040 3041

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

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

3042
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
3043
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
3044 3045 3046

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
3047
        len = strlen(text);
3048
        VIR_FREE(cmdname);
K
Karel Zak 已提交
3049 3050 3051 3052
    }

    if (!cmd)
        return NULL;
3053

3054 3055 3056
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
3057
    while ((name = cmd->opts[list_index].name)) {
3058
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
3059
        char *res;
3060

K
Karel Zak 已提交
3061
        list_index++;
3062

3063
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
3064 3065
            /* ignore non --option */
            continue;
3066

K
Karel Zak 已提交
3067
        if (len > 2) {
3068
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
3069 3070
                continue;
        }
3071
        res = vshMalloc(NULL, strlen(name) + 3);
3072
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
3073 3074 3075 3076 3077 3078 3079 3080
        return res;
    }

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

static char **
3081 3082 3083
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
3084 3085
    char **matches = (char **) NULL;

3086
    if (start == 0)
K
Karel Zak 已提交
3087
        /* command name generator */
3088
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
3089 3090
    else
        /* commands options */
3091
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
3092 3093 3094
    return matches;
}

3095
# define VIRSH_HISTSIZE_MAX 500000
K
Karel Zak 已提交
3096

3097 3098
static int
vshReadlineInit(vshControl *ctl)
3099
{
3100
    char *userdir = NULL;
3101 3102
    int max_history = 500;
    const char *histsize_str;
3103

3104 3105 3106 3107 3108
    /* 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 已提交
3109 3110 3111

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

    /* Limit the total size of the history buffer */
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
    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);
3127

3128
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
3129
    userdir = virGetUserCacheDirectory();
3130

3131 3132
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
3133
        return -1;
3134
    }
3135

3136
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
3137
        vshError(ctl, "%s", _("Out of memory"));
3138
        VIR_FREE(userdir);
3139 3140 3141 3142 3143
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
3144
        VIR_FREE(userdir);
3145 3146 3147
        return -1;
    }

3148
    VIR_FREE(userdir);
3149 3150 3151 3152 3153 3154 3155

    read_history(ctl->historyfile);

    return 0;
}

static void
3156
vshReadlineDeinit(vshControl *ctl)
3157 3158
{
    if (ctl->historyfile != NULL) {
3159 3160
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
3161 3162
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
3163
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
3164
        } else {
3165
            write_history(ctl->historyfile);
E
Eric Blake 已提交
3166
        }
3167 3168
    }

3169 3170
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
3171 3172
}

3173
static char *
3174
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
3175
{
3176
    return readline(prompt);
3177 3178
}

3179
#else /* !WITH_READLINE */
3180

3181
static int
3182
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
3183 3184 3185 3186 3187
{
    /* empty */
    return 0;
}

3188
static void
3189
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
3190 3191 3192 3193 3194
{
    /* empty */
}

static char *
3195
vshReadline(vshControl *ctl, const char *prompt)
3196 3197 3198 3199 3200
{
    char line[1024];
    char *r;
    int len;

3201 3202
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
3203 3204 3205
    if (r == NULL) return NULL; /* EOF */

    /* Chomp trailing \n */
3206
    len = strlen(r);
3207 3208 3209
    if (len > 0 && r[len-1] == '\n')
        r[len-1] = '\0';

3210
    return vshStrdup(ctl, r);
3211 3212
}

3213
#endif /* !WITH_READLINE */
3214

3215 3216 3217 3218 3219 3220
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
3221
/*
J
Jim Meyering 已提交
3222
 * Deinitialize virsh
K
Karel Zak 已提交
3223
 */
E
Eric Blake 已提交
3224
static bool
3225
vshDeinit(vshControl *ctl)
3226
{
3227
    vshReadlineDeinit(ctl);
3228
    vshCloseLogFile(ctl);
3229
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
3230
    if (ctl->conn) {
3231
        int ret;
3232 3233 3234 3235 3236 3237 3238
        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 已提交
3239
    }
D
Daniel P. Berrange 已提交
3240 3241
    virResetLastError();

J
Jiri Denemark 已提交
3242
    if (ctl->eventLoopStarted) {
3243 3244 3245 3246
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
3247
        /* HACK: Add a dummy timeout to break event loop */
3248 3249 3250 3251 3252
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
3253 3254 3255
        if (timer != -1)
            virEventRemoveTimeout(timer);

3256 3257 3258
        if (ctl->eventTimerId != -1)
            virEventRemoveTimeout(ctl->eventTimerId);

J
Jiri Denemark 已提交
3259 3260 3261
        ctl->eventLoopStarted = false;
    }

3262 3263
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
3264
    return true;
K
Karel Zak 已提交
3265
}
3266

K
Karel Zak 已提交
3267 3268 3269
/*
 * Print usage
 */
E
Eric Blake 已提交
3270
static void
3271
vshUsage(void)
3272
{
3273
    const vshCmdGrp *grp;
3274
    const vshCmdDef *cmd;
3275

L
Lai Jiangshan 已提交
3276 3277
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
3278
                      "  options:\n"
3279 3280
                      "    -c | --connect=URI      hypervisor connection URI\n"
                      "    -d | --debug=NUM        debug level [0-4]\n"
3281
                      "    -e | --escape <char>    set escape sequence for console\n"
3282
                      "    -h | --help             this help\n"
3283 3284 3285 3286
                      "    -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"
3287
                      "    -l | --log=FILE         output logging to file\n"
3288
                      "    -q | --quiet            quiet mode\n"
3289
                      "    -r | --readonly         connect readonly\n"
3290
                      "    -t | --timing           print timing information\n"
3291 3292 3293
                      "    -v                      short version\n"
                      "    -V                      long version\n"
                      "         --version[=TYPE]   version, TYPE is short or long (default short)\n"
3294
                      "  commands (non interactive mode):\n\n"), progname, progname);
3295

3296
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
3297 3298 3299 3300 3301
        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;
3302
            fprintf(stdout,
E
Eric Blake 已提交
3303 3304 3305
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
3306 3307 3308 3309 3310
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
3311 3312 3313
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
3314 3315
}

3316 3317 3318 3319 3320 3321 3322 3323 3324 3325
/*
 * 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 已提交
3326 3327
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
3328
#ifdef WITH_QEMU
3329
    vshPrint(ctl, " QEMU/KVM");
3330
#endif
D
Doug Goldstein 已提交
3331 3332 3333
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
3334 3335 3336
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
3337 3338 3339 3340 3341 3342
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
3343 3344 3345
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
3346 3347
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
3348
#endif
D
Doug Goldstein 已提交
3349 3350
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
3351
#endif
D
Doug Goldstein 已提交
3352 3353
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
3354 3355 3356 3357
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
3358 3359
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
3360
#endif
D
Doug Goldstein 已提交
3361 3362
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
3363
#endif
3364 3365 3366
#ifdef WITH_BHYVE
    vshPrint(ctl, " Bhyve");
#endif
3367 3368 3369 3370 3371
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
3372
    vshPrint(ctl, "%s", _(" Networking:"));
3373 3374 3375 3376 3377 3378 3379 3380 3381
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
3382
#if defined(WITH_INTERFACE)
D
Doug Goldstein 已提交
3383
    vshPrint(ctl, " Interface");
3384 3385
# if defined(WITH_NETCF)
    vshPrint(ctl, " netcf");
3386
# elif defined(WITH_UDEV)
3387
    vshPrint(ctl, " udev");
3388
# endif
3389 3390 3391 3392 3393 3394 3395 3396 3397
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
3398
    vshPrint(ctl, "%s", _(" Storage:"));
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
#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");
3419 3420 3421
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
3422 3423 3424
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
3425 3426 3427
#endif
#ifdef WITH_STORAGE_GLUSTER
    vshPrint(ctl, " Gluster");
3428 3429 3430
#endif
    vshPrint(ctl, "\n");

3431
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
3432 3433 3434
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452
#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
3453
#if WITH_READLINE
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475
    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 已提交
3476
static bool
3477 3478
vshParseArgv(vshControl *ctl, int argc, char **argv)
{
3479
    int arg, len, debug, keepalive;
3480
    size_t i;
3481
    int longindex = -1;
3482
    struct option opt[] = {
3483
        {"connect", required_argument, NULL, 'c'},
3484
        {"debug", required_argument, NULL, 'd'},
3485
        {"escape", required_argument, NULL, 'e'},
3486
        {"help", no_argument, NULL, 'h'},
3487 3488
        {"keepalive-interval", required_argument, NULL, 'k'},
        {"keepalive-count", required_argument, NULL, 'K'},
3489
        {"log", required_argument, NULL, 'l'},
3490
        {"quiet", no_argument, NULL, 'q'},
3491
        {"readonly", no_argument, NULL, 'r'},
3492 3493 3494 3495 3496 3497 3498 3499
        {"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. */
3500
    while ((arg = getopt_long(argc, argv, "+:c:d:e:hk:K:l:qrtvV", opt, &longindex)) != -1) {
3501
        switch (arg) {
3502 3503 3504 3505
        case 'c':
            VIR_FREE(ctl->name);
            ctl->name = vshStrdup(ctl, optarg);
            break;
3506
        case 'd':
3507
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
3508 3509
                vshError(ctl, _("option %s takes a numeric argument"),
                         longindex == -1 ? "-d" : "--debug");
3510 3511
                exit(EXIT_FAILURE);
            }
3512 3513 3514 3515 3516
            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;
3517
            break;
3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530
        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;
3531 3532 3533 3534
        case 'h':
            vshUsage();
            exit(EXIT_SUCCESS);
            break;
3535
        case 'k':
E
Erik Skultety 已提交
3536 3537 3538 3539 3540 3541 3542 3543 3544 3545
            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"),
3546 3547 3548 3549 3550 3551
                         longindex == -1 ? "-k" : "--keepalive-interval");
                exit(EXIT_FAILURE);
            }
            ctl->keepalive_interval = keepalive;
            break;
        case 'K':
E
Erik Skultety 已提交
3552 3553 3554 3555 3556 3557 3558 3559 3560 3561
            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"),
3562 3563 3564 3565 3566
                         longindex == -1 ? "-K" : "--keepalive-count");
                exit(EXIT_FAILURE);
            }
            ctl->keepalive_count = keepalive;
            break;
3567 3568 3569 3570 3571
        case 'l':
            vshCloseLogFile(ctl);
            ctl->logfile = vshStrdup(ctl, optarg);
            vshOpenLogFile(ctl);
            break;
3572 3573 3574 3575 3576 3577
        case 'q':
            ctl->quiet = true;
            break;
        case 't':
            ctl->timing = true;
            break;
3578 3579
        case 'r':
            ctl->readonly = true;
3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
            /* fall through */
        case 'V':
            vshShowVersion(ctl);
            exit(EXIT_SUCCESS);
3590
        case ':':
3591
            for (i = 0; opt[i].name != NULL; i++) {
3592 3593
                if (opt[i].val == optopt)
                    break;
3594
            }
3595 3596 3597 3598 3599 3600
            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);
3601
        case '?':
3602 3603 3604 3605
            if (optopt)
                vshError(ctl, _("unsupported option '-%c'. See --help."), optopt);
            else
                vshError(ctl, _("unsupported option '%s'. See --help."), argv[optind - 1]);
3606
            exit(EXIT_FAILURE);
3607
        default:
3608
            vshError(ctl, _("unknown option"));
3609 3610
            exit(EXIT_FAILURE);
        }
3611
        longindex = -1;
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627
    }

    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[] = {
3628 3629 3630 3631 3632
    {.name = "cd",
     .handler = cmdCd,
     .opts = opts_cd,
     .info = info_cd,
     .flags = VSH_CMD_FLAG_NOCONNECT
3633 3634 3635 3636 3637 3638
    },
    {.name = "connect",
     .handler = cmdConnect,
     .opts = opts_connect,
     .info = info_connect,
     .flags = VSH_CMD_FLAG_NOCONNECT
3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670
    },
    {.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}
3671
};
3672

3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687
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 已提交
3688

3689 3690 3691 3692
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
3693
    const char *defaultConn;
E
Eric Blake 已提交
3694
    bool ret = true;
K
Karel Zak 已提交
3695

3696 3697 3698
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
3699
    ctl->debug = VSH_DEBUG_DEFAULT;
E
Eric Blake 已提交
3700
    ctl->escapeChar = "^]";     /* Same default as telnet */
3701 3702 3703 3704 3705

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

3706 3707 3708
    ctl->eventPipe[0] = -1;
    ctl->eventPipe[1] = -1;
    ctl->eventTimerId = -1;
3709

3710 3711
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
3712
        /* failure to setup locale is not fatal */
3713
    }
3714
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
3715
        perror("bindtextdomain");
E
Eric Blake 已提交
3716
        return EXIT_FAILURE;
3717
    }
3718
    if (!textdomain(PACKAGE)) {
3719
        perror("textdomain");
E
Eric Blake 已提交
3720
        return EXIT_FAILURE;
3721 3722
    }

3723 3724 3725
    if (isatty(STDIN_FILENO)) {
        ctl->istty = true;

3726
#ifndef WIN32
3727 3728
        if (tcgetattr(STDIN_FILENO, &ctl->termattr) < 0)
            ctl->istty = false;
3729
#endif
3730 3731
    }

3732 3733 3734 3735 3736
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

3737 3738 3739 3740 3741
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

3742 3743
    virFileActivateDirOverride(argv[0]);

3744
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
3745 3746 3747
        progname = argv[0];
    else
        progname++;
3748

3749
    if ((defaultConn = virGetEnvBlockSUID("VIRSH_DEFAULT_CONNECT_URI")))
E
Eric Blake 已提交
3750
        ctl->name = vshStrdup(ctl, defaultConn);
3751

M
Martin Kletzander 已提交
3752
    vshInitDebug(ctl);
3753

M
Martin Kletzander 已提交
3754 3755
    if (!vshParseArgv(ctl, argc, argv) ||
        !vshInit(ctl)) {
D
Daniel P. Berrange 已提交
3756
        vshDeinit(ctl);
K
Karel Zak 已提交
3757
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3758
    }
3759

K
Karel Zak 已提交
3760
    if (!ctl->imode) {
3761
        ret = vshCommandRun(ctl, ctl->cmd);
3762
    } else {
K
Karel Zak 已提交
3763 3764
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
3765
            vshPrint(ctl,
3766
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
3767
                     progname);
J
Jim Meyering 已提交
3768
            vshPrint(ctl, "%s",
3769
                     _("Type:  'help' for help with commands\n"
3770
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
3771
        }
3772 3773 3774 3775 3776 3777

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

K
Karel Zak 已提交
3778
        do {
3779
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
3780
            ctl->cmdstr =
3781
                vshReadline(ctl, prompt);
3782 3783
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
3784
            if (*ctl->cmdstr) {
3785
#if WITH_READLINE
K
Karel Zak 已提交
3786
                add_history(ctl->cmdstr);
3787
#endif
3788
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
3789 3790
                    vshCommandRun(ctl, ctl->cmd);
            }
3791
            VIR_FREE(ctl->cmdstr);
3792
        } while (ctl->imode);
K
Karel Zak 已提交
3793

3794 3795
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
3796
    }
3797

K
Karel Zak 已提交
3798 3799
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
3800
}