virsh.c 113.3 KB
Newer Older
1
/*
2
 * virsh.c: a shell to exercise the libvirt API
3
 *
4
 * Copyright (C) 2005, 2007-2012 Red Hat, Inc.
5 6 7 8
 *
 * See COPYING.LIB for the License of this software
 *
 * Daniel Veillard <veillard@redhat.com>
K
Karel Zak 已提交
9
 * Karel Zak <kzak@redhat.com>
K
Karel Zak 已提交
10
 * Daniel P. Berrange <berrange@redhat.com>
11 12
 */

13
#include <config.h>
14

15
#include <stdio.h>
K
Karel Zak 已提交
16 17 18
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
19
#include <unistd.h>
20
#include <errno.h>
K
Karel Zak 已提交
21
#include <getopt.h>
22
#include <sys/types.h>
K
Karel Zak 已提交
23
#include <sys/time.h>
E
Eric Blake 已提交
24
#include <sys/wait.h>
J
Jim Meyering 已提交
25
#include "c-ctype.h"
26
#include <fcntl.h>
27
#include <locale.h>
28
#include <time.h>
29
#include <limits.h>
30
#include <assert.h>
31
#include <sys/stat.h>
32
#include <inttypes.h>
33
#include <signal.h>
34
#include <poll.h>
E
Eric Blake 已提交
35
#include <strings.h>
36
#include <termios.h>
K
Karel Zak 已提交
37

38 39 40
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
41
#include <libxml/xmlsave.h>
42

43
#ifdef HAVE_READLINE_READLINE_H
44 45
# include <readline/readline.h>
# include <readline/history.h>
46
#endif
K
Karel Zak 已提交
47

48
#include "internal.h"
49
#include "virterror_internal.h"
50
#include "base64.h"
51
#include "buf.h"
52
#include "console.h"
53
#include "util.h"
54
#include "memory.h"
55
#include "xml.h"
56
#include "libvirt/libvirt-qemu.h"
E
Eric Blake 已提交
57
#include "virfile.h"
58
#include "event_poll.h"
59
#include "configmake.h"
60
#include "threads.h"
E
Eric Blake 已提交
61
#include "command.h"
62
#include "virkeycode.h"
63
#include "virnetdevbandwidth.h"
64
#include "util/bitmap.h"
H
Hu Tao 已提交
65
#include "conf/domain_conf.h"
66
#include "virtypedparam.h"
67
#include "conf/virdomainlist.h"
K
Karel Zak 已提交
68 69 70

static char *progname;

71 72
#define VIRSH_MAX_XML_FILE 10*1024*1024

K
Karel Zak 已提交
73 74 75
#define VSH_PROMPT_RW    "virsh # "
#define VSH_PROMPT_RO    "virsh > "

76 77
#define VIR_FROM_THIS VIR_FROM_NONE

K
Karel Zak 已提交
78 79 80 81 82
#define GETTIMEOFDAY(T) gettimeofday(T, NULL)
#define DIFF_MSEC(T, U) \
        ((((int) ((T)->tv_sec - (U)->tv_sec)) * 1000000.0 + \
          ((int) ((T)->tv_usec - (U)->tv_usec))) / 1000.0)

83 84 85
/* Default escape char Ctrl-] as per telnet */
#define CTRL_CLOSE_BRACKET "^]"

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
/**
 * The log configuration
 */
#define MSG_BUFFER    4096
#define SIGN_NAME     "virsh"
#define DIR_MODE      (S_IWUSR | S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)  /* 0755 */
#define FILE_MODE     (S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH)                                /* 0644 */
#define LOCK_MODE     (S_IWUSR | S_IRUSR)                                                    /* 0600 */
#define LVL_DEBUG     "DEBUG"
#define LVL_INFO      "INFO"
#define LVL_NOTICE    "NOTICE"
#define LVL_WARNING   "WARNING"
#define LVL_ERROR     "ERROR"

/**
 * vshErrorLevel:
 *
J
Jim Meyering 已提交
103
 * Indicates the level of a log message
104 105 106 107 108 109 110 111 112
 */
typedef enum {
    VSH_ERR_DEBUG = 0,
    VSH_ERR_INFO,
    VSH_ERR_NOTICE,
    VSH_ERR_WARNING,
    VSH_ERR_ERROR
} vshErrorLevel;

J
Jiri Denemark 已提交
113 114
#define VSH_DEBUG_DEFAULT VSH_ERR_ERROR

K
Karel Zak 已提交
115 116 117 118 119
/*
 * virsh command line grammar:
 *
 *    command_line    =     <command>\n | <command>; <command>; ...
 *
E
Eric Blake 已提交
120
 *    command         =    <keyword> <option> [--] <data>
K
Karel Zak 已提交
121 122 123 124 125
 *
 *    option          =     <bool_option> | <int_option> | <string_option>
 *    data            =     <string>
 *
 *    bool_option     =     --optionname
E
Eric Blake 已提交
126 127
 *    int_option      =     --optionname <number> | --optionname=<number>
 *    string_option   =     --optionname <string> | --optionname=<string>
128
 *
E
Eric Blake 已提交
129
 *    keyword         =     [a-zA-Z][a-zA-Z-]*
130
 *    number          =     [0-9]+
E
Eric Blake 已提交
131
 *    string          =     ('[^']*'|"([^\\"]|\\.)*"|([^ \t\n\\'"]|\\.))+
K
Karel Zak 已提交
132 133 134 135
 *
 */

/*
136
 * vshCmdOptType - command option type
137
 */
K
Karel Zak 已提交
138
typedef enum {
139 140 141
    VSH_OT_BOOL,     /* optional boolean option */
    VSH_OT_STRING,   /* optional string option */
    VSH_OT_INT,      /* optional or mandatory int option */
142
    VSH_OT_DATA,     /* string data (as non-option) */
E
Eric Blake 已提交
143 144
    VSH_OT_ARGV,     /* remaining arguments */
    VSH_OT_ALIAS,    /* alternate spelling for a later argument */
K
Karel Zak 已提交
145 146
} vshCmdOptType;

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
/*
 * Command group types
 */
#define VSH_CMD_GRP_DOM_MANAGEMENT   "Domain Management"
#define VSH_CMD_GRP_DOM_MONITORING   "Domain Monitoring"
#define VSH_CMD_GRP_STORAGE_POOL     "Storage Pool"
#define VSH_CMD_GRP_STORAGE_VOL      "Storage Volume"
#define VSH_CMD_GRP_NETWORK          "Networking"
#define VSH_CMD_GRP_NODEDEV          "Node Device"
#define VSH_CMD_GRP_IFACE            "Interface"
#define VSH_CMD_GRP_NWFILTER         "Network Filter"
#define VSH_CMD_GRP_SECRET           "Secret"
#define VSH_CMD_GRP_SNAPSHOT         "Snapshot"
#define VSH_CMD_GRP_HOST_AND_HV      "Host and Hypervisor"
#define VSH_CMD_GRP_VIRSH            "Virsh itself"

K
Karel Zak 已提交
163 164 165
/*
 * Command Option Flags
 */
E
Eric Blake 已提交
166 167 168 169
enum {
    VSH_OFLAG_NONE     = 0,        /* without flags */
    VSH_OFLAG_REQ      = (1 << 0), /* option required */
    VSH_OFLAG_EMPTY_OK = (1 << 1), /* empty string option allowed */
L
Lai Jiangshan 已提交
170
    VSH_OFLAG_REQ_OPT  = (1 << 2), /* --optionname required */
E
Eric Blake 已提交
171
};
K
Karel Zak 已提交
172 173 174 175 176 177

/* dummy */
typedef struct __vshControl vshControl;
typedef struct __vshCmd vshCmd;

/*
E
Eric Blake 已提交
178 179 180 181 182
 * vshCmdInfo -- name/value pair for information about command
 *
 * Commands should have at least the following names:
 * "name" - command name
 * "desc" - description of command, or empty string
K
Karel Zak 已提交
183
 */
184
typedef struct {
E
Eric Blake 已提交
185 186
    const char *name;           /* name of information, or NULL for list end */
    const char *data;           /* non-NULL information */
K
Karel Zak 已提交
187 188 189 190 191
} vshCmdInfo;

/*
 * vshCmdOptDef - command option definition
 */
192
typedef struct {
E
Eric Blake 已提交
193
    const char *name;           /* the name of option, or NULL for list end */
194
    vshCmdOptType type;         /* option type */
E
Eric Blake 已提交
195
    unsigned int flags;         /* flags */
E
Eric Blake 已提交
196 197
    const char *help;           /* non-NULL help string; or for VSH_OT_ALIAS
                                 * the name of a later public option */
K
Karel Zak 已提交
198 199 200 201
} vshCmdOptDef;

/*
 * vshCmdOpt - command options
E
Eric Blake 已提交
202 203 204
 *
 * After parsing a command, all arguments to the command have been
 * collected into a list of these objects.
K
Karel Zak 已提交
205 206
 */
typedef struct vshCmdOpt {
E
Eric Blake 已提交
207 208
    const vshCmdOptDef *def;    /* non-NULL pointer to option definition */
    char *data;                 /* allocated data, or NULL for bool option */
209
    struct vshCmdOpt *next;
K
Karel Zak 已提交
210 211
} vshCmdOpt;

212 213 214 215 216
/*
 * Command Usage Flags
 */
enum {
    VSH_CMD_FLAG_NOCONNECT = (1 << 0),  /* no prior connection needed */
217
    VSH_CMD_FLAG_ALIAS     = (1 << 1),  /* command is an alias */
218 219
};

K
Karel Zak 已提交
220 221 222
/*
 * vshCmdDef - command definition
 */
223
typedef struct {
E
Eric Blake 已提交
224
    const char *name;           /* name of command, or NULL for list end */
E
Eric Blake 已提交
225
    bool (*handler) (vshControl *, const vshCmd *);    /* command handler */
226 227
    const vshCmdOptDef *opts;   /* definition of command options */
    const vshCmdInfo *info;     /* details about command */
228
    unsigned int flags;         /* bitwise OR of VSH_CMD_FLAG */
K
Karel Zak 已提交
229 230 231 232 233 234
} vshCmdDef;

/*
 * vshCmd - parsed command
 */
typedef struct __vshCmd {
235
    const vshCmdDef *def;       /* command definition */
236 237
    vshCmdOpt *opts;            /* list of command arguments */
    struct __vshCmd *next;      /* next command */
K
Karel Zak 已提交
238 239 240 241 242 243
} __vshCmd;

/*
 * vshControl
 */
typedef struct __vshControl {
K
Karel Zak 已提交
244
    char *name;                 /* connection name */
245
    virConnectPtr conn;         /* connection to hypervisor (MAY BE NULL) */
246 247
    vshCmd *cmd;                /* the current command */
    char *cmdstr;               /* string with command */
E
Eric Blake 已提交
248 249
    bool imode;                 /* interactive mode? */
    bool quiet;                 /* quiet mode */
250
    int debug;                  /* print debug messages? */
E
Eric Blake 已提交
251 252
    bool timing;                /* print timing info? */
    bool readonly;              /* connect readonly (first time only, not
253 254
                                 * during explicit connect command)
                                 */
255 256
    char *logfile;              /* log file name */
    int log_fd;                 /* log file descriptor */
257 258
    char *historydir;           /* readline history directory name */
    char *historyfile;          /* readline history file name */
259 260
    bool useGetInfo;            /* must use virDomainGetInfo, since
                                   virDomainGetState is not supported */
261 262
    bool useSnapshotOld;        /* cannot use virDomainSnapshotGetParent or
                                   virDomainSnapshotNumChildren */
J
Jiri Denemark 已提交
263
    virThread eventLoop;
264
    virMutex lock;
J
Jiri Denemark 已提交
265 266
    bool eventLoopStarted;
    bool quit;
267 268 269

    const char *escapeChar;     /* String representation of
                                   console escape character */
K
Karel Zak 已提交
270
} __vshControl;
271

272
typedef struct vshCmdGrp {
E
Eric Blake 已提交
273
    const char *name;    /* name of group, or NULL for list end */
274 275 276
    const char *keyword; /* help keyword */
    const vshCmdDef *commands;
} vshCmdGrp;
277

278
static const vshCmdGrp cmdGroups[];
K
Karel Zak 已提交
279

280 281
static void vshError(vshControl *ctl, const char *format, ...)
    ATTRIBUTE_FMT_PRINTF(2, 3);
E
Eric Blake 已提交
282 283
static bool vshInit(vshControl *ctl);
static bool vshDeinit(vshControl *ctl);
284
static void vshUsage(void);
285
static void vshOpenLogFile(vshControl *ctl);
286 287
static void vshOutputLogFile(vshControl *ctl, int log_level, const char *format, va_list ap)
    ATTRIBUTE_FMT_PRINTF(3, 0);
288
static void vshCloseLogFile(vshControl *ctl);
K
Karel Zak 已提交
289

E
Eric Blake 已提交
290
static bool vshParseArgv(vshControl *ctl, int argc, char **argv);
K
Karel Zak 已提交
291

292
static const char *vshCmddefGetInfo(const vshCmdDef *cmd, const char *info);
293
static const vshCmdDef *vshCmddefSearch(const char *cmdname);
E
Eric Blake 已提交
294
static bool vshCmddefHelp(vshControl *ctl, const char *name);
295
static const vshCmdGrp *vshCmdGrpSearch(const char *grpname);
E
Eric Blake 已提交
296
static bool vshCmdGrpHelp(vshControl *ctl, const char *name);
K
Karel Zak 已提交
297

E
Eric Blake 已提交
298 299 300
static int vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
    ATTRIBUTE_RETURN_CHECK;
