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

25
#include <config.h>
26

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

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

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

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

static char *progname;

83 84
#define VIRSH_MAX_XML_FILE 10*1024*1024

K
Karel Zak 已提交
85 86 87
#define VSH_PROMPT_RW    "virsh # "
#define VSH_PROMPT_RO    "virsh > "

88 89
#define VIR_FROM_THIS VIR_FROM_NONE

K
Karel Zak 已提交
90 91 92 93 94
#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)

95 96 97
/* Default escape char Ctrl-] as per telnet */
#define CTRL_CLOSE_BRACKET "^]"

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
/**
 * 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 已提交
115
 * Indicates the level of a log message
116 117 118 119 120 121 122 123 124
 */
typedef enum {
    VSH_ERR_DEBUG = 0,
    VSH_ERR_INFO,
    VSH_ERR_NOTICE,
    VSH_ERR_WARNING,
    VSH_ERR_ERROR
} vshErrorLevel;

J
Jiri Denemark 已提交
125 126
#define VSH_DEBUG_DEFAULT VSH_ERR_ERROR

K
Karel Zak 已提交
127 128 129 130 131
/*
 * virsh command line grammar:
 *
 *    command_line    =     <command>\n | <command>; <command>; ...
 *
E
Eric Blake 已提交
132
 *    command         =    <keyword> <option> [--] <data>
K
Karel Zak 已提交
133 134 135 136 137
 *
 *    option          =     <bool_option> | <int_option> | <string_option>
 *    data            =     <string>
 *
 *    bool_option     =     --optionname
E
Eric Blake 已提交
138 139
 *    int_option      =     --optionname <number> | --optionname=<number>
 *    string_option   =     --optionname <string> | --optionname=<string>
140
 *
E
Eric Blake 已提交
141
 *    keyword         =     [a-zA-Z][a-zA-Z-]*
142
 *    number          =     [0-9]+
E
Eric Blake 已提交
143
 *    string          =     ('[^']*'|"([^\\"]|\\.)*"|([^ \t\n\\'"]|\\.))+
K
Karel Zak 已提交
144 145 146 147
 *
 */

/*
148
 * vshCmdOptType - command option type
149
 */
K
Karel Zak 已提交
150
typedef enum {
151 152 153
    VSH_OT_BOOL,     /* optional boolean option */
    VSH_OT_STRING,   /* optional string option */
    VSH_OT_INT,      /* optional or mandatory int option */
154
    VSH_OT_DATA,     /* string data (as non-option) */
E
Eric Blake 已提交
155 156
    VSH_OT_ARGV,     /* remaining arguments */
    VSH_OT_ALIAS,    /* alternate spelling for a later argument */
K
Karel Zak 已提交
157 158
} vshCmdOptType;

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
/*
 * 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 已提交
175 176 177
/*
 * Command Option Flags
 */
E
Eric Blake 已提交
178 179 180 181
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 已提交
182
    VSH_OFLAG_REQ_OPT  = (1 << 2), /* --optionname required */
E
Eric Blake 已提交
183
};
K
Karel Zak 已提交
184 185 186 187 188 189

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

/*
E
Eric Blake 已提交
190 191 192 193 194
 * 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 已提交
195
 */
196
typedef struct {
E
Eric Blake 已提交
197 198
    const char *name;           /* name of information, or NULL for list end */
    const char *data;           /* non-NULL information */
K
Karel Zak 已提交
199 200 201 202 203
} vshCmdInfo;

/*
 * vshCmdOptDef - command option definition
 */
204
typedef struct {
E
Eric Blake 已提交
205
    const char *name;           /* the name of option, or NULL for list end */
206
    vshCmdOptType type;         /* option type */
E
Eric Blake 已提交
207
    unsigned int flags;         /* flags */
E
Eric Blake 已提交
208 209
    const char *help;           /* non-NULL help string; or for VSH_OT_ALIAS
                                 * the name of a later public option */
K
Karel Zak 已提交
210 211 212 213
} vshCmdOptDef;

/*
 * vshCmdOpt - command options
E
Eric Blake 已提交
214 215 216
 *
 * After parsing a command, all arguments to the command have been
 * collected into a list of these objects.
K
Karel Zak 已提交
217 218
 */
typedef struct vshCmdOpt {
E
Eric Blake 已提交
219 220
    const vshCmdOptDef *def;    /* non-NULL pointer to option definition */
    char *data;                 /* allocated data, or NULL for bool option */
221
    struct vshCmdOpt *next;
K
Karel Zak 已提交
222 223
} vshCmdOpt;

224 225 226 227 228
/*
 * Command Usage Flags
 */
enum {
    VSH_CMD_FLAG_NOCONNECT = (1 << 0),  /* no prior connection needed */
229
    VSH_CMD_FLAG_ALIAS     = (1 << 1),  /* command is an alias */
230 231
};

K
Karel Zak 已提交
232 233 234
/*
 * vshCmdDef - command definition
 */
235
typedef struct {
E
Eric Blake 已提交
236
    const char *name;           /* name of command, or NULL for list end */
E
Eric Blake 已提交
237
    bool (*handler) (vshControl *, const vshCmd *);    /* command handler */
238 239
    const vshCmdOptDef *opts;   /* definition of command options */
    const vshCmdInfo *info;     /* details about command */
240
    unsigned int flags;         /* bitwise OR of VSH_CMD_FLAG */
K
Karel Zak 已提交
241 242 243 244 245 246
} vshCmdDef;

/*
 * vshCmd - parsed command
 */
typedef struct __vshCmd {
247
    const vshCmdDef *def;       /* command definition */
248 249
    vshCmdOpt *opts;            /* list of command arguments */
    struct __vshCmd *next;      /* next command */
K
Karel Zak 已提交
250 251 252 253 254 255
} __vshCmd;

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

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

284
typedef struct vshCmdGrp {
E
Eric Blake 已提交
285
    const char *name;    /* name of group, or NULL for list end */
286 287 288
    const char *keyword; /* help keyword */
    const vshCmdDef *commands;
} vshCmdGrp;
289

290
static const vshCmdGrp cmdGroups[];
K
Karel Zak 已提交
291

292 293
static void vshError(vshControl *ctl, const char *format, ...)
    ATTRIBUTE_FMT_PRINTF(2, 3);
E
Eric Blake 已提交
294 295
static bool vshInit(vshControl *ctl);
static bool vshDeinit(vshControl *ctl);
296
static void vshUsage(void);
297
static void vshOpenLogFile(vshControl *ctl);
298 299
static void vshOutputLogFile(vshControl *ctl, int log_level, const char *format, va_list ap)
    ATTRIBUTE_FMT_PRINTF(3, 0);
300
static void vshCloseLogFile(vshControl *ctl);
K
Karel Zak 已提交
301

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

304
static const char *vshCmddefGetInfo(const vshCmdDef *cmd, const char *info);
305
static const vshCmdDef *vshCmddefSearch(const char *cmdname);
E
Eric Blake 已提交
306
static bool vshCmddefHelp(vshControl *ctl, const char *name);
307
static const vshCmdGrp *vshCmdGrpSearch(const char *grpname);
E
Eric Blake 已提交
308
static bool vshCmdGrpHelp(vshControl *ctl, const char *name);
K
Karel Zak 已提交
309

E
Eric Blake 已提交
310 311 312
static int vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
    ATTRIBUTE_RETURN_CHECK;
313 314
static int vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
315 316 317
static int vshCommandOptUInt(const vshCmd *cmd, const char *name,
                             unsigned int *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
318 319 320 321 322 323 324 325 326
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;
327 328 329
static int vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                                  unsigned long long *value)
    ATTRIBUTE_NONNULL(3) ATTRIBUTE_RETURN_CHECK;
E
Eric Blake 已提交
330 331 332 333
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 已提交
334
static bool vshCommandOptBool(const vshCmd *cmd, const char *name);
335 336
static const vshCmdOpt *vshCommandOptArgv(const vshCmd *cmd,
                                          const vshCmdOpt *opt);
337 338 339
static char *vshGetDomainDescription(vshControl *ctl, virDomainPtr dom,
                                     bool title, unsigned int flags)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_RETURN_CHECK;
K
Karel Zak 已提交
340

341 342 343
#define VSH_BYID     (1 << 1)
#define VSH_BYUUID   (1 << 2)
#define VSH_BYNAME   (1 << 3)
344
#define VSH_BYMAC    (1 << 4)
K
Karel Zak 已提交
345

346
static virDomainPtr vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
347
                                          const char **name, int flag);
K
Karel Zak 已提交
348 349

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

353
static void vshPrintExtra(vshControl *ctl, const char *format, ...)
354
    ATTRIBUTE_FMT_PRINTF(2, 3);
355
static void vshDebug(vshControl *ctl, int level, const char *format, ...)
356
    ATTRIBUTE_FMT_PRINTF(3, 4);
K
Karel Zak 已提交
357 358

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

361
static int vshDomainState(vshControl *ctl, virDomainPtr dom, int *reason);
K
Karel Zak 已提交
362
static const char *vshDomainStateToString(int state);
363
static const char *vshDomainStateReasonToString(int state, int reason);
364
static const char *vshDomainControlStateToString(int state);
365
static const char *vshDomainVcpuStateToString(int state);
E
Eric Blake 已提交
366
static bool vshConnectionUsability(vshControl *ctl, virConnectPtr conn);
367 368 369
static virTypedParameterPtr vshFindTypedParamByName(const char *name,
                                                    virTypedParameterPtr list,
                                                    int count);
370 371
static char *vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
    ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2);
K
Karel Zak 已提交
372

E
Eric Blake 已提交
373 374 375
static char *editWriteToTempFile(vshControl *ctl, const char *doc);
static int   editFile(vshControl *ctl, const char *filename);
static char *editReadBackFile(vshControl *ctl, const char *filename);
376

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
/* 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);

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

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

406
static char *_vshStrdup(vshControl *ctl, const char *s, const char *filename, int line);
407 408
#define vshStrdup(_ctl, _s)    _vshStrdup(_ctl, _s, __FILE__, __LINE__)

409 410
static int parseRateStr(const char *rateStr, virNetDevBandwidthRatePtr rate);

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

E
Eric Blake 已提交
416
    if (VIR_ALLOC_N(x, size) == 0)
E
Eric Blake 已提交
417 418 419 420 421 422 423 424 425
        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 已提交
426
    char *x;
E
Eric Blake 已提交
427

E
Eric Blake 已提交
428 429
    if (!xalloc_oversized(nmemb, size) &&
        VIR_ALLOC_N(x, nmemb * size) == 0)
E
Eric Blake 已提交
430 431 432 433 434 435 436 437 438 439 440 441
        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)
442
        return NULL;
E
Eric Blake 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
    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
459

460 461 462 463 464
static int
vshNameSorter(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;
465

466 467
    /* User visible sort, so we want locale-specific case comparison. */
    return strcasecmp(*sa, *sb);
468 469
}