301 302
static int vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
303 304 305
static int vshCommandOptUInt(const vshCmd *cmd, const char *name,
                             unsigned int *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
306 307 308 309 310 311 312 313 314
static int vshCommandOptUL(const vshCmd *cmd, const char *name,
                           unsigned long *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
static int vshCommandOptString(const vshCmd *cmd, const char *name,
                               const char **value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
static int vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                                 long long *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
315 316 317
static int vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                                  unsigned long long *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
E
Eric Blake 已提交
318 319 320 321
static int vshCommandOptScaledInt(const vshCmd *cmd, const char *name,
                                  unsigned long long *value, int scale,
                                  unsigned long long max)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
E
Eric Blake 已提交
322
static bool vshCommandOptBool(const vshCmd *cmd, const char *name);
323 324
static const vshCmdOpt *vshCommandOptArgv(const vshCmd *cmd,
                                          const vshCmdOpt *opt);
325 326 327
static char *vshGetDomainDescription(vshControl *ctl, virDomainPtr dom,
                                     bool title, unsigned int flags)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_RETURN_CHECK;
K
Karel Zak 已提交
328

329 330 331
#define VSH_BYID     (1 << 1)
#define VSH_BYUUID   (1 << 2)
#define VSH_BYNAME   (1 << 3)
332
#define VSH_BYMAC    (1 << 4)
K
Karel Zak 已提交
333

334
static virDomainPtr vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
335
                                          const char **name, int flag);
K
Karel Zak 已提交
336 337

/* default is lookup by Id, Name and UUID */
J
Jim Meyering 已提交
338 339
#define vshCommandOptDomain(_ctl, _cmd, _name)                      \
    vshCommandOptDomainBy(_ctl, _cmd, _name, VSH_BYID|VSH_BYUUID|VSH_BYNAME)
340

341
static void vshPrintExtra(vshControl *ctl, const char *format, ...)
342
    ATTRIBUTE_FMT_PRINTF(2, 3);
343
static void vshDebug(vshControl *ctl, int level, const char *format, ...)
344
    ATTRIBUTE_FMT_PRINTF(3, 4);
K
Karel Zak 已提交
345 346

/* XXX: add batch support */
347
#define vshPrint(_ctl, ...)   vshPrintExtra(NULL, __VA_ARGS__)
K
Karel Zak 已提交
348

349
static int vshDomainState(vshControl *ctl, virDomainPtr dom, int *reason);
K
Karel Zak 已提交
350
static const char *vshDomainStateToString(int state);
351
static const char *vshDomainStateReasonToString(int state, int reason);
352
static const char *vshDomainControlStateToString(int state);
353
static const char *vshDomainVcpuStateToString(int state);
E
Eric Blake 已提交
354
static bool vshConnectionUsability(vshControl *ctl, virConnectPtr conn);
355 356 357
static virTypedParameterPtr vshFindTypedParamByName(const char *name,
                                                    virTypedParameterPtr list,
                                                    int count);
358 359
static char *vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2);
K
Karel Zak 已提交
360

E
Eric Blake 已提交
361 362 363
static char *editWriteToTempFile(vshControl *ctl, const char *doc);
static int   editFile(vshControl *ctl, const char *filename);
static char *editReadBackFile(vshControl *ctl, const char *filename);
364

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
/* Typedefs, function prototypes for job progress reporting.
 * There are used by some long lingering commands like
 * migrate, dump, save, managedsave.
 */
typedef struct __vshCtrlData {
    vshControl *ctl;
    const vshCmd *cmd;
    int writefd;
} vshCtrlData;

typedef void (*jobWatchTimeoutFunc) (vshControl *ctl, virDomainPtr dom,
                                     void *opaque);

static bool
vshWatchJob(vshControl *ctl,
            virDomainPtr dom,
            bool verbose,
            int pipe_fd,
            int timeout,
            jobWatchTimeoutFunc timeout_func,
            void *opaque,
            const char *label);

388
static void *_vshMalloc(vshControl *ctl, size_t sz, const char *filename, int line);
389 390
#define vshMalloc(_ctl, _sz)    _vshMalloc(_ctl, _sz, __FILE__, __LINE__)

391
static void *_vshCalloc(vshControl *ctl, size_t nmemb, size_t sz, const char *filename, int line);
392 393
#define vshCalloc(_ctl, _nmemb, _sz)    _vshCalloc(_ctl, _nmemb, _sz, __FILE__, __LINE__)

394
static char *_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line);
395 396
#define vshStrdup(_ctl, _s)    _vshStrdup(_ctl, _s, __FILE__, __LINE__)

397 398
static int parseRateStr(const char *rateStr, virNetDevBandwidthRatePtr rate);

E
Eric Blake 已提交
399 400 401
static void *
_vshMalloc(vshControl *ctl, size_t size, const char *filename, int line)
{
E
Eric Blake 已提交
402
    char *x;
E
Eric Blake 已提交
403

E
Eric Blake 已提交
404
    if (VIR_ALLOC_N(x, size) == 0)
E
Eric Blake 已提交
405 406 407 408 409 410 411 412 413
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %d bytes"),
             filename, line, (int) size);
    exit(EXIT_FAILURE);
}

static void *
_vshCalloc(vshControl *ctl, size_t nmemb, size_t size, const char *filename, int line)
{
E
Eric Blake 已提交
414
    char *x;
E
Eric Blake 已提交
415

E
Eric Blake 已提交
416 417
    if (!xalloc_oversized(nmemb, size) &&
        VIR_ALLOC_N(x, nmemb * size) == 0)
E
Eric Blake 已提交
418 419 420 421 422 423 424 425 426 427 428 429
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %d bytes"),
             filename, line, (int) (size*nmemb));
    exit(EXIT_FAILURE);
}

static char *
_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line)
{
    char *x;

    if (s == NULL)
430
        return NULL;
E
Eric Blake 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
    if ((x = strdup(s)))
        return x;
    vshError(ctl, _("%s: %d: failed to allocate %lu bytes"),
             filename, line, (unsigned long)strlen(s));
    exit(EXIT_FAILURE);
}

/* Poison the raw allocating identifiers in favor of our vsh variants.  */
#undef malloc
#undef calloc
#undef realloc
#undef strdup
#define malloc use_vshMalloc_instead_of_malloc
#define calloc use_vshCalloc_instead_of_calloc
#define realloc use_vshRealloc_instead_of_realloc
#define strdup use_vshStrdup_instead_of_strdup
447

448 449 450 451 452
static int
vshNameSorter(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;
453

454 455
    /* User visible sort, so we want locale-specific case comparison. */
    return strcasecmp(*sa, *sb);
456 457
}

458 459 460 461 462 463 464
static double
prettyCapacity(unsigned long long val,
               const char **unit) {
    if (val < 1024) {
        *unit = "";
        return (double)val;
    } else if (val < (1024.0l * 1024.0l)) {
465
        *unit = "KiB";
466 467
        return (((double)val / 1024.0l));
    } else if (val < (1024.0l * 1024.0l * 1024.0l)) {
468
        *unit = "MiB";
469
        return (double)val / (1024.0l * 1024.0l);
470
    } else if (val < (1024.0l * 1024.0l * 1024.0l * 1024.0l)) {
471
        *unit = "GiB";
472
        return (double)val / (1024.0l * 1024.0l * 1024.0l);
473
    } else {
474
        *unit = "TiB";
475
        return (double)val / (1024.0l * 1024.0l * 1024.0l * 1024.0l);
476 477 478 479
    }
}


J
John Levon 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
static virErrorPtr last_error;

/*
 * Quieten libvirt until we're done with the command.
 */
static void
virshErrorHandler(void *unused ATTRIBUTE_UNUSED, virErrorPtr error)
{
    virFreeError(last_error);
    last_error = virSaveLastError();
    if (getenv("VIRSH_DEBUG") != NULL)
        virDefaultErrorFunc(error);
}

/*
 * 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.
 */
static void
virshReportError(vshControl *ctl)
{
505 506 507 508 509 510 511 512
    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)
513
            goto out;
514
    }
J
John Levon 已提交
515 516

    if (last_error->code == VIR_ERR_OK) {
517
        vshError(ctl, "%s", _("unknown error"));
J
John Levon 已提交
518 519 520
        goto out;
    }

521
    vshError(ctl, "%s", last_error->message);
J
John Levon 已提交
522 523 524 525 526 527

out:
    virFreeError(last_error);
    last_error = NULL;
}

528 529 530 531 532 533 534 535 536
static volatile sig_atomic_t intCaught = 0;

static void vshCatchInt(int sig ATTRIBUTE_UNUSED,
                        siginfo_t *siginfo ATTRIBUTE_UNUSED,
                        void *context ATTRIBUTE_UNUSED)
{
    intCaught = 1;
}

537 538 539 540 541
/*
 * Detection of disconnections and automatic reconnection support
 */
static int disconnected = 0; /* we may have been disconnected */

542 543 544 545 546
/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

547 548 549 550 551 552
/*
 * vshCatchDisconnect:
 *
 * We get here when a SIGPIPE is being raised, we can't do much in the
 * handler, just save the fact it was raised
 */
553 554
static void vshCatchDisconnect(int sig, siginfo_t *siginfo,
                               void *context ATTRIBUTE_UNUSED) {
E
Eric Blake 已提交
555
    if (sig == SIGPIPE ||
556
        (SA_SIGINFO && siginfo->si_signo == SIGPIPE))
557 558 559 560 561 562 563 564 565
        disconnected++;
}

/*
 * vshSetupSignals:
 *
 * Catch SIGPIPE signals which may arise when disconnection
 * from libvirtd occurs
 */
L
Laine Stump 已提交
566
static void
567 568 569 570 571 572 573 574 575 576 577 578 579
vshSetupSignals(void) {
    struct sigaction sig_action;

    sig_action.sa_sigaction = vshCatchDisconnect;
    sig_action.sa_flags = SA_SIGINFO;
    sigemptyset(&sig_action.sa_mask);

    sigaction(SIGPIPE, &sig_action, NULL);
}

/*
 * vshReconnect:
 *
L
Laine Stump 已提交
580
 * Reconnect after a disconnect from libvirtd
581 582
 *
 */
L
Laine Stump 已提交
583
static void
584 585 586 587 588 589
vshReconnect(vshControl *ctl)
{
    bool connected = false;

    if (ctl->conn != NULL) {
        connected = true;
590
        virConnectClose(ctl->conn);
591
    }
592 593 594 595 596 597

    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);
    if (!ctl->conn)
        vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
598
    else if (connected)
599 600
        vshError(ctl, "%s", _("Reconnected to the hypervisor"));
    disconnected = 0;
601
    ctl->useGetInfo = false;
602
    ctl->useSnapshotOld = false;
603
}
604

605
#ifndef WIN32
606 607 608 609 610 611 612 613 614 615 616 617 618
static void
vshPrintRaw(vshControl *ctl, ...)
{
    va_list ap;
    char *key;

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

619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
/**
 * vshAskReedit:
 * @msg: Question to ask user
 *
 * Ask user if he wants to return to previously
 * edited file.
 *
 * Returns 'y' if he wants to
 *         'f' if he forcibly wants to
 *         'n' if he doesn't want to
 *         -1  on error
 *          0  otherwise
 */
static int
vshAskReedit(vshControl *ctl, const char *msg)
{
    int c = -1;
    struct termios ttyattr;

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

    virshReportError(ctl);

    if (vshMakeStdinRaw(&ttyattr, false) < 0)
        return -1;

    while (true) {
        /* TRANSLATORS: For now, we aren't using LC_MESSAGES, and the user
         * choices really are limited to just 'y', 'n', 'f' and '?'  */
        vshPrint(ctl, "\r%s %s", msg, _("Try again? [y,n,f,?]:"));
        c = c_tolower(getchar());

        if (c == '?') {
653 654 655 656 657 658 659
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
660 661 662 663 664 665 666 667 668 669
            continue;
        } else if (c == 'y' || c == 'n' || c == 'f') {
            break;
        }
    }

    tcsetattr(STDIN_FILENO, TCSAFLUSH, &ttyattr);

    vshPrint(ctl, "\r\n");
    return c;
670 671 672 673 674
}
#else /* WIN32 */
static int
vshAskReedit(vshControl *ctl, const char *msg ATTRIBUTE_UNUSED)
{
675 676 677 678
    vshDebug(ctl, VSH_ERR_WARNING, "%s", _("This function is not "
                                           "supported on WIN32 platform"));
    return 0;
}
679
#endif /* WIN32 */
680

681 682 683 684 685 686 687 688
static int vshStreamSink(virStreamPtr st ATTRIBUTE_UNUSED,
                         const char *bytes, size_t nbytes, void *opaque)
{
    int *fd = opaque;

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

K
Karel Zak 已提交
689 690 691 692 693 694
/* ---------------
 * Commands
 * ---------------
 */

/*
695
 * "help" command
K
Karel Zak 已提交
696
 */
697
static const vshCmdInfo info_help[] = {
698
    {"help", N_("print help")},
699 700
    {"desc", N_("Prints global help, command specific help, or help for a\n"
                "    group of related commands")},
701

702
    {NULL, NULL}
K
Karel Zak 已提交
703 704
};

705
static const vshCmdOptDef opts_help[] = {
706
    {"command", VSH_OT_DATA, 0, N_("Prints global help, command specific help, or help for a group of related commands")},
707
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
708 709
};

E
Eric Blake 已提交
710
static bool
711
cmdHelp(vshControl *ctl, const vshCmd *cmd)
712
 {
713
    const char *name = NULL;
714

715
    if (vshCommandOptString(cmd, "command", &name) <= 0) {
716
        const vshCmdGrp *grp;
717
        const vshCmdDef *def;
718

719 720 721 722 723 724
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

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

725 726 727
            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
728 729
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
730
            }
731 732 733 734

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
735
        return true;
736
    }
737

E
Eric Blake 已提交
738
    if (vshCmddefSearch(name)) {
739
        return vshCmddefHelp(ctl, name);
E
Eric Blake 已提交
740
    } else if (vshCmdGrpSearch(name)) {
741 742 743
        return vshCmdGrpHelp(ctl, name);
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
E
Eric Blake 已提交
744
        return false;
K
Karel Zak 已提交
745 746 747
    }
}

748
/*
749
 * "nodedev-create" command
750
 */
751 752 753 754 755 756
static const vshCmdInfo info_node_device_create[] = {
    {"help", N_("create a device defined "
                          "by an XML file on the node")},
    {"desc", N_("Create a device on the node.  Note that this "
                          "command creates devices on the physical host "
                          "that can then be assigned to a virtual machine.")},
757 758
    {NULL, NULL}
};
759

760 761 762
static const vshCmdOptDef opts_node_device_create[] = {
    {"file", VSH_OT_DATA, VSH_OFLAG_REQ,
     N_("file containing an XML description of the device")},
763 764
    {NULL, 0, 0, NULL}
};
765

766
static bool
767
cmdNodeDeviceCreate(vshControl *ctl, const vshCmd *cmd)
768
{
769 770
    virNodeDevicePtr dev = NULL;
    const char *from = NULL;
771
    bool ret = true;
772
    char *buffer;
773

774
    if (!vshConnectionUsability(ctl, ctl->conn))
775 776
        return false;

777 778 779 780
    if (vshCommandOptString(cmd, "file", &from) <= 0)
        return false;

    if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0)
781 782
        return false;

783 784 785 786 787 788 789
    dev = virNodeDeviceCreateXML(ctl->conn, buffer, 0);
    VIR_FREE(buffer);

    if (dev != NULL) {
        vshPrint(ctl, _("Node device %s created from %s\n"),
                 virNodeDeviceGetName(dev), from);
        virNodeDeviceFree(dev);
790
    } else {
791
        vshError(ctl, _("Failed to create node device from %s"), from);
792 793
        ret = false;
    }
794

795 796
    return ret;
}
797

798 799

/*
800
 * "nodedev-destroy" command
801
 */
802 803 804 805
static const vshCmdInfo info_node_device_destroy[] = {
    {"help", N_("destroy (stop) a device on the node")},
    {"desc", N_("Destroy a device on the node.  Note that this "
                "command destroys devices on the physical host")},
806 807 808
    {NULL, NULL}
};

809 810 811
static const vshCmdOptDef opts_node_device_destroy[] = {
    {"name", VSH_OT_DATA, VSH_OFLAG_REQ,
     N_("name of the device to be destroyed")},
812 813 814
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
815
static bool
816
cmdNodeDeviceDestroy(vshControl *ctl, const vshCmd *cmd)
817
{
818 819 820
    virNodeDevicePtr dev = NULL;
    bool ret = true;
    const char *name = NULL;
821

822
    if (!vshConnectionUsability(ctl, ctl->conn)) {
E
Eric Blake 已提交
823
        return false;
824
    }
825

826
    if (vshCommandOptString(cmd, "name", &name) <= 0)
E
Eric Blake 已提交
827
        return false;
828

829
    dev = virNodeDeviceLookupByName(ctl->conn, name);
830

831 832 833 834 835 836 837 838 839
    if (virNodeDeviceDestroy(dev) == 0) {
        vshPrint(ctl, _("Destroyed node device '%s'\n"), name);
    } else {
        vshError(ctl, _("Failed to destroy node device '%s'"), name);
        ret = false;
    }

    virNodeDeviceFree(dev);
    return ret;
840 841
}

842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
/* Tree listing helpers.  */

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

static int
vshTreePrintInternal(vshControl *ctl,
                     vshTreeLookup lookup,
                     void *opaque,
                     int num_devices,
                     int devid,
                     int lastdev,
                     bool root,
                     virBufferPtr indent)
857
{
858 859 860 861
    int i;
    int nextlastdev = -1;
    int ret = -1;
    const char *dev = (lookup)(devid, false, opaque);
862

863
    if (virBufferError(indent))
864 865
        goto cleanup;

866 867 868 869 870 871 872 873 874 875
    /* 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;
876 877
    }

878 879 880
    /* Determine the index of the last child device */
    for (i = 0 ; i < num_devices ; i++) {
        const char *parent = (lookup)(i, true, opaque);
881

882 883 884
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
885

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

890 891 892 893
    /* Finally print all children */
    virBufferAddLit(indent, "  ");
    for (i = 0 ; i < num_devices ; i++) {
        const char *parent = (lookup)(i, true, opaque);
894

895 896 897 898 899
        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
900
    }
901
    virBufferTrim(indent, "  ", -1);
902

903 904 905 906
    /* 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));
907

908 909 910
    if (!root)
        virBufferTrim(indent, NULL, 2);
    ret = 0;
911 912 913 914
cleanup:
    return ret;
}

915 916 917
static int
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
918
{
919 920
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;
921

922 923 924 925 926
    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
927
    return ret;
928
}
929

930 931 932 933 934 935 936 937 938 939 940 941
struct vshNodeList {
    char **names;
    char **parents;
};

static const char *
vshNodeListLookup(int devid, bool parent, void *opaque)
{
    struct vshNodeList *arrays = opaque;
    if (parent)
        return arrays->parents[devid];
    return arrays->names[devid];
942 943
}

944
/*
945
 * "nodedev-list" command
946
 */
947 948 949
static const vshCmdInfo info_node_list_devices[] = {
    {"help", N_("enumerate devices on this host")},
    {"desc", ""},
950 951 952
    {NULL, NULL}
};

953 954 955
static const vshCmdOptDef opts_node_list_devices[] = {
    {"tree", VSH_OT_BOOL, 0, N_("list devices in a tree")},
    {"cap", VSH_OT_STRING, VSH_OFLAG_NONE, N_("capability name")},
956 957 958
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
959
static bool
960
cmdNodeListDevices(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
961
{
962 963 964 965 966
    const char *cap = NULL;
    char **devices;
    int num_devices, i;
    bool tree = vshCommandOptBool(cmd, "tree");
    bool ret = true;
967

968
    if (!vshConnectionUsability(ctl, ctl->conn))
969
        return false;
970

971 972
    if (vshCommandOptString(cmd, "cap", &cap) <= 0)
        cap = NULL;
973

974 975 976 977 978 979 980
    num_devices = virNodeNumOfDevices(ctl->conn, cap, 0);
    if (num_devices < 0) {
        vshError(ctl, "%s", _("Failed to count node devices"));
        return false;
    } else if (num_devices == 0) {
        return true;
    }
981

982 983 984 985 986 987 988
    devices = vshMalloc(ctl, sizeof(char *) * num_devices);
    num_devices =
        virNodeListDevices(ctl->conn, cap, devices, num_devices, 0);
    if (num_devices < 0) {
        vshError(ctl, "%s", _("Failed to list node devices"));
        VIR_FREE(devices);
        return false;
J
Jim Fehlig 已提交
989
    }
990 991 992 993
    qsort(&devices[0], num_devices, sizeof(char*), vshNameSorter);
    if (tree) {
        char **parents = vshMalloc(ctl, sizeof(char *) * num_devices);
        struct vshNodeList arrays = { devices, parents };
J
Jim Fehlig 已提交
994

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        for (i = 0; i < num_devices; i++) {
            virNodeDevicePtr dev = virNodeDeviceLookupByName(ctl->conn, devices[i]);
            if (dev && STRNEQ(devices[i], "computer")) {
                const char *parent = virNodeDeviceGetParent(dev);
                parents[i] = parent ? vshStrdup(ctl, parent) : NULL;
            } else {
                parents[i] = NULL;
            }
            virNodeDeviceFree(dev);
        }
        for (i = 0 ; i < num_devices ; i++) {
            if (parents[i] == NULL &&
                vshTreePrint(ctl, vshNodeListLookup, &arrays, num_devices,
                             i) < 0)
                ret = false;
        }
        for (i = 0 ; i < num_devices ; i++) {
            VIR_FREE(devices[i]);
            VIR_FREE(parents[i]);
        }
        VIR_FREE(parents);
J
Jim Fehlig 已提交
1016
    } else {
1017 1018 1019 1020
        for (i = 0; i < num_devices; i++) {
            vshPrint(ctl, "%s\n", devices[i]);
            VIR_FREE(devices[i]);
        }
1021
    }
1022 1023
    VIR_FREE(devices);
    return ret;
1024 1025
}

O
Osier Yang 已提交
1026
/*
1027
 * "nodedev-dumpxml" command
O
Osier Yang 已提交
1028
 */
1029 1030 1031
static const vshCmdInfo info_node_device_dumpxml[] = {
    {"help", N_("node device details in XML")},
    {"desc", N_("Output the node device details as an XML dump to stdout.")},
O
Osier Yang 已提交
1032 1033 1034
    {NULL, NULL}
};

1035 1036 1037

static const vshCmdOptDef opts_node_device_dumpxml[] = {
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
O
Osier Yang 已提交
1038 1039 1040 1041
    {NULL, 0, 0, NULL}
};

static bool
1042
cmdNodeDeviceDumpXML(vshControl *ctl, const vshCmd *cmd)
O
Osier Yang 已提交
1043
{
1044 1045 1046
    const char *name = NULL;
    virNodeDevicePtr device;
    char *xml;
O
Osier Yang 已提交
1047

1048 1049 1050 1051 1052 1053 1054
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;
    if (vshCommandOptString(cmd, "device", &name) <= 0)
        return false;
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
        return false;
O
Osier Yang 已提交
1055 1056
    }

1057 1058 1059 1060
    xml = virNodeDeviceGetXMLDesc(device, 0);
    if (!xml) {
        virNodeDeviceFree(device);
        return false;
O
Osier Yang 已提交
1061 1062
    }

1063 1064 1065 1066 1067
    vshPrint(ctl, "%s\n", xml);
    VIR_FREE(xml);
    virNodeDeviceFree(device);
    return true;
}
O
Osier Yang 已提交
1068

1069 1070 1071 1072 1073 1074 1075 1076
/*
 * "nodedev-detach" command
 */
static const vshCmdInfo info_node_device_detach[] = {
    {"help", N_("detach node device from its device driver")},
    {"desc", N_("Detach node device from its device driver before assigning to a domain.")},
    {NULL, NULL}
};
O
Osier Yang 已提交
1077 1078


1079 1080 1081 1082
static const vshCmdOptDef opts_node_device_detach[] = {
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
    {NULL, 0, 0, NULL}
};
O
Osier Yang 已提交
1083

1084 1085 1086 1087 1088 1089
static bool
cmdNodeDeviceDetach(vshControl *ctl, const vshCmd *cmd)
{
    const char *name = NULL;
    virNodeDevicePtr device;
    bool ret = true;
O
Osier Yang 已提交
1090

1091 1092 1093 1094 1095 1096 1097
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;
    if (vshCommandOptString(cmd, "device", &name) <= 0)
        return false;
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
        return false;
O
Osier Yang 已提交
1098 1099
    }

1100 1101 1102 1103 1104 1105 1106 1107 1108
    /* Yes, our public API is misspelled.  At least virsh can accept
     * either spelling.  */
    if (virNodeDeviceDettach(device) == 0) {
        vshPrint(ctl, _("Device %s detached\n"), name);
    } else {
        vshError(ctl, _("Failed to detach device %s"), name);
        ret = false;
    }
    virNodeDeviceFree(device);
O
Osier Yang 已提交
1109 1110 1111
    return ret;
}

1112
/*
1113
 * "nodedev-reattach" command
1114
 */
1115 1116 1117
static const vshCmdInfo info_node_device_reattach[] = {
    {"help", N_("reattach node device to its device driver")},
    {"desc", N_("Reattach node device to its device driver once released by the domain.")},
1118 1119 1120
    {NULL, NULL}
};

1121 1122 1123

static const vshCmdOptDef opts_node_device_reattach[] = {
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
1124 1125 1126
    {NULL, 0, 0, NULL}
};

E
Eric Blake 已提交
1127
static bool
1128
cmdNodeDeviceReAttach(vshControl *ctl, const vshCmd *cmd)
1129
{
1130 1131 1132
    const char *name = NULL;
    virNodeDevicePtr device;
    bool ret = true;
1133

1134
    if (!vshConnectionUsability(ctl, ctl->conn))
E
Eric Blake 已提交
1135
        return false;
1136
    if (vshCommandOptString(cmd, "device", &name) <= 0)
E
Eric Blake 已提交
1137
        return false;
1138 1139
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
E
Eric Blake 已提交
1140
        return false;
1141
    }
1142

1143 1144
    if (virNodeDeviceReAttach(device) == 0) {
        vshPrint(ctl, _("Device %s re-attached\n"), name);
1145
    } else {
1146 1147
        vshError(ctl, _("Failed to re-attach device %s"), name);
        ret = false;
1148
    }
1149 1150 1151
    virNodeDeviceFree(device);
    return ret;
}
1152

1153 1154 1155 1156 1157 1158 1159 1160
/*
 * "nodedev-reset" command
 */
static const vshCmdInfo info_node_device_reset[] = {
    {"help", N_("reset node device")},
    {"desc", N_("Reset node device before or after assigning to a domain.")},
    {NULL, NULL}
};
1161 1162


1163 1164 1165 1166
static const vshCmdOptDef opts_node_device_reset[] = {
    {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")},
    {NULL, 0, 0, NULL}
};
1167

1168 1169 1170 1171 1172 1173
static bool
cmdNodeDeviceReset(vshControl *ctl, const vshCmd *cmd)
{
    const char *name = NULL;
    virNodeDevicePtr device;
    bool ret = true;
1174

1175 1176 1177 1178 1179 1180 1181
    if (!vshConnectionUsability(ctl, ctl->conn))
        return false;
    if (vshCommandOptString(cmd, "device", &name) <= 0)
        return false;
    if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) {
        vshError(ctl, "%s '%s'", _("Could not find matching device"), name);
        return false;
1182 1183
    }

1184 1185 1186 1187 1188 1189 1190
    if (virNodeDeviceReset(device) == 0) {
        vshPrint(ctl, _("Device %s reset\n"), name);
    } else {
        vshError(ctl, _("Failed to reset device %s"), name);
        ret = false;
    }
    virNodeDeviceFree(device);
1191 1192 1193
    return ret;
}

1194 1195
/* Common code for the edit / net-edit / pool-edit functions which follow. */
static char *
1196
editWriteToTempFile(vshControl *ctl, const char *doc)
1197 1198 1199 1200 1201 1202 1203
{
    char *ret;
    const char *tmpdir;
    int fd;

    tmpdir = getenv ("TMPDIR");
    if (!tmpdir) tmpdir = "/tmp";
1204 1205 1206 1207
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
1208
    fd = mkstemps(ret, 4);
1209
    if (fd == -1) {
1210
        vshError(ctl, _("mkstemps: failed to create temporary file: %s"),
1211
                 strerror(errno));
1212
        VIR_FREE(ret);
1213 1214 1215
        return NULL;
    }

1216
    if (safewrite(fd, doc, strlen(doc)) == -1) {
1217 1218
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
                 ret, strerror(errno));
S
Stefan Berger 已提交
1219
        VIR_FORCE_CLOSE(fd);
1220
        unlink(ret);
1221
        VIR_FREE(ret);
1222 1223
        return NULL;
    }
S
Stefan Berger 已提交
1224
    if (VIR_CLOSE(fd) < 0) {
1225 1226
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
                 ret, strerror(errno));
1227
        unlink(ret);
1228
        VIR_FREE(ret);
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        return NULL;
    }

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

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

static int
1241
editFile(vshControl *ctl, const char *filename)
1242 1243
{
    const char *editor;
E
Eric Blake 已提交
1244 1245 1246 1247
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;
1248

1249
    editor = getenv("VISUAL");
E
Eric Blake 已提交
1250
    if (!editor)
1251
        editor = getenv("EDITOR");
E
Eric Blake 已提交
1252 1253
    if (!editor)
        editor = "vi"; /* could be cruel & default to ed(1) here */
1254

1255 1256 1257 1258 1259
    /* 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 已提交
1260 1261
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
1262
     */
1263 1264
    if (strspn(editor, ACCEPTED_CHARS) != strlen(editor)) {
        if (strspn(filename, ACCEPTED_CHARS) != strlen(filename)) {
E
Eric Blake 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
            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);
1275 1276
    }

E
Eric Blake 已提交
1277 1278 1279 1280 1281 1282 1283
    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
        virshReportError(ctl);
        goto cleanup;
1284
    }
E
Eric Blake 已提交
1285
    ret = 0;
1286

E
Eric Blake 已提交
1287 1288 1289
cleanup:
    virCommandFree(cmd);
    return ret;
1290 1291 1292
}