470 471 472 473 474 475 476
static double
prettyCapacity(unsigned long long val,
               const char **unit) {
    if (val < 1024) {
        *unit = "";
        return (double)val;
    } else if (val < (1024.0l * 1024.0l)) {
477
        *unit = "KiB";
478 479
        return (((double)val / 1024.0l));
    } else if (val < (1024.0l * 1024.0l * 1024.0l)) {
480
        *unit = "MiB";
481
        return (double)val / (1024.0l * 1024.0l);
482
    } else if (val < (1024.0l * 1024.0l * 1024.0l * 1024.0l)) {
483
        *unit = "GiB";
484
        return (double)val / (1024.0l * 1024.0l * 1024.0l);
485
    } else {
486
        *unit = "TiB";
487
        return (double)val / (1024.0l * 1024.0l * 1024.0l * 1024.0l);
488 489 490 491
    }
}


J
John Levon 已提交
492 493 494 495 496 497 498 499 500 501 502 503 504 505
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);
}

506 507 508 509 510 511 512 513 514 515
/*
 * Reset libvirt error on graceful fallback paths
 */
static void
vshResetLibvirtError(void)
{
    virFreeError(last_error);
    last_error = NULL;
}

J
John Levon 已提交
516 517 518 519 520 521 522 523 524 525 526
/*
 * 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)
{
527 528 529 530 531 532 533 534
    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)
535
            goto out;
536
    }
J
John Levon 已提交
537 538

    if (last_error->code == VIR_ERR_OK) {
539
        vshError(ctl, "%s", _("unknown error"));
J
John Levon 已提交
540 541 542
        goto out;
    }

543
    vshError(ctl, "%s", last_error->message);
J
John Levon 已提交
544 545

out:
546
    vshResetLibvirtError();
J
John Levon 已提交
547 548
}

549 550 551 552 553 554 555 556 557
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;
}

558 559 560 561 562
/*
 * Detection of disconnections and automatic reconnection support
 */
static int disconnected = 0; /* we may have been disconnected */

563 564 565 566 567
/* Gnulib doesn't guarantee SA_SIGINFO support.  */
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

568 569 570 571 572 573
/*
 * 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
 */
574 575
static void vshCatchDisconnect(int sig, siginfo_t *siginfo,
                               void *context ATTRIBUTE_UNUSED) {
E
Eric Blake 已提交
576
    if (sig == SIGPIPE ||
577
        (SA_SIGINFO && siginfo->si_signo == SIGPIPE))
578 579 580 581 582 583 584 585 586
        disconnected++;
}

/*
 * vshSetupSignals:
 *
 * Catch SIGPIPE signals which may arise when disconnection
 * from libvirtd occurs
 */
L
Laine Stump 已提交
587
static void
588 589 590 591 592 593 594 595 596 597 598 599 600
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 已提交
601
 * Reconnect after a disconnect from libvirtd
602 603
 *
 */
L
Laine Stump 已提交
604
static void
605 606 607 608 609 610
vshReconnect(vshControl *ctl)
{
    bool connected = false;

    if (ctl->conn != NULL) {
        connected = true;
611
        virConnectClose(ctl->conn);
612
    }
613 614 615 616 617 618

    ctl->conn = virConnectOpenAuth(ctl->name,
                                   virConnectAuthPtrDefault,
                                   ctl->readonly ? VIR_CONNECT_RO : 0);
    if (!ctl->conn)
        vshError(ctl, "%s", _("Failed to reconnect to the hypervisor"));
619
    else if (connected)
620 621
        vshError(ctl, "%s", _("Reconnected to the hypervisor"));
    disconnected = 0;
622
    ctl->useGetInfo = false;
623
    ctl->useSnapshotOld = false;
624
}
625

626
#ifndef WIN32
627 628 629 630 631 632 633 634 635 636 637 638 639
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);
}

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
/**
 * 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 == '?') {
674 675 676 677 678 679 680
            vshPrintRaw(ctl,
                        "",
                        _("y - yes, start editor again"),
                        _("n - no, throw away my changes"),
                        _("f - force, try to redefine again"),
                        _("? - print this help"),
                        NULL);
681 682 683 684 685 686 687 688 689 690
            continue;
        } else if (c == 'y' || c == 'n' || c == 'f') {
            break;
        }
    }

    tcsetattr(STDIN_FILENO, TCSAFLUSH, &ttyattr);

    vshPrint(ctl, "\r\n");
    return c;
691 692 693 694 695
}
#else /* WIN32 */
static int
vshAskReedit(vshControl *ctl, const char *msg ATTRIBUTE_UNUSED)
{
696 697 698 699
    vshDebug(ctl, VSH_ERR_WARNING, "%s", _("This function is not "
                                           "supported on WIN32 platform"));
    return 0;
}
700
#endif /* WIN32 */
701

702 703 704 705 706 707 708 709
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 已提交
710 711 712 713 714 715
/* ---------------
 * Commands
 * ---------------
 */

/*
716
 * "help" command
K
Karel Zak 已提交
717
 */
718
static const vshCmdInfo info_help[] = {
719
    {"help", N_("print help")},
720 721
    {"desc", N_("Prints global help, command specific help, or help for a\n"
                "    group of related commands")},
722

723
    {NULL, NULL}
K
Karel Zak 已提交
724 725
};

726
static const vshCmdOptDef opts_help[] = {
727
    {"command", VSH_OT_DATA, 0, N_("Prints global help, command specific help, or help for a group of related commands")},
728
    {NULL, 0, 0, NULL}
K
Karel Zak 已提交
729 730
};

E
Eric Blake 已提交
731
static bool
732
cmdHelp(vshControl *ctl, const vshCmd *cmd)
733
 {
734
    const char *name = NULL;
735

736
    if (vshCommandOptString(cmd, "command", &name) <= 0) {
737
        const vshCmdGrp *grp;
738
        const vshCmdDef *def;
739

740 741 742 743 744 745
        vshPrint(ctl, "%s", _("Grouped commands:\n\n"));

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

746 747 748
            for (def = grp->commands; def->name; def++) {
                if (def->flags & VSH_CMD_FLAG_ALIAS)
                    continue;
749 750
                vshPrint(ctl, "    %-30s %s\n", def->name,
                         _(vshCmddefGetInfo(def, "help")));
751
            }
752 753 754 755

            vshPrint(ctl, "\n");
        }

E
Eric Blake 已提交
756
        return true;
757
    }
758

E
Eric Blake 已提交
759
    if (vshCmddefSearch(name)) {
760
        return vshCmddefHelp(ctl, name);
E
Eric Blake 已提交
761
    } else if (vshCmdGrpSearch(name)) {
762 763 764
        return vshCmdGrpHelp(ctl, name);
    } else {
        vshError(ctl, _("command or command group '%s' doesn't exist"), name);
E
Eric Blake 已提交
765
        return false;
K
Karel Zak 已提交
766 767 768
    }
}

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
/* 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)
784
{
785 786 787 788
    int i;
    int nextlastdev = -1;
    int ret = -1;
    const char *dev = (lookup)(devid, false, opaque);
789

790
    if (virBufferError(indent))
791 792
        goto cleanup;

793 794 795 796 797 798 799 800 801 802
    /* 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;
803 804
    }

805 806 807
    /* Determine the index of the last child device */
    for (i = 0 ; i < num_devices ; i++) {
        const char *parent = (lookup)(i, true, opaque);
808

809 810 811
        if (parent && STREQ(parent, dev))
            nextlastdev = i;
    }
812

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

817 818 819 820
    /* Finally print all children */
    virBufferAddLit(indent, "  ");
    for (i = 0 ; i < num_devices ; i++) {
        const char *parent = (lookup)(i, true, opaque);
821

822 823 824 825 826
        if (parent && STREQ(parent, dev) &&
            vshTreePrintInternal(ctl, lookup, opaque,
                                 num_devices, i, nextlastdev,
                                 false, indent) < 0)
            goto cleanup;
827
    }
828
    virBufferTrim(indent, "  ", -1);
829

830 831 832 833
    /* 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));
834

835 836 837
    if (!root)
        virBufferTrim(indent, NULL, 2);
    ret = 0;
838 839 840 841
cleanup:
    return ret;
}

842 843 844
static int
vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
             int num_devices, int devid)
845
{
846 847
    int ret;
    virBuffer indent = VIR_BUFFER_INITIALIZER;
848

849 850 851 852 853
    ret = vshTreePrintInternal(ctl, lookup, opaque, num_devices,
                               devid, devid, true, &indent);
    if (ret < 0)
        vshError(ctl, "%s", _("Failed to complete tree listing"));
    virBufferFreeAndReset(&indent);
854
    return ret;
855
}
856

857 858
/* Common code for the edit / net-edit / pool-edit functions which follow. */
static char *
859
editWriteToTempFile(vshControl *ctl, const char *doc)
860 861 862 863 864 865 866
{
    char *ret;
    const char *tmpdir;
    int fd;

    tmpdir = getenv ("TMPDIR");
    if (!tmpdir) tmpdir = "/tmp";
867 868 869 870
    if (virAsprintf(&ret, "%s/virshXXXXXX.xml", tmpdir) < 0) {
        vshError(ctl, "%s", _("out of memory"));
        return NULL;
    }
871
    fd = mkstemps(ret, 4);
872
    if (fd == -1) {
873
        vshError(ctl, _("mkstemps: failed to create temporary file: %s"),
874
                 strerror(errno));
875
        VIR_FREE(ret);
876 877 878
        return NULL;
    }

879
    if (safewrite(fd, doc, strlen(doc)) == -1) {
880 881
        vshError(ctl, _("write: %s: failed to write to temporary file: %s"),
                 ret, strerror(errno));
S
Stefan Berger 已提交
882
        VIR_FORCE_CLOSE(fd);
883
        unlink(ret);
884
        VIR_FREE(ret);
885 886
        return NULL;
    }
S
Stefan Berger 已提交
887
    if (VIR_CLOSE(fd) < 0) {
888 889
        vshError(ctl, _("close: %s: failed to write or close temporary file: %s"),
                 ret, strerror(errno));
890
        unlink(ret);
891
        VIR_FREE(ret);
892 893 894 895 896 897 898 899 900 901 902 903
        return NULL;
    }

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

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

static int
904
editFile(vshControl *ctl, const char *filename)
905 906
{
    const char *editor;
E
Eric Blake 已提交
907 908 909 910
    virCommandPtr cmd;
    int ret = -1;
    int outfd = STDOUT_FILENO;
    int errfd = STDERR_FILENO;
911

912
    editor = getenv("VISUAL");
E
Eric Blake 已提交
913
    if (!editor)
914
        editor = getenv("EDITOR");
E
Eric Blake 已提交
915 916
    if (!editor)
        editor = "vi"; /* could be cruel & default to ed(1) here */
917

918 919 920 921 922
    /* 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 已提交
923 924
     * is why sudo scrubs it by default).  Conversely, if the editor
     * is safe, we can run it directly rather than wasting a shell.
925
     */
926 927
    if (strspn(editor, ACCEPTED_CHARS) != strlen(editor)) {
        if (strspn(filename, ACCEPTED_CHARS) != strlen(filename)) {
E
Eric Blake 已提交
928 929 930 931 932 933 934 935 936 937
            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);
938 939
    }

E
Eric Blake 已提交
940 941 942 943 944 945 946
    virCommandSetInputFD(cmd, STDIN_FILENO);
    virCommandSetOutputFD(cmd, &outfd);
    virCommandSetErrorFD(cmd, &errfd);
    if (virCommandRunAsync(cmd, NULL) < 0 ||
        virCommandWait(cmd, NULL) < 0) {
        virshReportError(ctl);
        goto cleanup;
947
    }
E
Eric Blake 已提交
948
    ret = 0;
949

E
Eric Blake 已提交
950 951 952
cleanup:
    virCommandFree(cmd);
    return ret;
953 954 955
}

static char *
956
editReadBackFile(vshControl *ctl, const char *filename)
957 958 959
{
    char *ret;

E
Eric Blake 已提交
960
    if (virFileReadAll(filename, VIRSH_MAX_XML_FILE, &ret) == -1) {
961
        vshError(ctl,
962
                 _("%s: failed to read temporary file: %s"),
963
                 filename, strerror(errno));
964 965 966 967 968
        return NULL;
    }
    return ret;
}

969

P
Paolo Bonzini 已提交
970 971 972 973
/*
 * "cd" command
 */
static const vshCmdInfo info_cd[] = {
974 975
    {"help", N_("change the current directory")},
    {"desc", N_("Change the current directory.")},
P
Paolo Bonzini 已提交
976 977 978 979
    {NULL, NULL}
};

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

E
Eric Blake 已提交
984
static bool
985
cmdCd(vshControl *ctl, const vshCmd *cmd)
P
Paolo Bonzini 已提交
986
{
987
    const char *dir = NULL;
988
    char *dir_malloced = NULL;
E
Eric Blake 已提交
989
    bool ret = true;
P
Paolo Bonzini 已提交
990 991

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

996
    if (vshCommandOptString(cmd, "dir", &dir) <= 0) {
997
        dir = dir_malloced = virGetUserDirectory();
P
Paolo Bonzini 已提交
998 999 1000 1001
    }
    if (!dir)
        dir = "/";

P
Phil Petty 已提交
1002
    if (chdir(dir) == -1) {
1003
        vshError(ctl, _("cd: %s: %s"), strerror(errno), dir);
E
Eric Blake 已提交
1004
        ret = false;
P
Paolo Bonzini 已提交
1005 1006
    }

1007
    VIR_FREE(dir_malloced);
P
Phil Petty 已提交
1008
    return ret;
P
Paolo Bonzini 已提交
1009 1010 1011 1012 1013 1014
}

/*
 * "pwd" command
 */
static const vshCmdInfo info_pwd[] = {
1015 1016
    {"help", N_("print the current directory")},
    {"desc", N_("Print the current directory.")},
P
Paolo Bonzini 已提交
1017 1018 1019
    {NULL, NULL}
};

E
Eric Blake 已提交
1020
static bool
P
Paolo Bonzini 已提交
1021 1022 1023
cmdPwd(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    char *cwd;
1024
    bool ret = true;
P
Paolo Bonzini 已提交
1025

1026 1027
    cwd = getcwd(NULL, 0);
    if (!cwd) {
1028 1029
        vshError(ctl, _("pwd: cannot get current directory: %s"),
                 strerror(errno));
1030 1031
        ret = false;
    } else {
1032
        vshPrint(ctl, _("%s\n"), cwd);
1033 1034
        VIR_FREE(cwd);
    }
P
Paolo Bonzini 已提交
1035

1036
    return ret;
P
Paolo Bonzini 已提交
1037 1038
}

E
Eric Blake 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
/*
 * "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 已提交
1051
    {"str", VSH_OT_ALIAS, 0, "string"},
1052
    {"string", VSH_OT_ARGV, 0, N_("arguments to echo")},
E
Eric Blake 已提交
1053 1054 1055 1056 1057 1058
    {NULL, 0, 0, NULL}
};

/* Exists mainly for debugging virsh, but also handy for adding back
 * quotes for later evaluation.
 */
E
Eric Blake 已提交
1059
static bool
1060
cmdEcho(vshControl *ctl, const vshCmd *cmd)
E
Eric Blake 已提交
1061 1062 1063 1064
{
    bool shell = false;
    bool xml = false;
    int count = 0;
1065
    const vshCmdOpt *opt = NULL;
E
Eric Blake 已提交
1066 1067 1068 1069 1070 1071 1072 1073
    char *arg;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

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

1074
    while ((opt = vshCommandOptArgv(cmd, opt))) {
1075 1076
        char *str;
        virBuffer xmlbuf = VIR_BUFFER_INITIALIZER;
E
Eric Blake 已提交
1077

1078
        arg = opt->data;
1079

E
Eric Blake 已提交
1080 1081
        if (count)
            virBufferAddChar(&buf, ' ');
1082

E
Eric Blake 已提交
1083
        if (xml) {
1084 1085 1086 1087
            virBufferEscapeString(&xmlbuf, "%s", arg);
            if (virBufferError(&buf)) {
                vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
                return false;
E
Eric Blake 已提交
1088
            }
1089 1090 1091
            str = virBufferContentAndReset(&xmlbuf);
        } else {
            str = vshStrdup(ctl, arg);
E
Eric Blake 已提交
1092
        }
1093 1094 1095 1096 1097

        if (shell)
            virBufferEscapeShell(&buf, str);
        else
            virBufferAdd(&buf, str, -1);
E
Eric Blake 已提交
1098
        count++;
1099
        VIR_FREE(str);
E
Eric Blake 已提交
1100 1101 1102 1103
    }

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
E
Eric Blake 已提交
1104
        return false;
E
Eric Blake 已提交
1105 1106 1107 1108 1109
    }
    arg = virBufferContentAndReset(&buf);
    if (arg)
        vshPrint(ctl, "%s", arg);
    VIR_FREE(arg);
E
Eric Blake 已提交
1110
    return true;
E
Eric Blake 已提交
1111 1112
}

K
Karel Zak 已提交
1113 1114 1115
/*
 * "quit" command
 */
1116
static const vshCmdInfo info_quit[] = {
1117
    {"help", N_("quit this interactive terminal")},
1118
    {"desc", ""},
1119
    {NULL, NULL}
K
Karel Zak 已提交
1120 1121
};

E
Eric Blake 已提交
1122
static bool
1123
cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
1124
{
E
Eric Blake 已提交
1125 1126
    ctl->imode = false;
    return true;
K
Karel Zak 已提交
1127 1128
}

1129 1130 1131 1132 1133 1134 1135 1136
/* ---------------
 * Utils for work with command definition
 * ---------------
 */
static const char *
vshCmddefGetInfo(const vshCmdDef * cmd, const char *name)
{
    const vshCmdInfo *info;
1137

1138 1139 1140 1141 1142 1143
    for (info = cmd->info; info && info->name; info++) {
        if (STREQ(info->name, name))
            return info->data;
    }
    return NULL;
}
1144

1145 1146 1147 1148 1149 1150 1151
/* 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;
1152

1153 1154
    *opts_need_arg = 0;
    *opts_required = 0;
1155

1156 1157
    if (!cmd->opts)
        return 0;
1158

1159 1160
    for (i = 0; cmd->opts[i].name; i++) {
        const vshCmdOptDef *opt = &cmd->opts[i];
1161 1162 1163 1164

        if (i > 31)
            return -1; /* too many options */
        if (opt->type == VSH_OT_BOOL) {
E
Eric Blake 已提交
1165
            if (opt->flags & VSH_OFLAG_REQ)
1166 1167 1168
                return -1; /* bool options can't be mandatory */
            continue;
        }
E
Eric Blake 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
        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 已提交
1181 1182
        if (opt->flags & VSH_OFLAG_REQ_OPT) {
            if (opt->flags & VSH_OFLAG_REQ)
L
Lai Jiangshan 已提交
1183 1184 1185 1186
                *opts_required |= 1 << i;
            continue;
        }

1187
        *opts_need_arg |= 1 << i;
E
Eric Blake 已提交
1188
        if (opt->flags & VSH_OFLAG_REQ) {
1189 1190 1191 1192 1193 1194
            if (optional)
                return -1; /* mandatory options must be listed first */
            *opts_required |= 1 << i;
        } else {
            optional = true;
        }
1195 1196 1197

        if (opt->type == VSH_OT_ARGV && cmd->opts[i + 1].name)
            return -1; /* argv option must be listed last */
1198 1199 1200 1201
    }
    return 0;
}

1202
static const vshCmdOptDef *
1203
vshCmddefGetOption(vshControl *ctl, const vshCmdDef *cmd, const char *name,
1204
                   uint32_t *opts_seen, int *opt_index)
1205
{
1206 1207 1208 1209
    int i;

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

1211
        if (STREQ(opt->name, name)) {
E
Eric Blake 已提交
1212 1213 1214 1215
            if (opt->type == VSH_OT_ALIAS) {
                name = opt->help;
                continue;
            }
1216
            if ((*opts_seen & (1 << i)) && opt->type != VSH_OT_ARGV) {
1217 1218 1219
                vshError(ctl, _("option --%s already seen"), name);
                return NULL;
            }
1220 1221
            *opts_seen |= 1 << i;
            *opt_index = i;
K
Karel Zak 已提交
1222
            return opt;
1223 1224 1225 1226 1227
        }
    }

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

1231
static const vshCmdOptDef *
1232 1233
vshCmddefGetData(const vshCmdDef *cmd, uint32_t *opts_need_arg,
                 uint32_t *opts_seen)
1234
{
1235
    int i;
1236
    const vshCmdOptDef *opt;
K
Karel Zak 已提交
1237

1238 1239 1240 1241
    if (!*opts_need_arg)
        return NULL;

    /* Grab least-significant set bit */
E
Eric Blake 已提交
1242
    i = ffs(*opts_need_arg) - 1;
1243
    opt = &cmd->opts[i];
1244
    if (opt->type != VSH_OT_ARGV)
1245
        *opts_need_arg &= ~(1 << i);
1246
    *opts_seen |= 1 << i;
1247
    return opt;
K
Karel Zak 已提交
1248 1249
}

1250 1251 1252
/*
 * Checks for required options
 */
1253
static int
1254 1255
vshCommandCheckOpts(vshControl *ctl, const vshCmd *cmd, uint32_t opts_required,
                    uint32_t opts_seen)
1256
{
1257
    const vshCmdDef *def = cmd->def;
1258 1259 1260 1261 1262 1263 1264 1265 1266
    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];
1267

1268
            vshError(ctl,
1269
                     opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV ?
1270 1271 1272
                     _("command '%s' requires <%s> option") :
                     _("command '%s' requires --%s option"),
                     def->name, opt->name);
1273 1274
        }
    }
1275
    return -1;
1276 1277
}

1278
static const vshCmdDef *
1279 1280
vshCmddefSearch(const char *cmdname)
{
1281
    const vshCmdGrp *g;
1282
    const vshCmdDef *c;
1283

1284 1285
    for (g = cmdGroups; g->name; g++) {
        for (c = g->commands; c->name; c++) {
1286
            if (STREQ(c->name, cmdname))
1287 1288 1289 1290
                return c;
        }
    }

K
Karel Zak 已提交
1291 1292 1293
    return NULL;
}