static char *
1293
editReadBackFile(vshControl *ctl, const char *filename)
1294 1295 1296
{
    char *ret;

E
Eric Blake 已提交
1297
    if (virFileReadAll(filename, VIRSH_MAX_XML_FILE, &ret) == -1) {
1298
        vshError(ctl,
1299
                 _("%s: failed to read temporary file: %s"),
1300
                 filename, strerror(errno));
1301 1302 1303 1304 1305
        return NULL;
    }
    return ret;
}

1306

P
Paolo Bonzini 已提交
1307 1308 1309 1310
/*
 * "cd" command
 */
static const vshCmdInfo info_cd[] = {
1311 1312
    {"help", N_("change the current directory")},
    {"desc", N_("Change the current directory.")},
P
Paolo Bonzini 已提交
1313 1314 1315 1316
    {NULL, NULL}
};

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

E
Eric Blake 已提交
1321
static bool
1322
cmdCd(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
1323
{
1324
    const char *dir = NULL;
1325
    char *dir_malloced = NULL;
E
Eric Blake 已提交
1326
    bool ret = true;
P
Paolo Bonzini 已提交
1327 1328

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

1333
    if (vshCommandOptString(cmd, "dir", &dir) <= 0) {
1334
        dir = dir_malloced = virGetUserDirectory();
P
Paolo Bonzini 已提交
1335 1336 1337 1338
    }
    if (!dir)
        dir = "/";

P
Phil Petty 已提交
1339
    if (chdir(dir) == -1) {
1340
        vshError(ctl, _("cd: %s: %s"), strerror(errno), dir);
E
Eric Blake 已提交
1341
        ret = false;
P
Paolo Bonzini 已提交
1342 1343
    }

1344
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
1345
    return ret;
P
Paolo Bonzini 已提交
1346 1347 1348 1349 1350 1351
}

/*
 * "pwd" command
 */
static const vshCmdInfo info_pwd[] = {
1352 1353
    {"help", N_("print the current directory")},
    {"desc", N_("Print the current directory.")},
P
Paolo Bonzini 已提交
1354 1355 1356
    {NULL, NULL}
};

E
Eric Blake 已提交
1357
static bool
P
Paolo Bonzini 已提交
1358 1359 1360
cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cwd;
1361
    bool ret = true;
P
Paolo Bonzini 已提交
1362

1363 1364
    cwd = getcwd(NULL, 0);
    if (!cwd) {
1365 1366
        vshError(ctl, _("pwd: cannot get current directory: %s"),
                 strerror(errno));
1367 1368
        ret = false;
    } else {
1369
        vshPrint(ctl, _("%s\n"), cwd);
1370 1371
        VIR_FREE(cwd);
    }
P
Paolo Bonzini 已提交
1372

1373
    return ret;
P
Paolo Bonzini 已提交
1374 1375
}

E
Eric Blake 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
/*
 * "echo" command
 */
static const vshCmdInfo info_echo[] = {
    {"help", N_("echo arguments")},
    {"desc", N_("Echo back arguments, possibly with quoting.")},
    {NULL, NULL}
};

static const vshCmdOptDef opts_echo[] = {
    {"shell", VSH_OT_BOOL, 0, N_("escape for shell use")},
    {"xml", VSH_OT_BOOL, 0, N_("escape for XML use")},
E
Eric Blake 已提交
1388
    {"str", VSH_OT_ALIAS, 0, "string"},
1389
    {"string", VSH_OT_ARGV, 0, N_("arguments to echo")},
E
Eric Blake 已提交
1390 1391 1392 1393 1394 1395
    {NULL, 0, 0, NULL}
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
E
Eric Blake 已提交
1396
static bool
1397
cmdEcho(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
1398 1399 1400 1401
{
    bool shell = false;
    bool xml = false;
    int count = 0;
1402
    const vshCmdOpt *opt = NULL;
E
Eric Blake 已提交
1403 1404 1405 1406 1407 1408 1409 1410
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

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

1411
    while ((opt = vshCommandOptArgv(cmd, opt))) {
1412 1413
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
1414

1415
        arg = opt->data;
1416

E
Eric Blake 已提交
1417 1418
        if (count)
            virBufferAddChar(&buf, ' ');
1419

E
Eric Blake 已提交
1420
        if (xml) {
1421 1422 1423 1424
            virBufferEscapeString(&xmlbuf, "%s", arg);
            if (virBufferError(&buf)) {
                vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
                return false;
E
Eric Blake 已提交
1425
            }
1426 1427 1428
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
E
Eric Blake 已提交
1429
        }
1430 1431 1432 1433 1434

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
E
Eric Blake 已提交
1435
        count++;
1436
        VIR_FREE(str);
E
Eric Blake 已提交
1437 1438 1439 1440
    }

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
1441
        return false;
E
Eric Blake 已提交
1442 1443 1444 1445 1446
    }
    arg = virBufferContentAndReset(&buf);
    if (arg)
        vshPrint(ctl, "%s", arg);
    VIR_FREE(arg);
E
Eric Blake 已提交
1447
    return true;
E
Eric Blake 已提交
1448 1449
}

K
Karel Zak 已提交
1450 1451 1452
/*
 * "quit" command
 */
1453
static const vshCmdInfo info_quit[] = {
1454
    {"help", N_("quit this interactive terminal")},
1455
    {"desc", ""},
1456
    {NULL, NULL}
K
Karel Zak 已提交
1457 1458
};

E
Eric Blake 已提交
1459
static bool
1460
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
1461
{
E
Eric Blake 已提交
1462 1463
    ctl->imode = false;
    return true;
K
Karel Zak 已提交
1464 1465
}

1466 1467 1468 1469 1470 1471 1472 1473
/* ---------------
 * Utils for work with command definition
 * ---------------
 */
static const char *
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
{
    const vshCmdInfo *info;
1474

1475 1476 1477 1478 1479 1480
    for (info = cmd->info; info && info->name; info++) {
        if (STREQ(info->name, name))
            return info->data;
    }
    return NULL;
}
1481

1482 1483 1484 1485 1486 1487 1488
/* Validate that the options associated with cmd can be parsed.  */
static int
vshCmddefOptParse(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                  uint32_t *opts_required)
{
    int i;
    bool optional = false;
1489

1490 1491
    *opts_need_arg = 0;
    *opts_required = 0;
1492

1493 1494
    if (!cmd->opts)
        return 0;
1495

1496 1497
    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
1498 1499 1500 1501

        if (i > 31)
            return -1; /* too many options */
        if (opt->type == VSH_OT_BOOL) {
E
Eric Blake 已提交
1502
            if (opt->flags & VSH_OFLAG_REQ)
1503 1504 1505
                return -1; /* bool options can't be mandatory */
            continue;
        }
E
Eric Blake 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
        if (opt->type == VSH_OT_ALIAS) {
            int j;
            if (opt->flags || !opt->help)
                return -1; /* alias options are tracked by the original name */
            for (j = i + 1; cmd->opts[j].name; j++) {
                if (STREQ(opt->help, cmd->opts[j].name))
                    break;
            }
            if (!cmd->opts[j].name)
                return -1; /* alias option must map to a later option name */
            continue;
        }
E
Eric Blake 已提交
1518 1519
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
L
Lai Jiangshan 已提交
1520 1521 1522 1523
                *opts_required |= 1 << i;
            continue;
        }

1524
        *opts_need_arg |= 1 << i;
E
Eric Blake 已提交
1525
        if (opt->flags & VSH_OFLAG_REQ) {
1526 1527 1528 1529 1530 1531
            if (optional)
                return -1; /* mandatory options must be listed first */
            *opts_required |= 1 << i;
        } else {
            optional = true;
        }
1532 1533 1534

        if (opt->type == VSH_OT_ARGV && cmd->opts[i + 1].name)
            return -1; /* argv option must be listed last */
1535 1536 1537 1538
    }
    return 0;
}

1539
static const vshCmdOptDef *
1540
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
1541
                   uint32_t *opts_seen, int *opt_index)
1542
{
1543 1544 1545 1546
    int i;

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

1548
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
1549 1550 1551 1552
            if (opt->type == VSH_OT_ALIAS) {
                name = opt->help;
                continue;
            }
1553
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
1554 1555 1556
                vshError(ctl, _("option --%s already seen"), name);
                return NULL;
            }
1557 1558
            *opts_seen |= 1 << i;
            *opt_index = i;
K
Karel Zak 已提交
1559
            return opt;
1560 1561 1562 1563 1564
        }
    }

    vshError(ctl, _("command '%s' doesn't support option --%s"),
             cmd->name, name);
K
Karel Zak 已提交
1565 1566 1567
    return NULL;
}

1568
static const vshCmdOptDef *
1569 1570
vshCmddefGetData(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                 uint32_t *opts_seen)
1571
{
1572
    int i;
1573
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
1574

1575 1576 1577 1578
    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
E
Eric Blake 已提交
1579
    i = ffs(*opts_need_arg) - 1;
1580
    opt = &cmd->opts[i];
1581
    if (opt->type != VSH_OT_ARGV)
1582
        *opts_need_arg &= ~(1 << i);
1583
    *opts_seen |= 1 << i;
1584
    return opt;
K
Karel Zak 已提交
1585 1586
}

1587 1588 1589
/*
 * Checks for required options
 */
1590
static int
1591 1592
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint32_t opts_required,
                    uint32_t opts_seen)
1593
{
1594
    const vshCmdDef *def = cmd->def;
1595 1596 1597 1598 1599 1600 1601 1602 1603
    int i;

    opts_required &= ~opts_seen;
    if (!opts_required)
        return 0;

    for (i = 0; def->opts[i].name; i++) {
        if (opts_required & (1 << i)) {
            const vshCmdOptDef *opt = &def->opts[i];
1604

1605
            vshError(ctl,
1606
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
1607 1608 1609
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
1610 1611
        }
    }
1612
    return -1;
1613 1614
}

1615
static const vshCmdDef *
1616 1617
vshCmddefSearch(const char *cmdname)
{
1618
    const vshCmdGrp *g;
1619
    const vshCmdDef *c;
1620

1621 1622
    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
1623
            if (STREQ(c->name, cmdname))
1624 1625 1626 1627
                return c;
        }
    }

K
Karel Zak 已提交
1628 1629 1630
    return NULL;
}

1631 1632 1633 1634 1635 1636
static const vshCmdGrp *
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
1637
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
1638 1639 1640 1641 1642 1643
            return g;
    }

    return NULL;
}

E
Eric Blake 已提交
1644
static bool
1645 1646 1647 1648 1649 1650 1651
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 已提交
1652
        return false;
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
    } else {
        vshPrint(ctl, _(" %s (help keyword '%s'):\n"), grp->name,
                 grp->keyword);

        for (cmd = grp->commands; cmd->name; cmd++) {
            vshPrint(ctl, "    %-30s %s\n", cmd->name,
                     _(vshCmddefGetInfo(cmd, "help")));
        }
    }

E
Eric Blake 已提交
1663
    return true;
1664 1665
}

E
Eric Blake 已提交
1666
static bool
1667
vshCmddefHelp(vshControl *ctl, const char *cmdname)
1668
{
1669
    const vshCmdDef *def = vshCmddefSearch(cmdname);
1670

K
Karel Zak 已提交
1671
    if (!def) {
1672
        vshError(ctl, _("command '%s' doesn't exist"), cmdname);
E
Eric Blake 已提交
1673
        return false;
1674
    } else {
E
Eric Blake 已提交
1675 1676
        /* Don't translate desc if it is "".  */
        const char *desc = vshCmddefGetInfo(def, "desc");
E
Eric Blake 已提交
1677
        const char *help = _(vshCmddefGetInfo(def, "help"));
1678
        char buf[256];
1679 1680
        uint32_t opts_need_arg;
        uint32_t opts_required;
1681
        bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
1682 1683 1684 1685

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

1689
        fputs(_("  NAME\n"), stdout);
1690 1691
        fprintf(stdout, "    %s - %s\n", def->name, help);

1692 1693 1694 1695 1696
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
1697
                const char *fmt = "%s";
1698 1699
                switch (opt->type) {
                case VSH_OT_BOOL:
1700
                    fmt = "[--%s]";
1701 1702
                    break;
                case VSH_OT_INT:
E
Eric Blake 已提交
1703
                    /* xgettext:c-format */
E
Eric Blake 已提交
1704
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
1705
                           : _("[--%s <number>]"));
1706 1707
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1708 1709
                    break;
                case VSH_OT_STRING:
E
Eric Blake 已提交
1710 1711
                    /* xgettext:c-format */
                    fmt = _("[--%s <string>]");
1712 1713
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1714 1715
                    break;
                case VSH_OT_DATA:
E
Eric Blake 已提交
1716
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
1717 1718
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1719 1720 1721
                    break;
                case VSH_OT_ARGV:
                    /* xgettext:c-format */
1722 1723 1724 1725 1726 1727 1728 1729
                    if (shortopt) {
                        fmt = (opt->flags & VSH_OFLAG_REQ)
                            ? _("{[--%s] <string>}...")
                            : _("[[--%s] <string>]...");
                    } else {
                        fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                            : _("[<%s>]...");
                    }
1730
                    break;
E
Eric Blake 已提交
1731 1732 1733
                case VSH_OT_ALIAS:
                    /* aliases are intentionally undocumented */
                    continue;
1734
                default:
1735
                    assert(0);
1736
                }
1737
                fputc(' ', stdout);
E
Eric Blake 已提交
1738
                fprintf(stdout, fmt, opt->name);
1739
            }
K
Karel Zak 已提交
1740
        }
1741 1742 1743
        fputc('\n', stdout);

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

K
Karel Zak 已提交
1749
        if (def->opts) {
1750
            const vshCmdOptDef *opt;
1751
            fputs(_("\n  OPTIONS\n"), stdout);
1752
            for (opt = def->opts; opt->name; opt++) {
1753 1754
                switch (opt->type) {
                case VSH_OT_BOOL:
K
Karel Zak 已提交
1755
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1756 1757
                    break;
                case VSH_OT_INT:
1758
                    snprintf(buf, sizeof(buf),
E
Eric Blake 已提交
1759
                             (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
1760
                             : _("--%s <number>"), opt->name);
1761 1762
                    break;
                case VSH_OT_STRING:
1763
                    /* OT_STRING should never be VSH_OFLAG_REQ */
1764
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
1765 1766
                    break;
                case VSH_OT_DATA:
1767 1768
                    snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                             opt->name);
1769 1770
                    break;
                case VSH_OT_ARGV:
1771 1772 1773
                    snprintf(buf, sizeof(buf),
                             shortopt ? _("[--%s] <string>") : _("<%s>"),
                             opt->name);
1774
                    break;
E
Eric Blake 已提交
1775 1776
                case VSH_OT_ALIAS:
                    continue;
1777 1778 1779
                default:
                    assert(0);
                }
1780

E
Eric Blake 已提交
1781
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
1782
            }
K
Karel Zak 已提交
1783 1784 1785
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
1786
    return true;
K
Karel Zak 已提交
1787 1788 1789 1790 1791 1792
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1793 1794 1795
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1796 1797
    vshCmdOpt *a = arg;

1798
    while (a) {
K
Karel Zak 已提交
1799
        vshCmdOpt *tmp = a;
1800

K
Karel Zak 已提交
1801 1802
        a = a->next;

1803 1804
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
1805 1806 1807 1808
    }
}

static void
1809
vshCommandFree(vshCmd *cmd)
1810
{
K
Karel Zak 已提交
1811 1812
    vshCmd *c = cmd;

1813
    while (c) {
K
Karel Zak 已提交
1814
        vshCmd *tmp = c;
1815

K
Karel Zak 已提交
1816 1817 1818 1819
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
1820
        VIR_FREE(tmp);
K
Karel Zak 已提交
1821 1822 1823
    }
}

E
Eric Blake 已提交
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
/**
 * vshCommandOpt:
 * @cmd: parsed command line to search
 * @name: option name to search for
 * @opt: result of the search
 *
 * Look up an option passed to CMD by NAME.  Returns 1 with *OPT set
 * to the option if found, 0 with *OPT set to NULL if the name is
 * valid and the option is not required, -1 with *OPT set to NULL if
 * the option is required but not present, and -2 if NAME is not valid
 * (-2 indicates a programming error).  No error messages are issued.
K
Karel Zak 已提交
1835
 */
E
Eric Blake 已提交
1836 1837
static int
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
1838
{
E
Eric Blake 已提交
1839 1840
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
1841

E
Eric Blake 已提交
1842 1843 1844 1845 1846 1847 1848
    /* See if option is present on command line.  */
    while (candidate) {
        if (STREQ(candidate->def->name, name)) {
            *opt = candidate;
            return 1;
        }
        candidate = candidate->next;
K
Karel Zak 已提交
1849
    }
E
Eric Blake 已提交
1850 1851 1852 1853 1854 1855 1856

    /* Option not present, see if command requires it.  */
    *opt = NULL;
    while (valid) {
        if (!valid->name)
            break;
        if (STREQ(name, valid->name))
E
Eric Blake 已提交
1857
            return (valid->flags & VSH_OFLAG_REQ) == 0 ? 0 : -1;
E
Eric Blake 已提交
1858 1859 1860 1861
        valid++;
    }
    /* If we got here, the name is unknown.  */
    return -2;
K
Karel Zak 已提交
1862 1863
}

E
Eric Blake 已提交
1864 1865
/**
 * vshCommandOptInt:
1866 1867 1868 1869 1870 1871 1872
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Convert option to int
 * Return value:
 * >0 if option found and valid (@value updated)
E
Eric Blake 已提交
1873
 * 0 if option not found and not required (@value untouched)
1874
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
1875 1876
 */
static int
1877
vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
1878
{
E
Eric Blake 已提交
1879 1880
    vshCmdOpt *arg;
    int ret;
1881

E
Eric Blake 已提交
1882 1883 1884 1885 1886 1887 1888
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1889
    }
E
Eric Blake 已提交
1890

E
Eric Blake 已提交
1891 1892 1893
    if (virStrToLong_i(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
K
Karel Zak 已提交
1894 1895
}

1896

E
Eric Blake 已提交
1897 1898 1899 1900 1901 1902
/**
 * vshCommandOptUInt:
 * @cmd command reference
 * @name option name
 * @value result
 *
1903 1904 1905 1906 1907 1908
 * Convert option to unsigned int
 * See vshCommandOptInt()
 */
static int
vshCommandOptUInt(const vshCmd *cmd, const char *name, unsigned int *value)
{
E
Eric Blake 已提交
1909 1910
    vshCmdOpt *arg;
    int ret;
1911

E
Eric Blake 已提交
1912 1913 1914 1915 1916 1917 1918
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1919
    }
E
Eric Blake 已提交
1920

E
Eric Blake 已提交
1921 1922 1923
    if (virStrToLong_ui(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1924 1925 1926
}


1927
/*
E
Eric Blake 已提交
1928 1929 1930 1931 1932
 * vshCommandOptUL:
 * @cmd command reference
 * @name option name
 * @value result
 *
1933 1934 1935 1936 1937
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
static int
vshCommandOptUL(const vshCmd *cmd, const char *name, unsigned long *value)
1938
{
E
Eric Blake 已提交
1939 1940
    vshCmdOpt *arg;
    int ret;
1941

E
Eric Blake 已提交
1942 1943 1944 1945 1946 1947 1948
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1949
    }
E
Eric Blake 已提交
1950

E
Eric Blake 已提交
1951 1952 1953
    if (virStrToLong_ul(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1954 1955
}

E
Eric Blake 已提交
1956 1957 1958 1959 1960 1961
/**
 * vshCommandOptString:
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
1962
 * Returns option as STRING
E
Eric Blake 已提交
1963 1964 1965 1966
 * 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 已提交
1967
 */
1968 1969
static int
vshCommandOptString(const vshCmd *cmd, const char *name, const char **value)
1970
{
E
Eric Blake 已提交
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
    vshCmdOpt *arg;
    int ret;

    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
1981
    }
1982

E
Eric Blake 已提交
1983
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK)) {
E
Eric Blake 已提交
1984 1985 1986 1987
        return -1;
    }
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
1988 1989
}

E
Eric Blake 已提交
1990 1991 1992 1993 1994 1995
/**
 * vshCommandOptLongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
1996
 * Returns option as long long
1997
 * See vshCommandOptInt()
1998
 */
1999 2000 2001
static int
vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                      long long *value)
2002
{
E
Eric Blake 已提交
2003 2004
    vshCmdOpt *arg;
    int ret;
2005

E
Eric Blake 已提交
2006 2007 2008 2009 2010 2011 2012
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
2013
    }
E
Eric Blake 已提交
2014

E
Eric Blake 已提交
2015 2016 2017
    if (virStrToLong_ll(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
2018 2019
}

E
Eric Blake 已提交
2020 2021 2022 2023 2024 2025 2026 2027 2028
/**
 * vshCommandOptULongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long
 * See vshCommandOptInt()
 */
2029 2030 2031 2032
static int
vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                       unsigned long long *value)
{
E
Eric Blake 已提交
2033 2034
    vshCmdOpt *arg;
    int ret;
2035

E
Eric Blake 已提交
2036 2037 2038 2039 2040 2041 2042
    ret = vshCommandOpt(cmd, name, &arg);
    if (ret <= 0)
        return ret;
    if (!arg->data) {
        /* only possible on bool, but if name is bool, this is a
         * programming bug */
        return -2;
2043
    }
E
Eric Blake 已提交
2044

E
Eric Blake 已提交
2045 2046 2047
    if (virStrToLong_ull(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
2048 2049 2050
}


E
Eric Blake 已提交
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
/**
 * vshCommandOptScaledInt:
 * @cmd command reference
 * @name option name
 * @value result
 * @scale default of 1 or 1024, if no suffix is present
 * @max maximum value permitted
 *
 * Returns option as long long, scaled according to suffix
 * See vshCommandOptInt()
 */
static int
vshCommandOptScaledInt(const vshCmd *cmd, const char *name,
                       unsigned long long *value, int scale,
                       unsigned long long max)
{
    const char *str;
    int ret;
    char *end;

    ret = vshCommandOptString(cmd, name, &str);
    if (ret <= 0)
        return ret;
    if (virStrToLong_ull(str, &end, 10, value) < 0 ||
        virScaleInteger(value, end, scale, max) < 0)
        return -1;
    return 1;
}


E
Eric Blake 已提交
2081 2082 2083 2084 2085 2086 2087 2088 2089
/**
 * 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 已提交
2090
 */
E
Eric Blake 已提交
2091
static bool
2092
vshCommandOptBool(const vshCmd *cmd, const char *name)
2093
{
E
Eric Blake 已提交
2094 2095 2096
    vshCmdOpt *dummy;

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

E
Eric Blake 已提交
2099 2100 2101 2102 2103
/**
 * vshCommandOptArgv:
 * @cmd command reference
 * @opt starting point for the search
 *
2104 2105
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
2106
 *
2107
 * Requires that a VSH_OT_ARGV option be last in the
2108 2109
 * list of supported options in CMD->def->opts.
 */
2110 2111
static const vshCmdOpt *
vshCommandOptArgv(const vshCmd *cmd, const vshCmdOpt *opt)
2112
{
2113
    opt = opt ? opt->next : cmd->opts;
2114 2115

    while (opt) {
E
Eric Blake 已提交
2116
        if (opt->def->type == VSH_OT_ARGV) {
2117
            return opt;
2118 2119 2120 2121 2122 2123
        }
        opt = opt->next;
    }
    return NULL;
}

J
Jim Meyering 已提交
2124 2125 2126 2127
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
static bool
2128
cmd_has_option(vshControl *ctl, const vshCmd *cmd, const char *optname)
J
Jim Meyering 已提交
2129 2130 2131 2132 2133 2134
{
    /* Iterate through cmd->opts, to ensure that there is an entry
       with name OPTNAME and type VSH_OT_DATA. */
    bool found = false;
    const vshCmdOpt *opt;
    for (opt = cmd->opts; opt; opt = opt->next) {
2135
        if (STREQ(opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
J
Jim Meyering 已提交
2136 2137 2138 2139 2140 2141
            found = true;
            break;
        }
    }

    if (!found)
2142
        vshError(ctl, _("internal error: virsh %s: no %s VSH_OT_DATA option"),
J
Jim Meyering 已提交
2143 2144 2145
                 cmd->def->name, optname);
    return found;
}
2146

K
Karel Zak 已提交
2147
static virDomainPtr
J
Jim Meyering 已提交
2148
vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
2149
                      const char **name, int flag)
2150
{
K
Karel Zak 已提交
2151
    virDomainPtr dom = NULL;
2152
    const char *n = NULL;
K
Karel Zak 已提交
2153
    int id;
J
Jim Meyering 已提交
2154
    const char *optname = "domain";
2155
    if (!cmd_has_option(ctl, cmd, optname))
J
Jim Meyering 已提交
2156
        return NULL;
2157

2158
    if (vshCommandOptString(cmd, optname, &n) <= 0)
2159 2160
        return NULL;

2161
    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
2162 2163
             cmd->def->name, optname, n);

K
Karel Zak 已提交
2164 2165
    if (name)
        *name = n;
2166

K
Karel Zak 已提交
2167
    /* try it by ID */
2168
    if (flag & VSH_BYID) {
2169
        if (virStrToLong_i(n, NULL, 10, &id) == 0 && id >= 0) {
2170 2171
            vshDebug(ctl, VSH_ERR_DEBUG,
                     "%s: <%s> seems like domain ID\n",
K
Karel Zak 已提交
2172 2173 2174
                     cmd->def->name, optname);
            dom = virDomainLookupByID(ctl->conn, id);
        }
2175
    }
K
Karel Zak 已提交
2176
    /* try it by UUID */
2177
    if (dom==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
2178
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain UUID\n",
2179
                 cmd->def->name, optname);
K
Karel Zak 已提交
2180
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
2181
    }
K
Karel Zak 已提交
2182
    /* try it by NAME */
2183
    if (dom==NULL && (flag & VSH_BYNAME)) {
2184
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain NAME\n",
2185
                 cmd->def->name, optname);
K
Karel Zak 已提交
2186
        dom = virDomainLookupByName(ctl->conn, n);
2187
    }
K
Karel Zak 已提交
2188

2189
    if (!dom)
2190
        vshError(ctl, _("failed to get domain '%s'"), n);
2191

K
Karel Zak 已提交
2192 2193 2194
    return dom;
}

K
Karel Zak 已提交
2195 2196 2197
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
2198
static bool
2199
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
2200
{
E
Eric Blake 已提交
2201
    bool ret = true;
2202 2203

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

2207 2208
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
2209 2210
            vshReconnect(ctl);

2211
        if (enable_timing)
K
Karel Zak 已提交
2212
            GETTIMEOFDAY(&before);
2213

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

2216
        if (enable_timing)
K
Karel Zak 已提交
2217
            GETTIMEOFDAY(&after);
2218

2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
        /* 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++;

2229
        if (!ret)
J
John Levon 已提交
2230 2231
            virshReportError(ctl);

2232
        if (!ret && disconnected != 0)
2233 2234
            vshReconnect(ctl);

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

2238
        if (enable_timing)
2239
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
2240 2241
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
2242
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
2243 2244 2245 2246 2247 2248
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
2249
 * Command parsing
K
Karel Zak 已提交
2250 2251 2252
 * ---------------
 */

2253 2254 2255 2256 2257 2258 2259 2260
typedef enum {
    VSH_TK_ERROR, /* Failed to parse a token */
    VSH_TK_ARG, /* Arbitrary argument, might be option or empty */
    VSH_TK_SUBCMD_END, /* Separation between commands */
    VSH_TK_END /* No more commands */
} vshCommandToken;

typedef struct __vshCommandParser {
2261
    vshCommandToken(*getNextArg)(vshControl *, struct __vshCommandParser *,
2262
                                  char **);
L
Lai Jiangshan 已提交
2263
    /* vshCommandStringGetArg() */
2264
    char *pos;
L
Lai Jiangshan 已提交
2265 2266 2267
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
2268 2269
} vshCommandParser;

E
Eric Blake 已提交
2270
static bool
2271
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
2272
{
K
Karel Zak 已提交
2273 2274 2275
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
2276

K
Karel Zak 已提交
2277 2278 2279 2280
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
2281

2282
    while (1) {
K
Karel Zak 已提交
2283
        vshCmdOpt *last = NULL;
2284
        const vshCmdDef *cmd = NULL;
2285
        vshCommandToken tk;
L
Lai Jiangshan 已提交
2286
        bool data_only = false;
2287 2288 2289
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
2290

K
Karel Zak 已提交
2291
        first = NULL;
2292

2293
        while (1) {
2294
            const vshCmdOptDef *opt = NULL;
2295

K
Karel Zak 已提交
2296
            tkdata = NULL;
2297
            tk = parser->getNextArg(ctl, parser, &tkdata);
2298 2299

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2300
                goto syntaxError;
H
Hu Tao 已提交
2301 2302
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
2303
                break;
H
Hu Tao 已提交
2304
            }
2305 2306

            if (cmd == NULL) {
K
Karel Zak 已提交
2307 2308
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
2309
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
2310
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
2311
                }
2312 2313 2314 2315 2316 2317 2318
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
2319
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
2320 2321 2322 2323
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
2324
                char *optstr = strchr(tkdata + 2, '=');
2325 2326
                int opt_index;

2327 2328 2329 2330
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
2331
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
2332
                                               &opts_seen, &opt_index))) {
2333
                    VIR_FREE(optstr);
K
Karel Zak 已提交
2334 2335
                    goto syntaxError;
                }