1294 1295 1296 1297 1298 1299
static const vshCmdGrp *
vshCmdGrpSearch(const char *grpname)
{
    const vshCmdGrp *g;

    for (g = cmdGroups; g->name; g++) {
1300
        if (STREQ(g->name, grpname) || STREQ(g->keyword, grpname))
1301 1302 1303 1304 1305 1306
            return g;
    }

    return NULL;
}

E
Eric Blake 已提交
1307
static bool
1308 1309 1310 1311 1312 1313 1314
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 已提交
1315
        return false;
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    } 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 已提交
1326
    return true;
1327 1328
}

E
Eric Blake 已提交
1329
static bool
1330
vshCmddefHelp(vshControl *ctl, const char *cmdname)
1331
{
1332
    const vshCmdDef *def = vshCmddefSearch(cmdname);
1333

K
Karel Zak 已提交
1334
    if (!def) {
1335
        vshError(ctl, _("command '%s' doesn't exist"), cmdname);
E
Eric Blake 已提交
1336
        return false;
1337
    } else {
E
Eric Blake 已提交
1338 1339
        /* Don't translate desc if it is "".  */
        const char *desc = vshCmddefGetInfo(def, "desc");
E
Eric Blake 已提交
1340
        const char *help = _(vshCmddefGetInfo(def, "help"));
1341
        char buf[256];
1342 1343
        uint32_t opts_need_arg;
        uint32_t opts_required;
1344
        bool shortopt = false; /* true if 'arg' works instead of '--opt arg' */
1345 1346 1347 1348

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

1352
        fputs(_("  NAME\n"), stdout);
1353 1354
        fprintf(stdout, "    %s - %s\n", def->name, help);

1355 1356 1357 1358 1359
        fputs(_("\n  SYNOPSIS\n"), stdout);
        fprintf(stdout, "    %s", def->name);
        if (def->opts) {
            const vshCmdOptDef *opt;
            for (opt = def->opts; opt->name; opt++) {
1360
                const char *fmt = "%s";
1361 1362
                switch (opt->type) {
                case VSH_OT_BOOL:
1363
                    fmt = "[--%s]";
1364 1365
                    break;
                case VSH_OT_INT:
E
Eric Blake 已提交
1366
                    /* xgettext:c-format */
E
Eric Blake 已提交
1367
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>"
1368
                           : _("[--%s <number>]"));
1369 1370
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1371 1372
                    break;
                case VSH_OT_STRING:
E
Eric Blake 已提交
1373 1374
                    /* xgettext:c-format */
                    fmt = _("[--%s <string>]");
1375 1376
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1377 1378
                    break;
                case VSH_OT_DATA:
E
Eric Blake 已提交
1379
                    fmt = ((opt->flags & VSH_OFLAG_REQ) ? "<%s>" : "[<%s>]");
1380 1381
                    if (!(opt->flags & VSH_OFLAG_REQ_OPT))
                        shortopt = true;
1382 1383 1384
                    break;
                case VSH_OT_ARGV:
                    /* xgettext:c-format */
1385 1386 1387 1388 1389 1390 1391 1392
                    if (shortopt) {
                        fmt = (opt->flags & VSH_OFLAG_REQ)
                            ? _("{[--%s] <string>}...")
                            : _("[[--%s] <string>]...");
                    } else {
                        fmt = (opt->flags & VSH_OFLAG_REQ) ? _("<%s>...")
                            : _("[<%s>]...");
                    }
1393
                    break;
E
Eric Blake 已提交
1394 1395 1396
                case VSH_OT_ALIAS:
                    /* aliases are intentionally undocumented */
                    continue;
1397
                default:
1398
                    assert(0);
1399
                }
1400
                fputc(' ', stdout);
E
Eric Blake 已提交
1401
                fprintf(stdout, fmt, opt->name);
1402
            }
K
Karel Zak 已提交
1403
        }
1404 1405 1406
        fputc('\n', stdout);

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

K
Karel Zak 已提交
1412
        if (def->opts) {
1413
            const vshCmdOptDef *opt;
1414
            fputs(_("\n  OPTIONS\n"), stdout);
1415
            for (opt = def->opts; opt->name; opt++) {
1416 1417
                switch (opt->type) {
                case VSH_OT_BOOL:
K
Karel Zak 已提交
1418
                    snprintf(buf, sizeof(buf), "--%s", opt->name);
1419 1420
                    break;
                case VSH_OT_INT:
1421
                    snprintf(buf, sizeof(buf),
E
Eric Blake 已提交
1422
                             (opt->flags & VSH_OFLAG_REQ) ? _("[--%s] <number>")
1423
                             : _("--%s <number>"), opt->name);
1424 1425
                    break;
                case VSH_OT_STRING:
1426
                    /* OT_STRING should never be VSH_OFLAG_REQ */
1427
                    snprintf(buf, sizeof(buf), _("--%s <string>"), opt->name);
1428 1429
                    break;
                case VSH_OT_DATA:
1430 1431
                    snprintf(buf, sizeof(buf), _("[--%s] <string>"),
                             opt->name);
1432 1433
                    break;
                case VSH_OT_ARGV:
1434 1435 1436
                    snprintf(buf, sizeof(buf),
                             shortopt ? _("[--%s] <string>") : _("<%s>"),
                             opt->name);
1437
                    break;
E
Eric Blake 已提交
1438 1439
                case VSH_OT_ALIAS:
                    continue;
1440 1441 1442
                default:
                    assert(0);
                }
1443

E
Eric Blake 已提交
1444
                fprintf(stdout, "    %-15s  %s\n", buf, _(opt->help));
1445
            }
K
Karel Zak 已提交
1446 1447 1448
        }
        fputc('\n', stdout);
    }
E
Eric Blake 已提交
1449
    return true;
K
Karel Zak 已提交
1450 1451 1452 1453 1454 1455
}

/* ---------------
 * Utils for work with runtime commands data
 * ---------------
 */
1456 1457 1458
static void
vshCommandOptFree(vshCmdOpt * arg)
{
K
Karel Zak 已提交
1459 1460
    vshCmdOpt *a = arg;

1461
    while (a) {
K
Karel Zak 已提交
1462
        vshCmdOpt *tmp = a;
1463

K
Karel Zak 已提交
1464 1465
        a = a->next;

1466 1467
        VIR_FREE(tmp->data);
        VIR_FREE(tmp);
K
Karel Zak 已提交
1468 1469 1470 1471
    }
}

static void
1472
vshCommandFree(vshCmd *cmd)
1473
{
K
Karel Zak 已提交
1474 1475
    vshCmd *c = cmd;

1476
    while (c) {
K
Karel Zak 已提交
1477
        vshCmd *tmp = c;
1478

K
Karel Zak 已提交
1479 1480 1481 1482
        c = c->next;

        if (tmp->opts)
            vshCommandOptFree(tmp->opts);
1483
        VIR_FREE(tmp);
K
Karel Zak 已提交
1484 1485 1486
    }
}

E
Eric Blake 已提交
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
/**
 * 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 已提交
1498
 */
E
Eric Blake 已提交
1499 1500
static int
vshCommandOpt(const vshCmd *cmd, const char *name, vshCmdOpt **opt)
1501
{
E
Eric Blake 已提交
1502 1503
    vshCmdOpt *candidate = cmd->opts;
    const vshCmdOptDef *valid = cmd->def->opts;
1504

E
Eric Blake 已提交
1505 1506 1507 1508 1509 1510 1511
    /* 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 已提交
1512
    }
E
Eric Blake 已提交
1513 1514 1515 1516 1517 1518 1519

    /* Option not present, see if command requires it.  */
    *opt = NULL;
    while (valid) {
        if (!valid->name)
            break;
        if (STREQ(name, valid->name))
E
Eric Blake 已提交
1520
            return (valid->flags & VSH_OFLAG_REQ) == 0 ? 0 : -1;
E
Eric Blake 已提交
1521 1522 1523 1524
        valid++;
    }
    /* If we got here, the name is unknown.  */
    return -2;
K
Karel Zak 已提交
1525 1526
}

E
Eric Blake 已提交
1527 1528
/**
 * vshCommandOptInt:
1529 1530 1531 1532 1533 1534 1535
 * @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 已提交
1536
 * 0 if option not found and not required (@value untouched)
1537
 * <0 in all other cases (@value untouched)
K
Karel Zak 已提交
1538 1539
 */
static int
1540
vshCommandOptInt(const vshCmd *cmd, const char *name, int *value)
1541
{
E
Eric Blake 已提交
1542 1543
    vshCmdOpt *arg;
    int ret;
1544

E
Eric Blake 已提交
1545 1546 1547 1548 1549 1550 1551
    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;
1552
    }
E
Eric Blake 已提交
1553

E
Eric Blake 已提交
1554 1555 1556
    if (virStrToLong_i(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
K
Karel Zak 已提交
1557 1558
}

1559

E
Eric Blake 已提交
1560 1561 1562 1563 1564 1565
/**
 * vshCommandOptUInt:
 * @cmd command reference
 * @name option name
 * @value result
 *
1566 1567 1568 1569 1570 1571
 * Convert option to unsigned int
 * See vshCommandOptInt()
 */
static int
vshCommandOptUInt(const vshCmd *cmd, const char *name, unsigned int *value)
{
E
Eric Blake 已提交
1572 1573
    vshCmdOpt *arg;
    int ret;
1574

E
Eric Blake 已提交
1575 1576 1577 1578 1579 1580 1581
    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;
1582
    }
E
Eric Blake 已提交
1583

E
Eric Blake 已提交
1584 1585 1586
    if (virStrToLong_ui(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1587 1588 1589
}


1590
/*
E
Eric Blake 已提交
1591 1592 1593 1594 1595
 * vshCommandOptUL:
 * @cmd command reference
 * @name option name
 * @value result
 *
1596 1597 1598 1599 1600
 * Convert option to unsigned long
 * See vshCommandOptInt()
 */
static int
vshCommandOptUL(const vshCmd *cmd, const char *name, unsigned long *value)
1601
{
E
Eric Blake 已提交
1602 1603
    vshCmdOpt *arg;
    int ret;
1604

E
Eric Blake 已提交
1605 1606 1607 1608 1609 1610 1611
    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;
1612
    }
E
Eric Blake 已提交
1613

E
Eric Blake 已提交
1614 1615 1616
    if (virStrToLong_ul(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1617 1618
}

E
Eric Blake 已提交
1619 1620 1621 1622 1623 1624
/**
 * vshCommandOptString:
 * @cmd command reference
 * @name option name
 * @value result
 *
K
Karel Zak 已提交
1625
 * Returns option as STRING
E
Eric Blake 已提交
1626 1627 1628 1629
 * 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 已提交
1630
 */
1631 1632
static int
vshCommandOptString(const vshCmd *cmd, const char *name, const char **value)
1633
{
E
Eric Blake 已提交
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
    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;
1644
    }
1645

E
Eric Blake 已提交
1646
    if (!*arg->data && !(arg->def->flags & VSH_OFLAG_EMPTY_OK)) {
E
Eric Blake 已提交
1647 1648 1649 1650
        return -1;
    }
    *value = arg->data;
    return 1;
K
Karel Zak 已提交
1651 1652
}

E
Eric Blake 已提交
1653 1654 1655 1656 1657 1658
/**
 * vshCommandOptLongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
1659
 * Returns option as long long
1660
 * See vshCommandOptInt()
1661
 */
1662 1663 1664
static int
vshCommandOptLongLong(const vshCmd *cmd, const char *name,
                      long long *value)
1665
{
E
Eric Blake 已提交
1666 1667
    vshCmdOpt *arg;
    int ret;
1668

E
Eric Blake 已提交
1669 1670 1671 1672 1673 1674 1675
    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;
1676
    }
E
Eric Blake 已提交
1677

E
Eric Blake 已提交
1678 1679 1680
    if (virStrToLong_ll(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1681 1682
}

E
Eric Blake 已提交
1683 1684 1685 1686 1687 1688 1689 1690 1691
/**
 * vshCommandOptULongLong:
 * @cmd command reference
 * @name option name
 * @value result
 *
 * Returns option as long long
 * See vshCommandOptInt()
 */
1692 1693 1694 1695
static int
vshCommandOptULongLong(const vshCmd *cmd, const char *name,
                       unsigned long long *value)
{
E
Eric Blake 已提交
1696 1697
    vshCmdOpt *arg;
    int ret;
1698

E
Eric Blake 已提交
1699 1700 1701 1702 1703 1704 1705
    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;
1706
    }
E
Eric Blake 已提交
1707

E
Eric Blake 已提交
1708 1709 1710
    if (virStrToLong_ull(arg->data, NULL, 10, value) < 0)
        return -1;
    return 1;
1711 1712 1713
}


E
Eric Blake 已提交
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
/**
 * 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 已提交
1744 1745 1746 1747 1748 1749 1750 1751 1752
/**
 * 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 已提交
1753
 */
E
Eric Blake 已提交
1754
static bool
1755
vshCommandOptBool(const vshCmd *cmd, const char *name)
1756
{
E
Eric Blake 已提交
1757 1758 1759
    vshCmdOpt *dummy;

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

E
Eric Blake 已提交
1762 1763 1764 1765 1766
/**
 * vshCommandOptArgv:
 * @cmd command reference
 * @opt starting point for the search
 *
1767 1768
 * Returns the next argv argument after OPT (or the first one if OPT
 * is NULL), or NULL if no more are present.
1769
 *
1770
 * Requires that a VSH_OT_ARGV option be last in the
1771 1772
 * list of supported options in CMD->def->opts.
 */
1773 1774
static const vshCmdOpt *
vshCommandOptArgv(const vshCmd *cmd, const vshCmdOpt *opt)
1775
{
1776
    opt = opt ? opt->next : cmd->opts;
1777 1778

    while (opt) {
E
Eric Blake 已提交
1779
        if (opt->def->type == VSH_OT_ARGV) {
1780
            return opt;
1781 1782 1783 1784 1785 1786
        }
        opt = opt->next;
    }
    return NULL;
}

J
Jim Meyering 已提交
1787 1788 1789 1790
/* Determine whether CMD->opts includes an option with name OPTNAME.
   If not, give a diagnostic and return false.
   If so, return true.  */
static bool
1791
cmd_has_option(vshControl *ctl, const vshCmd *cmd, const char *optname)
J
Jim Meyering 已提交
1792 1793 1794 1795 1796 1797
{
    /* 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) {
1798
        if (STREQ(opt->def->name, optname) && opt->def->type == VSH_OT_DATA) {
J
Jim Meyering 已提交
1799 1800 1801 1802 1803 1804
            found = true;
            break;
        }
    }

    if (!found)
1805
        vshError(ctl, _("internal error: virsh %s: no %s VSH_OT_DATA option"),
J
Jim Meyering 已提交
1806 1807 1808
                 cmd->def->name, optname);
    return found;
}
1809

K
Karel Zak 已提交
1810
static virDomainPtr
J
Jim Meyering 已提交
1811
vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd,
1812
                      const char **name, int flag)
1813
{
K
Karel Zak 已提交
1814
    virDomainPtr dom = NULL;
1815
    const char *n = NULL;
K
Karel Zak 已提交
1816
    int id;
J
Jim Meyering 已提交
1817
    const char *optname = "domain";
1818
    if (!cmd_has_option(ctl, cmd, optname))
J
Jim Meyering 已提交
1819
        return NULL;
1820

1821
    if (vshCommandOptString(cmd, optname, &n) <= 0)
1822 1823
        return NULL;

1824
    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
1825 1826
             cmd->def->name, optname, n);

K
Karel Zak 已提交
1827 1828
    if (name)
        *name = n;
1829

K
Karel Zak 已提交
1830
    /* try it by ID */
1831
    if (flag & VSH_BYID) {
1832
        if (virStrToLong_i(n, NULL, 10, &id) == 0 && id >= 0) {
1833 1834
            vshDebug(ctl, VSH_ERR_DEBUG,
                     "%s: <%s> seems like domain ID\n",
K
Karel Zak 已提交
1835 1836 1837
                     cmd->def->name, optname);
            dom = virDomainLookupByID(ctl->conn, id);
        }
1838
    }
K
Karel Zak 已提交
1839
    /* try it by UUID */
1840
    if (dom==NULL && (flag & VSH_BYUUID) && strlen(n)==VIR_UUID_STRING_BUFLEN-1) {
1841
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain UUID\n",
1842
                 cmd->def->name, optname);
K
Karel Zak 已提交
1843
        dom = virDomainLookupByUUIDString(ctl->conn, n);
K
Karel Zak 已提交
1844
    }
K
Karel Zak 已提交
1845
    /* try it by NAME */
1846
    if (dom==NULL && (flag & VSH_BYNAME)) {
1847
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as domain NAME\n",
1848
                 cmd->def->name, optname);
K
Karel Zak 已提交
1849
        dom = virDomainLookupByName(ctl->conn, n);
1850
    }
K
Karel Zak 已提交
1851

1852
    if (!dom)
1853
        vshError(ctl, _("failed to get domain '%s'"), n);
1854

K
Karel Zak 已提交
1855 1856 1857
    return dom;
}

K
Karel Zak 已提交
1858 1859 1860
/*
 * Executes command(s) and returns return code from last command
 */
E
Eric Blake 已提交
1861
static bool
1862
vshCommandRun(vshControl *ctl, const vshCmd *cmd)
1863
{
E
Eric Blake 已提交
1864
    bool ret = true;
1865 1866

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

1870 1871
        if ((ctl->conn == NULL || disconnected) &&
            !(cmd->def->flags & VSH_CMD_FLAG_NOCONNECT))
1872 1873
            vshReconnect(ctl);

1874
        if (enable_timing)
K
Karel Zak 已提交
1875
            GETTIMEOFDAY(&before);
1876

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

1879
        if (enable_timing)
K
Karel Zak 已提交
1880
            GETTIMEOFDAY(&after);
1881

1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
        /* 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++;

1892
        if (!ret)
J
John Levon 已提交
1893 1894
            virshReportError(ctl);

1895
        if (!ret && disconnected != 0)
1896 1897
            vshReconnect(ctl);

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

1901
        if (enable_timing)
1902
            vshPrint(ctl, _("\n(Time: %.3f ms)\n\n"),
1903 1904
                     DIFF_MSEC(&after, &before));
        else
K
Karel Zak 已提交
1905
            vshPrintExtra(ctl, "\n");
K
Karel Zak 已提交
1906 1907 1908 1909 1910 1911
        cmd = cmd->next;
    }
    return ret;
}

/* ---------------
1912
 * Command parsing
K
Karel Zak 已提交
1913 1914 1915
 * ---------------
 */

1916 1917 1918 1919 1920 1921 1922 1923
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 {
1924
    vshCommandToken(*getNextArg)(vshControl *, struct __vshCommandParser *,
1925
                                  char **);
L
Lai Jiangshan 已提交
1926
    /* vshCommandStringGetArg() */
1927
    char *pos;
L
Lai Jiangshan 已提交
1928 1929 1930
    /* vshCommandArgvGetArg() */
    char **arg_pos;
    char **arg_end;
1931 1932
} vshCommandParser;

E
Eric Blake 已提交
1933
static bool
1934
vshCommandParse(vshControl *ctl, vshCommandParser *parser)
1935
{
K
Karel Zak 已提交
1936 1937 1938
    char *tkdata = NULL;
    vshCmd *clast = NULL;
    vshCmdOpt *first = NULL;
1939

K
Karel Zak 已提交
1940 1941 1942 1943
    if (ctl->cmd) {
        vshCommandFree(ctl->cmd);
        ctl->cmd = NULL;
    }
1944

1945
    while (1) {
K
Karel Zak 已提交
1946
        vshCmdOpt *last = NULL;
1947
        const vshCmdDef *cmd = NULL;
1948
        vshCommandToken tk;
L
Lai Jiangshan 已提交
1949
        bool data_only = false;
1950 1951 1952
        uint32_t opts_need_arg = 0;
        uint32_t opts_required = 0;
        uint32_t opts_seen = 0;
1953

K
Karel Zak 已提交
1954
        first = NULL;
1955

1956
        while (1) {
1957
            const vshCmdOptDef *opt = NULL;
1958

K
Karel Zak 已提交
1959
            tkdata = NULL;
1960
            tk = parser->getNextArg(ctl, parser, &tkdata);
1961 1962

            if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
1963
                goto syntaxError;
H
Hu Tao 已提交
1964 1965
            if (tk != VSH_TK_ARG) {
                VIR_FREE(tkdata);
1966
                break;
H
Hu Tao 已提交
1967
            }
1968 1969

            if (cmd == NULL) {
K
Karel Zak 已提交
1970 1971
                /* first token must be command name */
                if (!(cmd = vshCmddefSearch(tkdata))) {
1972
                    vshError(ctl, _("unknown command: '%s'"), tkdata);
1973
                    goto syntaxError;   /* ... or ignore this command only? */
K
Karel Zak 已提交
1974
                }
1975 1976 1977 1978 1979 1980 1981
                if (vshCmddefOptParse(cmd, &opts_need_arg,
                                      &opts_required) < 0) {
                    vshError(ctl,
                             _("internal error: bad options in command: '%s'"),
                             tkdata);
                    goto syntaxError;
                }
1982
                VIR_FREE(tkdata);
L
Lai Jiangshan 已提交
1983 1984 1985 1986
            } else if (data_only) {
                goto get_data;
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       c_isalnum(tkdata[2])) {
1987
                char *optstr = strchr(tkdata + 2, '=');
1988 1989
                int opt_index;

1990 1991 1992 1993
                if (optstr) {
                    *optstr = '\0'; /* convert the '=' to '\0' */
                    optstr = vshStrdup(ctl, optstr + 1);
                }
1994
                if (!(opt = vshCmddefGetOption(ctl, cmd, tkdata + 2,
1995
                                               &opts_seen, &opt_index))) {
1996
                    VIR_FREE(optstr);
K
Karel Zak 已提交
1997 1998
                    goto syntaxError;
                }
1999
                VIR_FREE(tkdata);
K
Karel Zak 已提交
2000 2001 2002

                if (opt->type != VSH_OT_BOOL) {
                    /* option data */
2003 2004 2005
                    if (optstr)
                        tkdata = optstr;
                    else
2006
                        tk = parser->getNextArg(ctl, parser, &tkdata);
2007
                    if (tk == VSH_TK_ERROR)
K
Karel Zak 已提交
2008
                        goto syntaxError;
2009
                    if (tk != VSH_TK_ARG) {
2010
                        vshError(ctl,
2011
                                 _("expected syntax: --%s <%s>"),
2012 2013
                                 opt->name,
                                 opt->type ==
2014
                                 VSH_OT_INT ? _("number") : _("string"));
K
Karel Zak 已提交
2015 2016
                        goto syntaxError;
                    }
2017 2018
                    if (opt->type != VSH_OT_ARGV)
                        opts_need_arg &= ~(1 << opt_index);
2019 2020 2021 2022 2023 2024 2025 2026
                } else {
                    tkdata = NULL;
                    if (optstr) {
                        vshError(ctl, _("invalid '=' after option --%s"),
                                opt->name);
                        VIR_FREE(optstr);
                        goto syntaxError;
                    }
K
Karel Zak 已提交
2027
                }
L
Lai Jiangshan 已提交
2028 2029 2030 2031
            } else if (tkdata[0] == '-' && tkdata[1] == '-' &&
                       tkdata[2] == '\0') {
                data_only = true;
                continue;
2032
            } else {
L
Lai Jiangshan 已提交
2033
get_data:
2034 2035
                if (!(opt = vshCmddefGetData(cmd, &opts_need_arg,
                                             &opts_seen))) {
2036
                    vshError(ctl, _("unexpected data '%s'"), tkdata);
K
Karel Zak 已提交
2037 2038 2039 2040 2041
                    goto syntaxError;
                }
            }
            if (opt) {
                /* save option */
2042
                vshCmdOpt *arg = vshMalloc(ctl, sizeof(vshCmdOpt));
2043

K
Karel Zak 已提交
2044 2045 2046 2047
                arg->def = opt;
                arg->data = tkdata;
                arg->next = NULL;
                tkdata = NULL;
2048

K
Karel Zak 已提交
2049 2050 2051 2052 2053
                if (!first)
                    first = arg;
                if (last)
                    last->next = arg;
                last = arg;
2054

2055
                vshDebug(ctl, VSH_ERR_INFO, "%s: %s(%s): %s\n",
2056 2057
                         cmd->name,
                         opt->name,
2058 2059
                         opt->type != VSH_OT_BOOL ? _("optdata") : _("bool"),
                         opt->type != VSH_OT_BOOL ? arg->data : _("(none)"));
K
Karel Zak 已提交
2060 2061
            }
        }
2062

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

K
Karel Zak 已提交
2067 2068 2069 2070
            c->opts = first;
            c->def = cmd;
            c->next = NULL;

2071
            if (vshCommandCheckOpts(ctl, c, opts_required, opts_seen) < 0) {
2072
                VIR_FREE(c);
2073
                goto syntaxError;
2074
            }
2075

K
Karel Zak 已提交
2076 2077 2078 2079 2080 2081
            if (!ctl->cmd)
                ctl->cmd = c;
            if (clast)
                clast->next = c;
            clast = c;
        }
2082 2083 2084

        if (tk == VSH_TK_END)
            break;
K
Karel Zak 已提交
2085
    }
2086

E
Eric Blake 已提交
2087
    return true;
K
Karel Zak 已提交
2088

2089
 syntaxError:
2090
    if (ctl->cmd) {
K
Karel Zak 已提交
2091
        vshCommandFree(ctl->cmd);
2092 2093
        ctl->cmd = NULL;
    }
K
Karel Zak 已提交
2094 2095
    if (first)
        vshCommandOptFree(first);
2096
    VIR_FREE(tkdata);
E
Eric Blake 已提交
2097
    return false;
K
Karel Zak 已提交
2098 2099
}

2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
/* --------------------
 * 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 已提交
2118 2119
static bool
vshCommandArgvParse(vshControl *ctl, int nargs, char **argv)
2120 2121 2122 2123
{
    vshCommandParser parser;

    if (nargs <= 0)
E
Eric Blake 已提交
2124
        return false;
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196

    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 已提交
2197 2198
static bool
vshCommandStringParse(vshControl *ctl, char *cmdstr)
2199 2200 2201 2202
{
    vshCommandParser parser;

    if (cmdstr == NULL || *cmdstr == '\0')
E
Eric Blake 已提交
2203
        return false;
2204 2205 2206 2207 2208 2209

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

K
Karel Zak 已提交
2210
/* ---------------
2211
 * Misc utils
K
Karel Zak 已提交
2212 2213
 * ---------------
 */
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
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;
}