2336
                VIR_FREE(tkdata);
K
Karel Zak 已提交
2337 2338 2339

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
2340 2341 2342
                    if (optstr)
                        tkdata = optstr;
                    else
2343
                        tk = parser->getNextArg(ctl, parser, &tkdata);
2344
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2345
                        goto syntaxError;
2346
                    if (tk != VSH_TK_ARG) {
2347
                        vshError(ctl,
2348
                                 _("expected syntax: --%s <%s>"),
2349 2350
                                 opt->name,
                                 opt->type ==
2351
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
2352 2353
                        goto syntaxError;
                    }
2354 2355
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
2356 2357 2358 2359 2360 2361 2362 2363
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                opt->name);
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
2364
                }
L
Lai Jiangshan 已提交
2365 2366 2367 2368
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
2369
            } else {
L
Lai Jiangshan 已提交
2370
get_data:
2371 2372
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
                                             &opts_seen))) {
2373
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
2374 2375 2376 2377 2378
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
2379
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
2380

K
Karel Zak 已提交
2381 2382 2383 2384
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
2385

K
Karel Zak 已提交
2386 2387 2388 2389 2390
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
2391

2392
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
2393 2394
                         cmd->name,
                         opt->name,
2395 2396
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
2397 2398
            }
        }
2399

D
Daniel Veillard 已提交
2400
        /* command parsed -- allocate new struct for the command */
K
Karel Zak 已提交
2401
        if (cmd) {
2402
            vshCmd *c = vshMalloc(ctl, sizeof(vshCmd));
2403

K
Karel Zak 已提交
2404 2405 2406 2407
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

2408
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
2409
                VIR_FREE(c);
2410
                goto syntaxError;
2411
            }
2412

K
Karel Zak 已提交
2413 2414 2415 2416 2417 2418
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
2419 2420 2421

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
2422
    }
2423

E
Eric Blake 已提交
2424
    return true;
K
Karel Zak 已提交
2425

2426
 syntaxError:
2427
    if (ctl->cmd) {
K
Karel Zak 已提交
2428
        vshCommandFree(ctl->cmd);
2429 2430
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
2431 2432
    if (first)
        vshCommandOptFree(first);
2433
    VIR_FREE(tkdata);
E
Eric Blake 已提交
2434
    return false;
K
Karel Zak 已提交
2435 2436
}

2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
/* --------------------
 * 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 已提交
2455 2456
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
2457 2458 2459 2460
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
2461
        return false;
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533

    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 已提交
2534 2535
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
2536 2537 2538 2539
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
2540
        return false;
2541 2542 2543 2544 2545 2546

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

K
Karel Zak 已提交
2547
/* ---------------
2548
 * Misc utils
K
Karel Zak 已提交
2549 2550
 * ---------------
 */
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
static int
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;
}

2579 2580
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
static char *
vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
{
    int ret = 0;
    char *str = NULL;

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

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

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

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

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

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

2612 2613 2614 2615
    case VIR_TYPED_PARAM_STRING:
        str = vshStrdup(ctl, item->value.s);
        break;

2616
    default:
2617
        vshError(ctl, _("unimplemented parameter type %d"), item->type);
2618 2619
    }

2620
    if (ret < 0) {
2621
        vshError(ctl, "%s", _("Out of memory"));
2622 2623
        exit(EXIT_FAILURE);
    }
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646
    return str;
}

static virTypedParameterPtr
vshFindTypedParamByName(const char *name, virTypedParameterPtr list, int count)
{
    int i = count;
    virTypedParameterPtr found = list;

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

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

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

    /* not found */
    return NULL;
}

E
Eric Blake 已提交
2647
static bool
2648
vshConnectionUsability(vshControl *ctl, virConnectPtr conn)
2649
{
2650 2651
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
2652 2653
     */
    if (!conn) {
2654
        vshError(ctl, "%s", _("no valid connection"));
E
Eric Blake 已提交
2655
        return false;
K
Karel Zak 已提交
2656
    }
E
Eric Blake 已提交
2657
    return true;
K
Karel Zak 已提交
2658 2659
}

K
Karel Zak 已提交
2660
static void
2661
vshDebug(vshControl *ctl, int level, const char *format, ...)
2662
{
K
Karel Zak 已提交
2663
    va_list ap;
2664
    char *str;
K
Karel Zak 已提交
2665

2666 2667 2668 2669 2670 2671 2672
    /* Aligning log levels to that of libvirt.
     * Traces with levels >=  user-specified-level
     * gets logged into file
     */
    if (level < ctl->debug)
        return;

2673
    va_start(ap, format);
2674
    vshOutputLogFile(ctl, level, format, ap);
2675 2676
    va_end(ap);

K
Karel Zak 已提交
2677
    va_start(ap, format);
2678 2679 2680 2681 2682
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2683
    va_end(ap);
2684 2685
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
2686 2687 2688
}

static void
2689
vshPrintExtra(vshControl *ctl, const char *format, ...)
2690
{
K
Karel Zak 已提交
2691
    va_list ap;
2692
    char *str;
2693

2694
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
2695
        return;
2696

K
Karel Zak 已提交
2697
    va_start(ap, format);
2698 2699 2700 2701 2702
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2703
    va_end(ap);
2704
    fputs(str, stdout);
2705
    VIR_FREE(str);
K
Karel Zak 已提交
2706 2707
}

K
Karel Zak 已提交
2708

K
Karel Zak 已提交
2709
static void
2710
vshError(vshControl *ctl, const char *format, ...)
2711
{
K
Karel Zak 已提交
2712
    va_list ap;
2713
    char *str;
2714

2715 2716 2717 2718 2719
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
2720

2721 2722 2723 2724
    /* 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);
2725
    fputs(_("error: "), stderr);
2726

K
Karel Zak 已提交
2727
    va_start(ap, format);
2728 2729 2730
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
2731 2732
    va_end(ap);

2733
    fprintf(stderr, "%s\n", NULLSTR(str));
2734
    fflush(stderr);
2735
    VIR_FREE(str);
K
Karel Zak 已提交
2736 2737
}

2738

J
Jiri Denemark 已提交
2739 2740 2741 2742 2743
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

2744 2745 2746 2747 2748 2749 2750 2751 2752 2753
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
J
Jiri Denemark 已提交
2754 2755 2756 2757 2758
            virshReportError(ctl);
    }
}


K
Karel Zak 已提交
2759
/*
2760
 * Initialize connection.
K
Karel Zak 已提交
2761
 */
E
Eric Blake 已提交
2762
static bool
2763
vshInit(vshControl *ctl)
2764
{
2765 2766
    char *debugEnv;

K
Karel Zak 已提交
2767
    if (ctl->conn)
E
Eric Blake 已提交
2768
        return false;
K
Karel Zak 已提交
2769

J
Jiri Denemark 已提交
2770
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
2771 2772 2773
        /* log level not set from commandline, check env variable */
        debugEnv = getenv("VIRSH_DEBUG");
        if (debugEnv) {
J
Jiri Denemark 已提交
2774 2775 2776
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
2777 2778
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
2779 2780
            } else {
                ctl->debug = debug;
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
            }
        }
    }

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

2793 2794
    vshOpenLogFile(ctl);

2795 2796
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2797

2798 2799 2800
    /* set up the signals handlers to catch disconnections */
    vshSetupSignals();

2801
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
2802
        return false;
2803

J
Jiri Denemark 已提交
2804 2805 2806 2807
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

2808 2809 2810 2811
    if (ctl->name) {
        ctl->conn = virConnectOpenAuth(ctl->name,
                                       virConnectAuthPtrDefault,
                                       ctl->readonly ? VIR_CONNECT_RO : 0);
2812

2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
        /* Connecting to a named connection must succeed, but we delay
         * connecting to the default connection until we need it
         * (since the first command might be 'connect' which allows a
         * non-default connection, or might be 'help' which needs no
         * connection).
         */
        if (!ctl->conn) {
            virshReportError(ctl);
            vshError(ctl, "%s", _("failed to connect to the hypervisor"));
            return false;
        }
2824
    }
K
Karel Zak 已提交
2825

E
Eric Blake 已提交
2826
    return true;
K
Karel Zak 已提交
2827 2828
}

2829 2830
#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
/**
 * vshOpenLogFile:
 *
 * Open log file.
 */
static void
vshOpenLogFile(vshControl *ctl)
{
    struct stat st;

    if (ctl->logfile == NULL)
        return;

    /* check log file */
    if (stat(ctl->logfile, &st) == -1) {
        switch (errno) {
            case ENOENT:
                break;
            default:
2850
                vshError(ctl, "%s",
J
Jim Meyering 已提交
2851
                         _("failed to get the log file information"));
2852
                exit(EXIT_FAILURE);
2853 2854 2855
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
2856 2857
            vshError(ctl, "%s", _("the log path is not a file"));
            exit(EXIT_FAILURE);
2858 2859 2860 2861
        }
    }

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

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
static void
2875 2876
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
2877
{
2878 2879 2880
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *str;
    size_t len;
2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894
    const char *lvl = "";
    struct timeval stTimeval;
    struct tm *stTm;

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

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

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

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

2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
    /* write log */
    if (safewrite(ctl->log_fd, str, len) < 0)
        goto error;

    return;

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

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
static void
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
2960 2961 2962
    if (VIR_CLOSE(ctl->log_fd) < 0) {
        vshError(ctl, _("%s: failed to write log file: %s"),
                 ctl->logfile ? ctl->logfile : "?", strerror (errno));
2963 2964 2965
    }

    if (ctl->logfile) {
2966
        VIR_FREE(ctl->logfile);
2967 2968 2969 2970
        ctl->logfile = NULL;
    }
}

2971
#ifdef USE_READLINE
2972

K
Karel Zak 已提交
2973 2974 2975 2976 2977
/* -----------------
 * Readline stuff
 * -----------------
 */

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

    if (!state) {
2992 2993
        grp_list_index = 0;
        cmd_list_index = 0;
2994
        len = strlen(text);
K
Karel Zak 已提交
2995 2996
    }

2997 2998
    grp = cmdGroups;

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

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

static char *
3023 3024
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
3025
    static int list_index, len;
3026
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
3027
    const char *name;
K
Karel Zak 已提交
3028 3029 3030 3031 3032 3033 3034 3035 3036

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

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

3037
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
3038
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
3039 3040 3041

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
3042
        len = strlen(text);
3043
        VIR_FREE(cmdname);
K
Karel Zak 已提交
3044 3045 3046 3047
    }

    if (!cmd)
        return NULL;
3048

3049 3050 3051
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
3052
    while ((name = cmd->opts[list_index].name)) {
3053
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
3054
        char *res;
3055

K
Karel Zak 已提交
3056
        list_index++;
3057

3058
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
3059 3060
            /* ignore non --option */
            continue;
3061

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

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

static char **
3076 3077 3078
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
3079 3080
    char **matches = (char **) NULL;

3081
    if (start == 0)
K
Karel Zak 已提交
3082
        /* command name generator */
3083
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
3084 3085
    else
        /* commands options */
3086
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
3087 3088 3089 3090
    return matches;
}


3091 3092
static int
vshReadlineInit(vshControl *ctl)
3093
{
3094 3095
    char *userdir = NULL;

K
Karel Zak 已提交
3096 3097 3098 3099 3100
    /* Allow conditional parsing of the ~/.inputrc file. */
    rl_readline_name = "virsh";

    /* Tell the completer that we want a crack first. */
    rl_attempted_completion_function = vshReadlineCompletion;
3101 3102 3103

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

3105
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
3106
    userdir = virGetUserCacheDirectory();
3107

3108 3109
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
3110
        return -1;
3111
    }
3112

3113
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
3114
        vshError(ctl, "%s", _("Out of memory"));
3115
        VIR_FREE(userdir);
3116 3117 3118 3119 3120
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
3121
        VIR_FREE(userdir);
3122 3123 3124
        return -1;
    }

3125
    VIR_FREE(userdir);
3126 3127 3128 3129 3130 3131 3132

    read_history(ctl->historyfile);

    return 0;
}

static void
3133
vshReadlineDeinit(vshControl *ctl)
3134 3135
{
    if (ctl->historyfile != NULL) {
3136 3137
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
3138 3139
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
3140
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
3141
        } else {
3142
            write_history(ctl->historyfile);
E
Eric Blake 已提交
3143
        }
3144 3145
    }

3146 3147
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
3148 3149
}

3150
static char *
3151
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
3152
{
3153
    return readline(prompt);
3154 3155
}

3156
#else /* !USE_READLINE */
3157

3158
static int
3159
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
3160 3161 3162 3163 3164
{
    /* empty */
    return 0;
}

3165
static void
3166
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
3167 3168 3169 3170 3171
{
    /* empty */
}

static char *
3172
vshReadline(vshControl *ctl, const char *prompt)
3173 3174 3175 3176 3177
{
    char line[1024];
    char *r;
    int len;

3178 3179
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
3180 3181 3182
    if (r == NULL) return NULL; /* EOF */

    /* Chomp trailing \n */
3183
    len = strlen(r);
3184 3185 3186
    if (len > 0 && r[len-1] == '\n')
        r[len-1] = '\0';

3187
    return vshStrdup(ctl, r);
3188 3189
}

3190
#endif /* !USE_READLINE */
3191

3192 3193 3194 3195 3196 3197
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
3198
/*
J
Jim Meyering 已提交
3199
 * Deinitialize virsh
K
Karel Zak 已提交
3200
 */