2242 2243
/* Return a non-NULL string representation of a typed parameter; exit
 * if we are out of memory.  */
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
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;

2275 2276 2277 2278
    case VIR_TYPED_PARAM_STRING:
        str = vshStrdup(ctl, item->value.s);
        break;

2279
    default:
2280
        vshError(ctl, _("unimplemented parameter type %d"), item->type);
2281 2282
    }

2283
    if (ret < 0) {
2284
        vshError(ctl, "%s", _("Out of memory"));
2285 2286
        exit(EXIT_FAILURE);
    }
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
    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 已提交
2310
static bool
2311
vshConnectionUsability(vshControl *ctl, virConnectPtr conn)
2312
{
2313 2314
    /* TODO: use something like virConnectionState() to
     *       check usability of the connection
K
Karel Zak 已提交
2315 2316
     */
    if (!conn) {
2317
        vshError(ctl, "%s", _("no valid connection"));
E
Eric Blake 已提交
2318
        return false;
K
Karel Zak 已提交
2319
    }
E
Eric Blake 已提交
2320
    return true;
K
Karel Zak 已提交
2321 2322
}

K
Karel Zak 已提交
2323
static void
2324
vshDebug(vshControl *ctl, int level, const char *format, ...)
2325
{
K
Karel Zak 已提交
2326
    va_list ap;
2327
    char *str;
K
Karel Zak 已提交
2328

2329 2330 2331 2332 2333 2334 2335
    /* Aligning log levels to that of libvirt.
     * Traces with levels >=  user-specified-level
     * gets logged into file
     */
    if (level < ctl->debug)
        return;

2336
    va_start(ap, format);
2337
    vshOutputLogFile(ctl, level, format, ap);
2338 2339
    va_end(ap);

K
Karel Zak 已提交
2340
    va_start(ap, format);
2341 2342 2343 2344 2345
    if (virVasprintf(&str, format, ap) < 0) {
        /* Skip debug messages on low memory */
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2346
    va_end(ap);
2347 2348
    fputs(str, stdout);
    VIR_FREE(str);
K
Karel Zak 已提交
2349 2350 2351
}

static void
2352
vshPrintExtra(vshControl *ctl, const char *format, ...)
2353
{
K
Karel Zak 已提交
2354
    va_list ap;
2355
    char *str;
2356

2357
    if (ctl && ctl->quiet)
K
Karel Zak 已提交
2358
        return;
2359

K
Karel Zak 已提交
2360
    va_start(ap, format);
2361 2362 2363 2364 2365
    if (virVasprintf(&str, format, ap) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
        va_end(ap);
        return;
    }
K
Karel Zak 已提交
2366
    va_end(ap);
2367
    fputs(str, stdout);
2368
    VIR_FREE(str);
K
Karel Zak 已提交
2369 2370
}

K
Karel Zak 已提交
2371

K
Karel Zak 已提交
2372
static void
2373
vshError(vshControl *ctl, const char *format, ...)
2374
{
K
Karel Zak 已提交
2375
    va_list ap;
2376
    char *str;
2377

2378 2379 2380 2381 2382
    if (ctl != NULL) {
        va_start(ap, format);
        vshOutputLogFile(ctl, VSH_ERR_ERROR, format, ap);
        va_end(ap);
    }
2383

2384 2385 2386 2387
    /* 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);
2388
    fputs(_("error: "), stderr);
2389

K
Karel Zak 已提交
2390
    va_start(ap, format);
2391 2392 2393
    /* We can't recursively call vshError on an OOM situation, so ignore
       failure here. */
    ignore_value(virVasprintf(&str, format, ap));
K
Karel Zak 已提交
2394 2395
    va_end(ap);

2396
    fprintf(stderr, "%s\n", NULLSTR(str));
2397
    fflush(stderr);
2398
    VIR_FREE(str);
K
Karel Zak 已提交
2399 2400
}

2401

J
Jiri Denemark 已提交
2402 2403 2404 2405 2406
static void
vshEventLoop(void *opaque)
{
    vshControl *ctl = opaque;

2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
    while (1) {
        bool quit;
        virMutexLock(&ctl->lock);
        quit = ctl->quit;
        virMutexUnlock(&ctl->lock);

        if (quit)
            break;

        if (virEventRunDefaultImpl() < 0)
J
Jiri Denemark 已提交
2417 2418 2419 2420 2421
            virshReportError(ctl);
    }
}


K
Karel Zak 已提交
2422
/*
2423
 * Initialize connection.
K
Karel Zak 已提交
2424
 */
E
Eric Blake 已提交
2425
static bool
2426
vshInit(vshControl *ctl)
2427
{
2428 2429
    char *debugEnv;

K
Karel Zak 已提交
2430
    if (ctl->conn)
E
Eric Blake 已提交
2431
        return false;
K
Karel Zak 已提交
2432

J
Jiri Denemark 已提交
2433
    if (ctl->debug == VSH_DEBUG_DEFAULT) {
2434 2435 2436
        /* log level not set from commandline, check env variable */
        debugEnv = getenv("VIRSH_DEBUG");
        if (debugEnv) {
J
Jiri Denemark 已提交
2437 2438 2439
            int debug;
            if (virStrToLong_i(debugEnv, NULL, 10, &debug) < 0 ||
                debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR) {
2440 2441
                vshError(ctl, "%s",
                         _("VIRSH_DEBUG not set with a valid numeric value"));
J
Jiri Denemark 已提交
2442 2443
            } else {
                ctl->debug = debug;
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
            }
        }
    }

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

2456 2457
    vshOpenLogFile(ctl);

2458 2459
    /* set up the library error handler */
    virSetErrorFunc(NULL, virshErrorHandler);
2460

2461 2462 2463
    /* set up the signals handlers to catch disconnections */
    vshSetupSignals();

2464
    if (virEventRegisterDefaultImpl() < 0)
E
Eric Blake 已提交
2465
        return false;
2466

J
Jiri Denemark 已提交
2467 2468 2469 2470
    if (virThreadCreate(&ctl->eventLoop, true, vshEventLoop, ctl) < 0)
        return false;
    ctl->eventLoopStarted = true;

2471 2472 2473 2474
    if (ctl->name) {
        ctl->conn = virConnectOpenAuth(ctl->name,
                                       virConnectAuthPtrDefault,
                                       ctl->readonly ? VIR_CONNECT_RO : 0);
2475

2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
        /* 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;
        }
2487
    }
K
Karel Zak 已提交
2488

E
Eric Blake 已提交
2489
    return true;
K
Karel Zak 已提交
2490 2491
}

2492 2493
#define LOGFILE_FLAGS (O_WRONLY | O_APPEND | O_CREAT | O_SYNC)

2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512
/**
 * 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:
2513
                vshError(ctl, "%s",
J
Jim Meyering 已提交
2514
                         _("failed to get the log file information"));
2515
                exit(EXIT_FAILURE);
2516 2517 2518
        }
    } else {
        if (!S_ISREG(st.st_mode)) {
2519 2520
            vshError(ctl, "%s", _("the log path is not a file"));
            exit(EXIT_FAILURE);
2521 2522 2523 2524
        }
    }

    /* log file open */
2525
    if ((ctl->log_fd = open(ctl->logfile, LOGFILE_FLAGS, FILE_MODE)) < 0) {
2526
        vshError(ctl, "%s",
J
Jim Meyering 已提交
2527
                 _("failed to open the log file. check the log file path"));
2528
        exit(EXIT_FAILURE);
2529 2530 2531 2532 2533 2534 2535 2536 2537
    }
}

/**
 * vshOutputLogFile:
 *
 * Outputting an error to log file.
 */
static void
2538 2539
vshOutputLogFile(vshControl *ctl, int log_level, const char *msg_format,
                 va_list ap)
2540
{
2541 2542 2543
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *str;
    size_t len;
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
    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);
2558
    virBufferAsprintf(&buf, "[%d.%02d.%02d %02d:%02d:%02d %s %d] ",
2559 2560 2561 2562 2563 2564
                      (1900 + stTm->tm_year),
                      (1 + stTm->tm_mon),
                      stTm->tm_mday,
                      stTm->tm_hour,
                      stTm->tm_min,
                      stTm->tm_sec,
2565 2566
                      SIGN_NAME,
                      (int) getpid());
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
    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;
    }
2587 2588 2589
    virBufferAsprintf(&buf, "%s ", lvl);
    virBufferVasprintf(&buf, msg_format, ap);
    virBufferAddChar(&buf, '\n');
2590

2591 2592
    if (virBufferError(&buf))
        goto error;
2593

2594 2595 2596 2597 2598
    str = virBufferContentAndReset(&buf);
    len = strlen(str);
    if (len > 1 && str[len - 2] == '\n') {
        str[len - 1] = '\0';
        len--;
2599
    }
2600

2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
    /* 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);
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622
}

/**
 * vshCloseLogFile:
 *
 * Close log file.
 */
static void
vshCloseLogFile(vshControl *ctl)
{
    /* log file close */
2623 2624 2625
    if (VIR_CLOSE(ctl->log_fd) < 0) {
        vshError(ctl, _("%s: failed to write log file: %s"),
                 ctl->logfile ? ctl->logfile : "?", strerror (errno));
2626 2627 2628
    }

    if (ctl->logfile) {
2629
        VIR_FREE(ctl->logfile);
2630 2631 2632 2633
        ctl->logfile = NULL;
    }
}

2634
#ifdef USE_READLINE
2635

K
Karel Zak 已提交
2636 2637 2638 2639 2640
/* -----------------
 * Readline stuff
 * -----------------
 */

2641
/*
K
Karel Zak 已提交
2642 2643
 * Generator function for command completion.  STATE lets us
 * know whether to start from scratch; without any state
2644
 * (i.e. STATE == 0), then we start at the top of the list.
K
Karel Zak 已提交
2645 2646
 */
static char *
2647 2648
vshReadlineCommandGenerator(const char *text, int state)
{
2649
    static int grp_list_index, cmd_list_index, len;
K
Karel Zak 已提交
2650
    const char *name;
2651 2652
    const vshCmdGrp *grp;
    const vshCmdDef *cmds;
K
Karel Zak 已提交
2653 2654

    if (!state) {
2655 2656
        grp_list_index = 0;
        cmd_list_index = 0;
2657
        len = strlen(text);
K
Karel Zak 已提交
2658 2659
    }

2660 2661
    grp = cmdGroups;

K
Karel Zak 已提交
2662
    /* Return the next name which partially matches from the
2663
     * command list.
K
Karel Zak 已提交
2664
     */
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
    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 已提交
2679 2680 2681 2682 2683 2684 2685
    }

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

static char *
2686 2687
vshReadlineOptionsGenerator(const char *text, int state)
{
K
Karel Zak 已提交
2688
    static int list_index, len;
2689
    static const vshCmdDef *cmd = NULL;
K
Karel Zak 已提交
2690
    const char *name;
K
Karel Zak 已提交
2691 2692 2693 2694 2695 2696 2697 2698 2699

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

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

2700
        cmdname = vshCalloc(NULL, (p - rl_line_buffer) + 1, 1);
2701
        memcpy(cmdname, rl_line_buffer, p - rl_line_buffer);
K
Karel Zak 已提交
2702 2703 2704

        cmd = vshCmddefSearch(cmdname);
        list_index = 0;
2705
        len = strlen(text);
2706
        VIR_FREE(cmdname);
K
Karel Zak 已提交
2707 2708 2709 2710
    }

    if (!cmd)
        return NULL;
2711

2712 2713 2714
    if (!cmd->opts)
        return NULL;

K
Karel Zak 已提交
2715
    while ((name = cmd->opts[list_index].name)) {
2716
        const vshCmdOptDef *opt = &cmd->opts[list_index];
K
Karel Zak 已提交
2717
        char *res;
2718

K
Karel Zak 已提交
2719
        list_index++;
2720

2721
        if (opt->type == VSH_OT_DATA || opt->type == VSH_OT_ARGV)
K
Karel Zak 已提交
2722 2723
            /* ignore non --option */
            continue;
2724

K
Karel Zak 已提交
2725
        if (len > 2) {
2726
            if (STRNEQLEN(name, text + 2, len - 2))
K
Karel Zak 已提交
2727 2728
                continue;
        }
2729
        res = vshMalloc(NULL, strlen(name) + 3);
2730
        snprintf(res, strlen(name) + 3,  "--%s", name);
K
Karel Zak 已提交
2731 2732 2733 2734 2735 2736 2737 2738
        return res;
    }

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

static char **
2739 2740 2741
vshReadlineCompletion(const char *text, int start,
                      int end ATTRIBUTE_UNUSED)
{
K
Karel Zak 已提交
2742 2743
    char **matches = (char **) NULL;

2744
    if (start == 0)
K
Karel Zak 已提交
2745
        /* command name generator */
2746
        matches = rl_completion_matches(text, vshReadlineCommandGenerator);
K
Karel Zak 已提交
2747 2748
    else
        /* commands options */
2749
        matches = rl_completion_matches(text, vshReadlineOptionsGenerator);
K
Karel Zak 已提交
2750 2751 2752 2753
    return matches;
}


2754 2755
static int
vshReadlineInit(vshControl *ctl)
2756
{
2757 2758
    char *userdir = NULL;

K
Karel Zak 已提交
2759 2760 2761 2762 2763
    /* 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;
2764 2765 2766

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

2768
    /* Prepare to read/write history from/to the $XDG_CACHE_HOME/virsh/history file */
2769
    userdir = virGetUserCacheDirectory();
2770

2771 2772
    if (userdir == NULL) {
        vshError(ctl, "%s", _("Could not determine home directory"));
2773
        return -1;
2774
    }
2775

2776
    if (virAsprintf(&ctl->historydir, "%s/virsh", userdir) < 0) {
2777
        vshError(ctl, "%s", _("Out of memory"));
2778
        VIR_FREE(userdir);
2779 2780 2781 2782 2783
        return -1;
    }

    if (virAsprintf(&ctl->historyfile, "%s/history", ctl->historydir) < 0) {
        vshError(ctl, "%s", _("Out of memory"));
2784
        VIR_FREE(userdir);
2785 2786 2787
        return -1;
    }

2788
    VIR_FREE(userdir);
2789 2790 2791 2792 2793 2794 2795

    read_history(ctl->historyfile);

    return 0;
}

static void
2796
vshReadlineDeinit(vshControl *ctl)
2797 2798
{
    if (ctl->historyfile != NULL) {
2799 2800
        if (virFileMakePathWithMode(ctl->historydir, 0755) < 0 &&
            errno != EEXIST) {
2801 2802
            char ebuf[1024];
            vshError(ctl, _("Failed to create '%s': %s"),
2803
                     ctl->historydir, virStrerror(errno, ebuf, sizeof(ebuf)));
E
Eric Blake 已提交
2804
        } else {
2805
            write_history(ctl->historyfile);
E
Eric Blake 已提交
2806
        }
2807 2808
    }

2809 2810
    VIR_FREE(ctl->historydir);
    VIR_FREE(ctl->historyfile);
K
Karel Zak 已提交
2811 2812
}

2813
static char *
2814
vshReadline(vshControl *ctl ATTRIBUTE_UNUSED, const char *prompt)
2815
{
2816
    return readline(prompt);
2817 2818
}

2819
#else /* !USE_READLINE */
2820

2821
static int
2822
vshReadlineInit(vshControl *ctl ATTRIBUTE_UNUSED)
2823 2824 2825 2826 2827
{
    /* empty */
    return 0;
}

2828
static void
2829
vshReadlineDeinit(vshControl *ctl ATTRIBUTE_UNUSED)
2830 2831 2832 2833 2834
{
    /* empty */
}

static char *
2835
vshReadline(vshControl *ctl, const char *prompt)
2836 2837 2838 2839 2840
{
    char line[1024];
    char *r;
    int len;

2841 2842
    fputs(prompt, stdout);
    r = fgets(line, sizeof(line), stdin);
2843 2844 2845
    if (r == NULL) return NULL; /* EOF */

    /* Chomp trailing \n */
2846
    len = strlen(r);
2847 2848 2849
    if (len > 0 && r[len-1] == '\n')
        r[len-1] = '\0';

2850
    return vshStrdup(ctl, r);
2851 2852
}

2853
#endif /* !USE_READLINE */
2854

2855 2856 2857 2858 2859 2860
static void
vshDeinitTimer(int timer ATTRIBUTE_UNUSED, void *opaque ATTRIBUTE_UNUSED)
{
    /* nothing to be done here */
}

K
Karel Zak 已提交
2861
/*
J
Jim Meyering 已提交
2862
 * Deinitialize virsh
K
Karel Zak 已提交
2863
 */
E
Eric Blake 已提交
2864
static bool
2865
vshDeinit(vshControl *ctl)
2866
{
2867
    vshReadlineDeinit(ctl);
2868
    vshCloseLogFile(ctl);
2869
    VIR_FREE(ctl->name);
K
Karel Zak 已提交
2870
    if (ctl->conn) {
2871 2872 2873
        int ret;
        if ((ret = virConnectClose(ctl->conn)) != 0) {
            vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret);
K
Karel Zak 已提交
2874 2875
        }
    }
D
Daniel P. Berrange 已提交
2876 2877
    virResetLastError();

J
Jiri Denemark 已提交
2878
    if (ctl->eventLoopStarted) {
2879 2880 2881 2882
        int timer;

        virMutexLock(&ctl->lock);
        ctl->quit = true;
J
Jiri Denemark 已提交
2883
        /* HACK: Add a dummy timeout to break event loop */
2884 2885 2886 2887 2888
        timer = virEventAddTimeout(0, vshDeinitTimer, NULL, NULL);
        virMutexUnlock(&ctl->lock);

        virThreadJoin(&ctl->eventLoop);

J
Jiri Denemark 已提交
2889 2890 2891 2892 2893 2894
        if (timer != -1)
            virEventRemoveTimeout(timer);

        ctl->eventLoopStarted = false;
    }

2895 2896
    virMutexDestroy(&ctl->lock);

E
Eric Blake 已提交
2897
    return true;
K
Karel Zak 已提交
2898
}
2899