E
Eric Blake 已提交
3201
static bool
3202
vshDeinit(vshControl *ctl)
3203
{
3204
    vshReadlineDeinit(ctl);
3205
    vshCloseLogFile(ctl);
3206
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
3207
    if (ctl->conn) {
3208 3209 3210
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
K
Karel Zak 已提交
3211 3212
        }
    }
D
Daniel P. Berrange 已提交
3213 3214
    virResetLastError();

J
Jiri Denemark 已提交
3215
    if (ctl->eventLoopStarted) {
3216 3217 3218 3219
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
3220
        /* HACK: Add a dummy timeout to break event loop */
3221 3222 3223 3224 3225
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
3226 3227 3228 3229 3230 3231
        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

3232 3233
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
3234
    return true;
K
Karel Zak 已提交
3235
}
3236

K
Karel Zak 已提交
3237 3238 3239 3240
/*
 * Print usage
 */
static void
3241
vshUsage(void)
3242
{
3243
    const vshCmdGrp *grp;
3244
    const vshCmdDef *cmd;
3245

L
Lai Jiangshan 已提交
3246 3247
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
3248
                      "  options:\n"
3249
                      "    -c | --connect=URI      hypervisor connection URI\n"
3250
                      "    -r | --readonly         connect readonly\n"
3251
                      "    -d | --debug=NUM        debug level [0-4]\n"
3252 3253 3254
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
3255 3256 3257 3258 3259
                      "    -l | --log=FILE         output logging to file\n"
                      "    -v                      short version\n"
                      "    -V                      long version\n"
                      "         --version[=TYPE]   version, TYPE is short or long (default short)\n"
                      "    -e | --escape <char>    set escape sequence for console\n\n"
3260
                      "  commands (non interactive mode):\n\n"), progname, progname);
3261

3262
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
3263 3264 3265 3266 3267
        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;
3268
            fprintf(stdout,
E
Eric Blake 已提交
3269 3270 3271
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
3272 3273 3274 3275 3276
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
3277 3278 3279
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
3280 3281
}

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

L
Laine Stump 已提交
3335
    vshPrint(ctl, "%s", _(" Networking:"));
3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348
#ifdef WITH_REMOTE
    vshPrint(ctl, " Remote");
#endif
#ifdef WITH_LIBVIRTD
    vshPrint(ctl, " Daemon");
#endif
#ifdef WITH_NETWORK
    vshPrint(ctl, " Network");
#endif
#ifdef WITH_BRIDGE
    vshPrint(ctl, " Bridging");
#endif
#ifdef WITH_NETCF
D
Doug Goldstein 已提交
3349
    vshPrint(ctl, " Interface");
3350 3351 3352 3353 3354 3355 3356 3357 3358
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

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

3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518
    vshPrint(ctl, "%s", _(" Miscellaneous:"));
#ifdef WITH_NODE_DEVICES
    vshPrint(ctl, " Nodedev");
#endif
#ifdef WITH_SECDRIVER_APPARMOR
    vshPrint(ctl, " AppArmor");
#endif
#ifdef WITH_SECDRIVER_SELINUX
    vshPrint(ctl, " SELinux");
#endif
#ifdef WITH_SECRETS
    vshPrint(ctl, " Secrets");
#endif
#ifdef ENABLE_DEBUG
    vshPrint(ctl, " Debug");
#endif
#ifdef WITH_DTRACE_PROBES
    vshPrint(ctl, " DTrace");
#endif
#ifdef USE_READLINE
    vshPrint(ctl, " Readline");
#endif
#ifdef WITH_DRIVER_MODULES
    vshPrint(ctl, " Modular");
#endif
    vshPrint(ctl, "\n");
}

static bool
vshAllowedEscapeChar(char c)
{
    /* Allowed escape characters:
     * a-z A-Z @ [ \ ] ^ _
     */
    return ('a' <= c && c <= 'z') ||
        ('@' <= c && c <= '_');
}

/*
 * argv[]:  virsh [options] [command]
 *
 */