K
Karel Zak 已提交
2900 2901 2902 2903
/*
 * Print usage
 */
static void
2904
vshUsage(void)
2905
{
2906
    const vshCmdGrp *grp;
2907
    const vshCmdDef *cmd;
2908

L
Lai Jiangshan 已提交
2909 2910
    fprintf(stdout, _("\n%s [options]... [<command_string>]"
                      "\n%s [options]... <command> [args...]\n\n"
2911
                      "  options:\n"
2912
                      "    -c | --connect=URI      hypervisor connection URI\n"
2913
                      "    -r | --readonly         connect readonly\n"
2914
                      "    -d | --debug=NUM        debug level [0-4]\n"
2915 2916 2917
                      "    -h | --help             this help\n"
                      "    -q | --quiet            quiet mode\n"
                      "    -t | --timing           print timing information\n"
2918 2919 2920 2921 2922
                      "    -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"
2923
                      "  commands (non interactive mode):\n\n"), progname, progname);
2924

2925
    for (grp = cmdGroups; grp->name; grp++) {
E
Eric Blake 已提交
2926 2927 2928 2929 2930
        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;
2931
            fprintf(stdout,
E
Eric Blake 已提交
2932 2933 2934
                    "    %-30s %s\n", cmd->name,
                    _(vshCmddefGetInfo(cmd, "help")));
        }
2935 2936 2937 2938 2939
        fprintf(stdout, "\n");
    }

    fprintf(stdout, "%s",
            _("\n  (specify help <group> for details about the commands in the group)\n"));