static bool
vshParseArgv(vshControl *ctl, int argc, char **argv)
{
    int arg, len;
    struct option opt[] = {
        {"debug", required_argument, NULL, 'd'},
        {"help", no_argument, NULL, 'h'},
        {"quiet", no_argument, NULL, 'q'},
        {"timing", no_argument, NULL, 't'},
        {"version", optional_argument, NULL, 'v'},
        {"connect", required_argument, NULL, 'c'},
        {"readonly", no_argument, NULL, 'r'},
        {"log", required_argument, NULL, 'l'},
        {"escape", required_argument, NULL, 'e'},
        {NULL, 0, NULL, 0}
    };

    /* Standard (non-command) options. The leading + ensures that no
     * argument reordering takes place, so that command options are
     * not confused with top-level virsh options. */
    while ((arg = getopt_long(argc, argv, "+d:hqtc:vVrl:e:", opt, NULL)) != -1) {
        switch (arg) {
        case 'd':
            if (virStrToLong_i(optarg, NULL, 10, &ctl->debug) < 0) {
                vshError(ctl, "%s", _("option -d takes a numeric argument"));
                exit(EXIT_FAILURE);
            }
            break;
        case 'h':
            vshUsage();
            exit(EXIT_SUCCESS);
            break;
        case 'q':
            ctl->quiet = true;
            break;
        case 't':
            ctl->timing = true;
            break;
        case 'c':
            ctl->name = vshStrdup(ctl, optarg);
            break;
        case 'v':
            if (STRNEQ_NULLABLE(optarg, "long")) {
                puts(VERSION);
                exit(EXIT_SUCCESS);
            }
            /* fall through */
        case 'V':
            vshShowVersion(ctl);
            exit(EXIT_SUCCESS);
        case 'r':
            ctl->readonly = true;
            break;
        case 'l':
            ctl->logfile = vshStrdup(ctl, optarg);
            break;
        case 'e':
            len = strlen(optarg);

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

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

3519 3520
#include "virsh-domain.c"

3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
static const vshCmdDef domManagementCmds[] = {
    {"attach-device", cmdAttachDevice, opts_attach_device,
     info_attach_device, 0},
    {"attach-disk", cmdAttachDisk, opts_attach_disk,
     info_attach_disk, 0},
    {"attach-interface", cmdAttachInterface, opts_attach_interface,
     info_attach_interface, 0},
    {"autostart", cmdAutostart, opts_autostart, info_autostart, 0},
    {"blkdeviotune", cmdBlkdeviotune, opts_blkdeviotune, info_blkdeviotune, 0},
    {"blkiotune", cmdBlkiotune, opts_blkiotune, info_blkiotune, 0},
    {"blockcopy", cmdBlockCopy, opts_block_copy, info_block_copy, 0},
    {"blockjob", cmdBlockJob, opts_block_job, info_block_job, 0},
    {"blockpull", cmdBlockPull, opts_block_pull, info_block_pull, 0},
    {"blockresize", cmdBlockResize, opts_block_resize, info_block_resize, 0},
    {"change-media", cmdChangeMedia, opts_change_media, info_change_media, 0},
#ifndef WIN32
    {"console", cmdConsole, opts_console, info_console, 0},
#endif
    {"cpu-baseline", cmdCPUBaseline, opts_cpu_baseline, info_cpu_baseline, 0},
    {"cpu-compare", cmdCPUCompare, opts_cpu_compare, info_cpu_compare, 0},
    {"cpu-stats", cmdCPUStats, opts_cpu_stats, info_cpu_stats, 0},
    {"create", cmdCreate, opts_create, info_create, 0},
    {"define", cmdDefine, opts_define, info_define, 0},
    {"desc", cmdDesc, opts_desc, info_desc, 0},
    {"destroy", cmdDestroy, opts_destroy, info_destroy, 0},
    {"detach-device", cmdDetachDevice, opts_detach_device,
     info_detach_device, 0},
    {"detach-disk", cmdDetachDisk, opts_detach_disk, info_detach_disk, 0},
    {"detach-interface", cmdDetachInterface, opts_detach_interface,
     info_detach_interface, 0},
    {"domdisplay", cmdDomDisplay, opts_domdisplay, info_domdisplay, 0},
    {"domhostname", cmdDomHostname, opts_domhostname, info_domhostname, 0},
    {"domid", cmdDomid, opts_domid, info_domid, 0},
    {"domif-setlink", cmdDomIfSetLink, opts_domif_setlink, info_domif_setlink, 0},
    {"domiftune", cmdDomIftune, opts_domiftune, info_domiftune, 0},
    {"domjobabort", cmdDomjobabort, opts_domjobabort, info_domjobabort, 0},
    {"domjobinfo", cmdDomjobinfo, opts_domjobinfo, info_domjobinfo, 0},
    {"domname", cmdDomname, opts_domname, info_domname, 0},
    {"dompmsuspend", cmdDomPMSuspend,
     opts_dom_pm_suspend, info_dom_pm_suspend, 0},
    {"dompmwakeup", cmdDomPMWakeup,
     opts_dom_pm_wakeup, info_dom_pm_wakeup, 0},
    {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid, 0},
    {"domxml-from-native", cmdDomXMLFromNative, opts_domxmlfromnative,
     info_domxmlfromnative, 0},
    {"domxml-to-native", cmdDomXMLToNative, opts_domxmltonative,
     info_domxmltonative, 0},
    {"dump", cmdDump, opts_dump, info_dump, 0},
    {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml, 0},
    {"edit", cmdEdit, opts_edit, info_edit, 0},
    {"inject-nmi", cmdInjectNMI, opts_inject_nmi, info_inject_nmi, 0},
    {"send-key", cmdSendKey, opts_send_key, info_send_key, 0},
    {"managedsave", cmdManagedSave, opts_managedsave, info_managedsave, 0},
    {"managedsave-remove", cmdManagedSaveRemove, opts_managedsaveremove,
     info_managedsaveremove, 0},
    {"maxvcpus", cmdMaxvcpus, opts_maxvcpus, info_maxvcpus, 0},
    {"memtune", cmdMemtune, opts_memtune, info_memtune, 0},
    {"migrate", cmdMigrate, opts_migrate, info_migrate, 0},
    {"migrate-setmaxdowntime", cmdMigrateSetMaxDowntime,
     opts_migrate_setmaxdowntime, info_migrate_setmaxdowntime, 0},
    {"migrate-setspeed", cmdMigrateSetMaxSpeed,
     opts_migrate_setspeed, info_migrate_setspeed, 0},
    {"migrate-getspeed", cmdMigrateGetMaxSpeed,
     opts_migrate_getspeed, info_migrate_getspeed, 0},
    {"numatune", cmdNumatune, opts_numatune, info_numatune, 0},
    {"reboot", cmdReboot, opts_reboot, info_reboot, 0},
    {"reset", cmdReset, opts_reset, info_reset, 0},
    {"restore", cmdRestore, opts_restore, info_restore, 0},
    {"resume", cmdResume, opts_resume, info_resume, 0},
    {"save", cmdSave, opts_save, info_save, 0},
    {"save-image-define", cmdSaveImageDefine, opts_save_image_define,
     info_save_image_define, 0},
    {"save-image-dumpxml", cmdSaveImageDumpxml, opts_save_image_dumpxml,
     info_save_image_dumpxml, 0},
    {"save-image-edit", cmdSaveImageEdit, opts_save_image_edit,
     info_save_image_edit, 0},
    {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo, 0},
    {"screenshot", cmdScreenshot, opts_screenshot, info_screenshot, 0},
    {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem, 0},
    {"setmem", cmdSetmem, opts_setmem, info_setmem, 0},
    {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus, 0},
    {"shutdown", cmdShutdown, opts_shutdown, info_shutdown, 0},
    {"start", cmdStart, opts_start, info_start, 0},
    {"suspend", cmdSuspend, opts_suspend, info_suspend, 0},
    {"ttyconsole", cmdTTYConsole, opts_ttyconsole, info_ttyconsole, 0},
    {"undefine", cmdUndefine, opts_undefine, info_undefine, 0},
    {"update-device", cmdUpdateDevice, opts_update_device,
     info_update_device, 0},
    {"vcpucount", cmdVcpucount, opts_vcpucount, info_vcpucount, 0},
    {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo, 0},
    {"vcpupin", cmdVcpuPin, opts_vcpupin, info_vcpupin, 0},
    {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay, 0},
    {NULL, NULL, NULL, NULL, 0}
};

3616 3617
#include "virsh-domain-monitor.c"

3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633
static const vshCmdDef domMonitoringCmds[] = {
    {"domblkerror", cmdDomBlkError, opts_domblkerror, info_domblkerror, 0},
    {"domblkinfo", cmdDomblkinfo, opts_domblkinfo, info_domblkinfo, 0},
    {"domblklist", cmdDomblklist, opts_domblklist, info_domblklist, 0},
    {"domblkstat", cmdDomblkstat, opts_domblkstat, info_domblkstat, 0},
    {"domcontrol", cmdDomControl, opts_domcontrol, info_domcontrol, 0},
    {"domif-getlink", cmdDomIfGetLink, opts_domif_getlink, info_domif_getlink, 0},
    {"domiflist", cmdDomiflist, opts_domiflist, info_domiflist, 0},
    {"domifstat", cmdDomIfstat, opts_domifstat, info_domifstat, 0},
    {"dominfo", cmdDominfo, opts_dominfo, info_dominfo, 0},
    {"dommemstat", cmdDomMemStat, opts_dommemstat, info_dommemstat, 0},
    {"domstate", cmdDomstate, opts_domstate, info_domstate, 0},
    {"list", cmdList, opts_list, info_list, 0},
    {NULL, NULL, NULL, NULL, 0}
};

3634 3635
#include "virsh-pool.c"

3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662
static const vshCmdDef storagePoolCmds[] = {
    {"find-storage-pool-sources-as", cmdPoolDiscoverSourcesAs,
     opts_find_storage_pool_sources_as, info_find_storage_pool_sources_as, 0},
    {"find-storage-pool-sources", cmdPoolDiscoverSources,
     opts_find_storage_pool_sources, info_find_storage_pool_sources, 0},
    {"pool-autostart", cmdPoolAutostart, opts_pool_autostart,
     info_pool_autostart, 0},
    {"pool-build", cmdPoolBuild, opts_pool_build, info_pool_build, 0},
    {"pool-create-as", cmdPoolCreateAs, opts_pool_X_as, info_pool_create_as, 0},
    {"pool-create", cmdPoolCreate, opts_pool_create, info_pool_create, 0},
    {"pool-define-as", cmdPoolDefineAs, opts_pool_X_as, info_pool_define_as, 0},
    {"pool-define", cmdPoolDefine, opts_pool_define, info_pool_define, 0},
    {"pool-delete", cmdPoolDelete, opts_pool_delete, info_pool_delete, 0},
    {"pool-destroy", cmdPoolDestroy, opts_pool_destroy, info_pool_destroy, 0},
    {"pool-dumpxml", cmdPoolDumpXML, opts_pool_dumpxml, info_pool_dumpxml, 0},
    {"pool-edit", cmdPoolEdit, opts_pool_edit, info_pool_edit, 0},
    {"pool-info", cmdPoolInfo, opts_pool_info, info_pool_info, 0},
    {"pool-list", cmdPoolList, opts_pool_list, info_pool_list, 0},
    {"pool-name", cmdPoolName, opts_pool_name, info_pool_name, 0},
    {"pool-refresh", cmdPoolRefresh, opts_pool_refresh, info_pool_refresh, 0},
    {"pool-start", cmdPoolStart, opts_pool_start, info_pool_start, 0},
    {"pool-undefine", cmdPoolUndefine, opts_pool_undefine,
     info_pool_undefine, 0},
    {"pool-uuid", cmdPoolUuid, opts_pool_uuid, info_pool_uuid, 0},
    {NULL, NULL, NULL, NULL, 0}
};

3663 3664
#include "virsh-volume.c"

3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
static const vshCmdDef storageVolCmds[] = {
    {"vol-clone", cmdVolClone, opts_vol_clone, info_vol_clone, 0},
    {"vol-create-as", cmdVolCreateAs, opts_vol_create_as,
     info_vol_create_as, 0},
    {"vol-create", cmdVolCreate, opts_vol_create, info_vol_create, 0},
    {"vol-create-from", cmdVolCreateFrom, opts_vol_create_from,
     info_vol_create_from, 0},
    {"vol-delete", cmdVolDelete, opts_vol_delete, info_vol_delete, 0},
    {"vol-download", cmdVolDownload, opts_vol_download, info_vol_download, 0},
    {"vol-dumpxml", cmdVolDumpXML, opts_vol_dumpxml, info_vol_dumpxml, 0},
    {"vol-info", cmdVolInfo, opts_vol_info, info_vol_info, 0},
    {"vol-key", cmdVolKey, opts_vol_key, info_vol_key, 0},
    {"vol-list", cmdVolList, opts_vol_list, info_vol_list, 0},
    {"vol-name", cmdVolName, opts_vol_name, info_vol_name, 0},
    {"vol-path", cmdVolPath, opts_vol_path, info_vol_path, 0},
    {"vol-pool", cmdVolPool, opts_vol_pool, info_vol_pool, 0},
    {"vol-resize", cmdVolResize, opts_vol_resize, info_vol_resize, 0},
    {"vol-upload", cmdVolUpload, opts_vol_upload, info_vol_upload, 0},
    {"vol-wipe", cmdVolWipe, opts_vol_wipe, info_vol_wipe, 0},
    {NULL, NULL, NULL, NULL, 0}
};

3687 3688
#include "virsh-network.c"

3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730
static const vshCmdDef networkCmds[] = {
    {"net-autostart", cmdNetworkAutostart, opts_network_autostart,
     info_network_autostart, 0},
    {"net-create", cmdNetworkCreate, opts_network_create,
     info_network_create, 0},
    {"net-define", cmdNetworkDefine, opts_network_define,
     info_network_define, 0},
    {"net-destroy", cmdNetworkDestroy, opts_network_destroy,
     info_network_destroy, 0},
    {"net-dumpxml", cmdNetworkDumpXML, opts_network_dumpxml,
     info_network_dumpxml, 0},
    {"net-edit", cmdNetworkEdit, opts_network_edit, info_network_edit, 0},
    {"net-info", cmdNetworkInfo, opts_network_info, info_network_info, 0},
    {"net-list", cmdNetworkList, opts_network_list, info_network_list, 0},
    {"net-name", cmdNetworkName, opts_network_name, info_network_name, 0},
    {"net-start", cmdNetworkStart, opts_network_start, info_network_start, 0},
    {"net-undefine", cmdNetworkUndefine, opts_network_undefine,
     info_network_undefine, 0},
    {"net-uuid", cmdNetworkUuid, opts_network_uuid, info_network_uuid, 0},
    {NULL, NULL, NULL, NULL, 0}
};

static const vshCmdDef nodedevCmds[] = {
    {"nodedev-create", cmdNodeDeviceCreate, opts_node_device_create,
     info_node_device_create, 0},
    {"nodedev-destroy", cmdNodeDeviceDestroy, opts_node_device_destroy,
     info_node_device_destroy, 0},
    {"nodedev-detach", cmdNodeDeviceDetach, opts_node_device_detach,
     info_node_device_detach, 0},
    {"nodedev-dettach", cmdNodeDeviceDetach, opts_node_device_detach,
     info_node_device_detach, VSH_CMD_FLAG_ALIAS},
    {"nodedev-dumpxml", cmdNodeDeviceDumpXML, opts_node_device_dumpxml,
     info_node_device_dumpxml, 0},
    {"nodedev-list", cmdNodeListDevices, opts_node_list_devices,
     info_node_list_devices, 0},
    {"nodedev-reattach", cmdNodeDeviceReAttach, opts_node_device_reattach,
     info_node_device_reattach, 0},
    {"nodedev-reset", cmdNodeDeviceReset, opts_node_device_reset,
     info_node_device_reset, 0},
    {NULL, NULL, NULL, NULL, 0}
};

3731 3732
#include "virsh-interface.c"

3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763
static const vshCmdDef ifaceCmds[] = {
    {"iface-begin", cmdInterfaceBegin, opts_interface_begin,
     info_interface_begin, 0},
    {"iface-bridge", cmdInterfaceBridge, opts_interface_bridge,
     info_interface_bridge, 0},
    {"iface-commit", cmdInterfaceCommit, opts_interface_commit,
     info_interface_commit, 0},
    {"iface-define", cmdInterfaceDefine, opts_interface_define,
     info_interface_define, 0},
    {"iface-destroy", cmdInterfaceDestroy, opts_interface_destroy,
     info_interface_destroy, 0},
    {"iface-dumpxml", cmdInterfaceDumpXML, opts_interface_dumpxml,
     info_interface_dumpxml, 0},
    {"iface-edit", cmdInterfaceEdit, opts_interface_edit,
     info_interface_edit, 0},
    {"iface-list", cmdInterfaceList, opts_interface_list,
     info_interface_list, 0},
    {"iface-mac", cmdInterfaceMAC, opts_interface_mac,
     info_interface_mac, 0},
    {"iface-name", cmdInterfaceName, opts_interface_name,
     info_interface_name, 0},
    {"iface-rollback", cmdInterfaceRollback, opts_interface_rollback,
     info_interface_rollback, 0},
    {"iface-start", cmdInterfaceStart, opts_interface_start,
     info_interface_start, 0},
    {"iface-unbridge", cmdInterfaceUnbridge, opts_interface_unbridge,
     info_interface_unbridge, 0},
    {"iface-undefine", cmdInterfaceUndefine, opts_interface_undefine,
     info_interface_undefine, 0},
    {NULL, NULL, NULL, NULL, 0}
};
3764

3765 3766
#include "virsh-nwfilter.c"

3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779
static const vshCmdDef nwfilterCmds[] = {
    {"nwfilter-define", cmdNWFilterDefine, opts_nwfilter_define,
     info_nwfilter_define, 0},
    {"nwfilter-dumpxml", cmdNWFilterDumpXML, opts_nwfilter_dumpxml,
     info_nwfilter_dumpxml, 0},
    {"nwfilter-edit", cmdNWFilterEdit, opts_nwfilter_edit,
     info_nwfilter_edit, 0},
    {"nwfilter-list", cmdNWFilterList, opts_nwfilter_list,
     info_nwfilter_list, 0},
    {"nwfilter-undefine", cmdNWFilterUndefine, opts_nwfilter_undefine,
     info_nwfilter_undefine, 0},
    {NULL, NULL, NULL, NULL, 0}
};
3780

3781 3782
#include "virsh-secret.c"

3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796
static const vshCmdDef secretCmds[] = {
    {"secret-define", cmdSecretDefine, opts_secret_define,
     info_secret_define, 0},
    {"secret-dumpxml", cmdSecretDumpXML, opts_secret_dumpxml,
     info_secret_dumpxml, 0},
    {"secret-get-value", cmdSecretGetValue, opts_secret_get_value,
     info_secret_get_value, 0},
    {"secret-list", cmdSecretList, NULL, info_secret_list, 0},
    {"secret-set-value", cmdSecretSetValue, opts_secret_set_value,
     info_secret_set_value, 0},
    {"secret-undefine", cmdSecretUndefine, opts_secret_undefine,
     info_secret_undefine, 0},
    {NULL, NULL, NULL, NULL, 0}
};
3797

3798 3799 3800 3801 3802 3803 3804 3805 3806
static const vshCmdDef virshCmds[] = {
    {"cd", cmdCd, opts_cd, info_cd, VSH_CMD_FLAG_NOCONNECT},
    {"echo", cmdEcho, opts_echo, info_echo, VSH_CMD_FLAG_NOCONNECT},
    {"exit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT},
    {"help", cmdHelp, opts_help, info_help, VSH_CMD_FLAG_NOCONNECT},
    {"pwd", cmdPwd, NULL, info_pwd, VSH_CMD_FLAG_NOCONNECT},
    {"quit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT},
    {NULL, NULL, NULL, NULL, 0}
};
3807

3808 3809
#include "virsh-snapshot.c"

3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832
static const vshCmdDef snapshotCmds[] = {
    {"snapshot-create", cmdSnapshotCreate, opts_snapshot_create,
     info_snapshot_create, 0},
    {"snapshot-create-as", cmdSnapshotCreateAs, opts_snapshot_create_as,
     info_snapshot_create_as, 0},
    {"snapshot-current", cmdSnapshotCurrent, opts_snapshot_current,
     info_snapshot_current, 0},
    {"snapshot-delete", cmdSnapshotDelete, opts_snapshot_delete,
     info_snapshot_delete, 0},
    {"snapshot-dumpxml", cmdSnapshotDumpXML, opts_snapshot_dumpxml,
     info_snapshot_dumpxml, 0},
    {"snapshot-edit", cmdSnapshotEdit, opts_snapshot_edit,
     info_snapshot_edit, 0},
    {"snapshot-info", cmdSnapshotInfo, opts_snapshot_info,
     info_snapshot_info, 0},
    {"snapshot-list", cmdSnapshotList, opts_snapshot_list,
     info_snapshot_list, 0},
    {"snapshot-parent", cmdSnapshotParent, opts_snapshot_parent,
     info_snapshot_parent, 0},
    {"snapshot-revert", cmdDomainSnapshotRevert, opts_snapshot_revert,
     info_snapshot_revert, 0},
    {NULL, NULL, NULL, NULL, 0}
};
K
Karel Zak 已提交
3833

3834 3835
#include "virsh-host.c"

3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
static const vshCmdDef hostAndHypervisorCmds[] = {
    {"capabilities", cmdCapabilities, NULL, info_capabilities, 0},
    {"connect", cmdConnect, opts_connect, info_connect,
     VSH_CMD_FLAG_NOCONNECT},
    {"freecell", cmdFreecell, opts_freecell, info_freecell, 0},
    {"hostname", cmdHostname, NULL, info_hostname, 0},
    {"nodecpustats", cmdNodeCpuStats, opts_node_cpustats, info_nodecpustats, 0},
    {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo, 0},
    {"nodememstats", cmdNodeMemStats, opts_node_memstats, info_nodememstats, 0},
    {"nodesuspend", cmdNodeSuspend, opts_node_suspend, info_nodesuspend, 0},
    {"qemu-attach", cmdQemuAttach, opts_qemu_attach, info_qemu_attach, 0},
    {"qemu-monitor-command", cmdQemuMonitorCommand, opts_qemu_monitor_command,
     info_qemu_monitor_command, 0},
    {"sysinfo", cmdSysinfo, NULL, info_sysinfo, 0},
    {"uri", cmdURI, NULL, info_uri, 0},
    {"version", cmdVersion, opts_version, info_version, 0},
    {NULL, NULL, NULL, NULL, 0}
};

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 已提交
3870

3871 3872 3873 3874
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
3875
    char *defaultConn;
E
Eric Blake 已提交
3876
    bool ret = true;
K
Karel Zak 已提交
3877

3878 3879 3880
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
3881
    ctl->debug = VSH_DEBUG_DEFAULT;
3882 3883
    ctl->escapeChar = CTRL_CLOSE_BRACKET;

3884

3885 3886
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
3887
        /* failure to setup locale is not fatal */
3888
    }
3889
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
3890
        perror("bindtextdomain");
E
Eric Blake 已提交
3891
        return EXIT_FAILURE;
3892
    }
3893
    if (!textdomain(PACKAGE)) {
3894
        perror("textdomain");
E
Eric Blake 已提交
3895
        return EXIT_FAILURE;
3896 3897
    }

3898 3899 3900 3901 3902
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

3903 3904 3905 3906 3907
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

3908
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
3909 3910 3911
        progname = argv[0];
    else
        progname++;
3912

3913
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
E
Eric Blake 已提交
3914
        ctl->name = vshStrdup(ctl, defaultConn);
3915 3916
    }

D
Daniel P. Berrange 已提交
3917 3918
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
3919
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3920
    }
3921

D
Daniel P. Berrange 已提交
3922 3923
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
3924
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3925
    }
3926

K
Karel Zak 已提交
3927
    if (!ctl->imode) {
3928
        ret = vshCommandRun(ctl, ctl->cmd);
3929
    } else {
K
Karel Zak 已提交
3930 3931
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
3932
            vshPrint(ctl,
3933
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
3934
                     progname);
J
Jim Meyering 已提交
3935
            vshPrint(ctl, "%s",
3936
                     _("Type:  'help' for help with commands\n"
3937
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
3938
        }
3939 3940 3941 3942 3943 3944

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

K
Karel Zak 已提交
3945
        do {
3946
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
3947
            ctl->cmdstr =
3948
                vshReadline(ctl, prompt);
3949 3950
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
3951
            if (*ctl->cmdstr) {
3952
#if USE_READLINE
K
Karel Zak 已提交
3953
                add_history(ctl->cmdstr);
3954
#endif
3955
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
3956 3957
                    vshCommandRun(ctl, ctl->cmd);
            }
3958
            VIR_FREE(ctl->cmdstr);
3959
        } while (ctl->imode);
K
Karel Zak 已提交
3960

3961 3962
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
3963
    }
3964

K
Karel Zak 已提交
3965 3966
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
3967
}