2940 2941 2942
    fprintf(stdout, "%s",
            _("\n  (specify help <command> for details about the command)\n\n"));
    return;
K
Karel Zak 已提交
2943 2944
}

2945 2946 2947 2948 2949 2950 2951 2952 2953 2954
/*
 * 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 已提交
2955 2956
    vshPrint(ctl, "%s", _("Compiled with support for:\n"));
    vshPrint(ctl, "%s", _(" Hypervisors:"));
2957 2958 2959
#ifdef WITH_QEMU
    vshPrint(ctl, " QEmu/KVM");
#endif
D
Doug Goldstein 已提交
2960 2961 2962
#ifdef WITH_LXC
    vshPrint(ctl, " LXC");
#endif
2963 2964 2965
#ifdef WITH_UML
    vshPrint(ctl, " UML");
#endif
D
Doug Goldstein 已提交
2966 2967 2968 2969 2970 2971
#ifdef WITH_XEN
    vshPrint(ctl, " Xen");
#endif
#ifdef WITH_LIBXL
    vshPrint(ctl, " LibXL");
#endif
2972 2973 2974
#ifdef WITH_OPENVZ
    vshPrint(ctl, " OpenVZ");
#endif
D
Doug Goldstein 已提交
2975 2976
#ifdef WITH_VMWARE
    vshPrint(ctl, " VMWare");
2977
#endif
D
Doug Goldstein 已提交
2978 2979
#ifdef WITH_PHYP
    vshPrint(ctl, " PHYP");
2980
#endif
D
Doug Goldstein 已提交
2981 2982
#ifdef WITH_VBOX
    vshPrint(ctl, " VirtualBox");
2983 2984 2985 2986
#endif
#ifdef WITH_ESX
    vshPrint(ctl, " ESX");
#endif
D
Doug Goldstein 已提交
2987 2988
#ifdef WITH_HYPERV
    vshPrint(ctl, " Hyper-V");
2989
#endif
D
Doug Goldstein 已提交
2990 2991
#ifdef WITH_XENAPI
    vshPrint(ctl, " XenAPI");
2992 2993 2994 2995 2996 2997
#endif
#ifdef WITH_TEST
    vshPrint(ctl, " Test");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
2998
    vshPrint(ctl, "%s", _(" Networking:"));
2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
#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 已提交
3012
    vshPrint(ctl, " Interface");
3013 3014 3015 3016 3017 3018 3019 3020 3021
#endif
#ifdef WITH_NWFILTER
    vshPrint(ctl, " Nwfilter");
#endif
#ifdef WITH_VIRTUALPORT
    vshPrint(ctl, " VirtualPort");
#endif
    vshPrint(ctl, "\n");

L
Laine Stump 已提交
3022
    vshPrint(ctl, "%s", _(" Storage:"));
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042
#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");
3043 3044 3045
#endif
#ifdef WITH_STORAGE_RBD
    vshPrint(ctl, " RBD");
3046 3047 3048
#endif
#ifdef WITH_STORAGE_SHEEPDOG
    vshPrint(ctl, " Sheepdog");
3049 3050 3051
#endif
    vshPrint(ctl, "\n");

3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
    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)
{
3097
    int arg, len, debug;
3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116
    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':
3117
            if (virStrToLong_i(optarg, NULL, 10, &debug) < 0) {
3118 3119 3120
                vshError(ctl, "%s", _("option -d takes a numeric argument"));
                exit(EXIT_FAILURE);
            }
3121 3122 3123 3124 3125
            if (debug < VSH_ERR_DEBUG || debug > VSH_ERR_ERROR)
                vshError(ctl, _("ignoring debug level %d out of range [%d-%d]"),
                         debug, VSH_ERR_DEBUG, VSH_ERR_ERROR);
            else
                ctl->debug = debug;
3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
            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;
}

3187
#include "virsh-domain.c"
3188
#include "virsh-domain-monitor.c"
3189
#include "virsh-pool.c"
3190
#include "virsh-volume.c"
3191
#include "virsh-network.c"
3192
#include "virsh-nodedev.c"
3193
#include "virsh-interface.c"
3194
#include "virsh-nwfilter.c"
3195
#include "virsh-secret.c"
3196 3197
#include "virsh-snapshot.c"
#include "virsh-host.c"
3198

3199 3200 3201 3202 3203 3204 3205 3206 3207
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}
};
3208

3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223
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 已提交
3224

3225 3226 3227 3228
int
main(int argc, char **argv)
{
    vshControl _ctl, *ctl = &_ctl;
3229
    char *defaultConn;
E
Eric Blake 已提交
3230
    bool ret = true;
K
Karel Zak 已提交
3231

3232 3233 3234
    memset(ctl, 0, sizeof(vshControl));
    ctl->imode = true;          /* default is interactive mode */
    ctl->log_fd = -1;           /* Initialize log file descriptor */
J
Jiri Denemark 已提交
3235
    ctl->debug = VSH_DEBUG_DEFAULT;
3236 3237
    ctl->escapeChar = CTRL_CLOSE_BRACKET;

3238

3239 3240
    if (!setlocale(LC_ALL, "")) {
        perror("setlocale");
3241
        /* failure to setup locale is not fatal */
3242
    }
3243
    if (!bindtextdomain(PACKAGE, LOCALEDIR)) {
3244
        perror("bindtextdomain");
E
Eric Blake 已提交
3245
        return EXIT_FAILURE;
3246
    }
3247
    if (!textdomain(PACKAGE)) {
3248
        perror("textdomain");
E
Eric Blake 已提交
3249
        return EXIT_FAILURE;
3250 3251
    }

3252 3253 3254 3255 3256
    if (virMutexInit(&ctl->lock) < 0) {
        vshError(ctl, "%s", _("Failed to initialize mutex"));
        return EXIT_FAILURE;
    }

3257 3258 3259 3260 3261
    if (virInitialize() < 0) {
        vshError(ctl, "%s", _("Failed to initialize libvirt"));
        return EXIT_FAILURE;
    }

3262
    if (!(progname = strrchr(argv[0], '/')))
K
Karel Zak 已提交
3263 3264 3265
        progname = argv[0];
    else
        progname++;
3266

3267
    if ((defaultConn = getenv("VIRSH_DEFAULT_CONNECT_URI"))) {
E
Eric Blake 已提交
3268
        ctl->name = vshStrdup(ctl, defaultConn);
3269 3270
    }

D
Daniel P. Berrange 已提交
3271 3272
    if (!vshParseArgv(ctl, argc, argv)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
3273
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3274
    }
3275

D
Daniel P. Berrange 已提交
3276 3277
    if (!vshInit(ctl)) {
        vshDeinit(ctl);
K
Karel Zak 已提交
3278
        exit(EXIT_FAILURE);
D
Daniel P. Berrange 已提交
3279
    }
3280

K
Karel Zak 已提交
3281
    if (!ctl->imode) {
3282
        ret = vshCommandRun(ctl, ctl->cmd);
3283
    } else {
K
Karel Zak 已提交
3284 3285
        /* interactive mode */
        if (!ctl->quiet) {
K
Karel Zak 已提交
3286
            vshPrint(ctl,
3287
                     _("Welcome to %s, the virtualization interactive terminal.\n\n"),
3288
                     progname);
J
Jim Meyering 已提交
3289
            vshPrint(ctl, "%s",
3290
                     _("Type:  'help' for help with commands\n"
3291
                       "       'quit' to quit\n\n"));
K
Karel Zak 已提交
3292
        }
3293 3294 3295 3296 3297 3298

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

K
Karel Zak 已提交
3299
        do {
3300
            const char *prompt = ctl->readonly ? VSH_PROMPT_RO : VSH_PROMPT_RW;
3301
            ctl->cmdstr =
3302
                vshReadline(ctl, prompt);
3303 3304
            if (ctl->cmdstr == NULL)
                break;          /* EOF */
K
Karel Zak 已提交
3305
            if (*ctl->cmdstr) {
3306
#if USE_READLINE
K
Karel Zak 已提交
3307
                add_history(ctl->cmdstr);
3308
#endif
3309
                if (vshCommandStringParse(ctl, ctl->cmdstr))
K
Karel Zak 已提交
3310 3311
                    vshCommandRun(ctl, ctl->cmd);
            }
3312
            VIR_FREE(ctl->cmdstr);
3313
        } while (ctl->imode);
K
Karel Zak 已提交
3314

3315 3316
        if (ctl->cmdstr == NULL)
            fputc('\n', stdout);        /* line break after alone prompt */
K
Karel Zak 已提交
3317
    }
3318

K
Karel Zak 已提交
3319 3320
    vshDeinit(ctl);
    exit(ret ? EXIT_SUCCESS : EXIT_FAILURE);
3321
}