1 /*
2  * vsh.h: common data to be used by clients to exercise the libvirt API
3  *
4  * Copyright (C) 2005, 2007-2015 Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library.  If not, see
18  * <http://www.gnu.org/licenses/>.
19  */
20 
21 #pragma once
22 
23 #include <stdarg.h>
24 #ifndef WIN32
25 # include <termios.h>
26 #endif
27 
28 #include "internal.h"
29 #include "virerror.h"
30 #include "virthread.h"
31 
32 #define VIR_FROM_THIS VIR_FROM_NONE
33 
34 #define VSH_MAX_XML_FILE (10*1024*1024)
35 #define VSH_MATCH(FLAG) (flags & (FLAG))
36 
37 /**
38  * The log configuration
39  */
40 #define MSG_BUFFER    4096
41 #define DIR_MODE      (S_IWUSR | S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)  /* 0755 */
42 #define FILE_MODE     (S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH)                                /* 0644 */
43 #define LOCK_MODE     (S_IWUSR | S_IRUSR)                                                    /* 0600 */
44 #define LVL_DEBUG     "DEBUG"
45 #define LVL_INFO      "INFO"
46 #define LVL_NOTICE    "NOTICE"
47 #define LVL_WARNING   "WARNING"
48 #define LVL_ERROR     "ERROR"
49 
50 /**
51  * vshErrorLevel:
52  *
53  * Indicates the level of a log message
54  */
55 typedef enum {
56     VSH_ERR_DEBUG = 0,
57     VSH_ERR_INFO,
58     VSH_ERR_NOTICE,
59     VSH_ERR_WARNING,
60     VSH_ERR_ERROR
61 } vshErrorLevel;
62 
63 #define VSH_DEBUG_DEFAULT VSH_ERR_ERROR
64 
65 /*
66  * virsh command line grammar:
67  *
68  *    command_line    =     <command>\n | <command>; <command>; ...
69  *
70  *    command         =    <keyword> <option> [--] <data>
71  *
72  *    option          =     <bool_option> | <int_option> | <string_option>
73  *    data            =     <string>
74  *
75  *    bool_option     =     --optionname
76  *    int_option      =     --optionname <number> | --optionname=<number>
77  *    string_option   =     --optionname <string> | --optionname=<string>
78  *
79  *    keyword         =     [a-zA-Z][a-zA-Z-]*
80  *    number          =     [0-9]+
81  *    string          =     ('[^']*'|"([^\\"]|\\.)*"|([^ \t\n\\'"]|\\.))+
82  *
83  */
84 
85 /*
86  * vshCmdOptType - command option type
87  */
88 typedef enum {
89     VSH_OT_BOOL,     /* optional boolean option */
90     VSH_OT_STRING,   /* optional string option */
91     VSH_OT_INT,      /* optional or mandatory int option */
92     VSH_OT_DATA,     /* string data (as non-option) */
93     VSH_OT_ARGV,     /* remaining arguments */
94     VSH_OT_ALIAS,    /* alternate spelling for a later argument */
95 } vshCmdOptType;
96 
97 /*
98  * Command Option Flags
99  */
100 enum {
101     VSH_OFLAG_NONE     = 0,        /* without flags */
102     VSH_OFLAG_REQ      = (1 << 0), /* option required */
103     VSH_OFLAG_EMPTY_OK = (1 << 1), /* empty string option allowed */
104     VSH_OFLAG_REQ_OPT  = (1 << 2), /* --optionname required */
105 };
106 
107 /* forward declarations */
108 typedef struct _vshClientHooks vshClientHooks;
109 typedef struct _vshCmd vshCmd;
110 typedef struct _vshCmdDef vshCmdDef;
111 typedef struct _vshCmdGrp vshCmdGrp;
112 typedef struct _vshCmdInfo vshCmdInfo;
113 typedef struct _vshCmdOpt vshCmdOpt;
114 typedef struct _vshCmdOptDef vshCmdOptDef;
115 typedef struct _vshControl vshControl;
116 
117 typedef char **(*vshCompleter)(vshControl *ctl,
118                                const vshCmd *cmd,
119                                unsigned int flags);
120 
121 /*
122  * vshCmdInfo -- name/value pair for information about command
123  *
124  * Commands should have at least the following names:
125  * "help" - short description of command
126  * "desc" - description of command, or empty string
127  */
128 struct _vshCmdInfo {
129     const char *name;           /* name of information, or NULL for list end */
130     const char *data;           /* non-NULL information */
131 };
132 
133 /*
134  * vshCmdOptDef - command option definition
135  */
136 struct _vshCmdOptDef {
137     const char *name;           /* the name of option, or NULL for list end */
138     vshCmdOptType type;         /* option type */
139     unsigned int flags;         /* flags */
140     const char *help;           /* non-NULL help string; or for VSH_OT_ALIAS
141                                  * the name of a later public option */
142     vshCompleter completer;         /* option completer */
143     unsigned int completer_flags;   /* option completer flags */
144 };
145 
146 /*
147  * vshCmdOpt - command options
148  *
149  * After parsing a command, all arguments to the command have been
150  * collected into a list of these objects.
151  */
152 struct _vshCmdOpt {
153     const vshCmdOptDef *def;    /* non-NULL pointer to option definition */
154     char *data;                 /* allocated data, or NULL for bool option */
155     bool completeThis;          /* true if this is the option user's wishing to
156                                    autocomplete */
157     vshCmdOpt *next;
158 };
159 
160 /*
161  * Command Usage Flags
162  */
163 enum {
164     VSH_CMD_FLAG_NOCONNECT = (1 << 0),  /* no prior connection needed */
165     VSH_CMD_FLAG_ALIAS     = (1 << 1),  /* command is an alias */
166     VSH_CMD_FLAG_HIDDEN    = (1 << 2),  /* command is hidden/internal */
167 };
168 
169 /*
170  * vshCmdDef - command definition
171  */
172 struct _vshCmdDef {
173     const char *name;           /* name of command, or NULL for list end */
174     bool (*handler) (vshControl *, const vshCmd *);    /* command handler */
175     const vshCmdOptDef *opts;   /* definition of command options */
176     const vshCmdInfo *info;     /* details about command */
177     unsigned int flags;         /* bitwise OR of VSH_CMD_FLAG */
178     const char *alias;          /* name of the aliased command */
179 };
180 
181 /*
182  * vshCmd - parsed command
183  */
184 struct _vshCmd {
185     const vshCmdDef *def;       /* command definition */
186     vshCmdOpt *opts;            /* list of command arguments */
187     vshCmd *next;               /* next command */
188     bool skipChecks;            /* skip validity checks when retrieving opts */
189 };
190 
191 /*
192  * vshControl
193  */
194 struct _vshControl {
195     const char *name;           /* hardcoded name of the binary that cannot
196                                  * be changed without recompilation compared
197                                  * to program name */
198     const char *env_prefix;     /* hardcoded environment variable prefix */
199     char *connname;             /* connection name */
200     char *progname;             /* program name */
201     vshCmd *cmd;                /* the current command */
202     char *cmdstr;               /* string with command */
203     bool imode;                 /* interactive mode? */
204     bool quiet;                 /* quiet mode */
205     bool timing;                /* print timing info? */
206     int debug;                  /* print debug messages? */
207     char *logfile;              /* log file name */
208     int log_fd;                 /* log file descriptor */
209     char *historydir;           /* readline history directory name */
210     char *historyfile;          /* readline history file name */
211     virThread eventLoop;
212     virMutex lock;
213     bool eventLoopStarted;
214     bool quit;
215     int eventPipe[2];           /* Write-to-self pipe to end waiting for an
216                                  * event to occur */
217     int eventTimerId;           /* id of event loop timeout registration */
218 
219     int keepalive_interval;     /* Client keepalive interval */
220     int keepalive_count;        /* Client keepalive count */
221 
222 #ifndef WIN32
223     struct termios termattr;    /* settings of the tty terminal */
224 #endif
225     bool istty;                 /* is the terminal a tty */
226 
227     const vshClientHooks *hooks;/* mandatory client specific hooks */
228     void *privData;             /* client specific data */
229 };
230 
231 typedef void *
232 (*vshConnectionHook)(vshControl *ctl);
233 
234 struct _vshClientHooks {
235     vshConnectionHook connHandler;
236 };
237 
238 struct _vshCmdGrp {
239     const char *name;    /* name of group, or NULL for list end */
240     const char *keyword; /* help keyword */
241     const vshCmdDef *commands;
242 };
243 
244 void vshError(vshControl *ctl, const char *format, ...)
245     G_GNUC_PRINTF(2, 3);
246 void vshOpenLogFile(vshControl *ctl);
247 void vshOutputLogFile(vshControl *ctl, int log_level, const char *format,
248                       va_list ap)
249     G_GNUC_PRINTF(3, 0);
250 void vshCloseLogFile(vshControl *ctl);
251 
252 const char *vshCmddefGetInfo(const vshCmdDef *cmd, const char *info);
253 const vshCmdDef *vshCmddefSearch(const char *cmdname);
254 const vshCmdGrp *vshCmdGrpSearch(const char *grpname);
255 bool vshCmdGrpHelp(vshControl *ctl, const vshCmdGrp *grp);
256 
257 int vshCommandOptInt(vshControl *ctl, const vshCmd *cmd,
258                      const char *name, int *value)
259     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
260 int vshCommandOptUInt(vshControl *ctl, const vshCmd *cmd,
261                       const char *name, unsigned int *value)
262     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
263 int vshCommandOptUIntWrap(vshControl *ctl, const vshCmd *cmd,
264                           const char *name, unsigned int *value)
265     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
266 int vshCommandOptUL(vshControl *ctl, const vshCmd *cmd,
267                     const char *name, unsigned long *value)
268     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
269 int vshCommandOptULWrap(vshControl *ctl, const vshCmd *cmd,
270                         const char *name, unsigned long *value)
271     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
272 int vshCommandOptStringQuiet(vshControl *ctl, const vshCmd *cmd,
273                              const char *name, const char **value)
274     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
275 int vshCommandOptStringReq(vshControl *ctl, const vshCmd *cmd,
276                            const char *name, const char **value)
277     ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3)
278     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
279 int vshCommandOptLongLong(vshControl *ctl, const vshCmd *cmd,
280                           const char *name, long long *value)
281     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
282 int vshCommandOptULongLong(vshControl *ctl, const vshCmd *cmd,
283                            const char *name, unsigned long long *value)
284     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
285 int vshCommandOptULongLongWrap(vshControl *ctl, const vshCmd *cmd,
286                                const char *name, unsigned long long *value)
287     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
288 int vshCommandOptScaledInt(vshControl *ctl, const vshCmd *cmd,
289                            const char *name, unsigned long long *value,
290                            int scale, unsigned long long max)
291     ATTRIBUTE_NONNULL(4) G_GNUC_WARN_UNUSED_RESULT;
292 int vshBlockJobOptionBandwidth(vshControl *ctl,
293                                const vshCmd *cmd,
294                                bool bytes,
295                                unsigned long *bandwidth);
296 bool vshCommandOptBool(const vshCmd *cmd, const char *name);
297 bool vshCommandRun(vshControl *ctl, const vshCmd *cmd);
298 bool vshCommandStringParse(vshControl *ctl, char *cmdstr,
299                            vshCmd **partial, size_t point);
300 
301 const vshCmdOpt *vshCommandOptArgv(vshControl *ctl, const vshCmd *cmd,
302                                    const vshCmdOpt *opt);
303 bool vshCommandArgvParse(vshControl *ctl, int nargs, char **argv);
304 int vshCommandOptTimeoutToMs(vshControl *ctl, const vshCmd *cmd, int *timeout);
305 
306 void vshPrint(vshControl *ctl, const char *format, ...)
307     G_GNUC_PRINTF(2, 3);
308 void vshPrintExtra(vshControl *ctl, const char *format, ...)
309     G_GNUC_PRINTF(2, 3);
310 bool vshInit(vshControl *ctl, const vshCmdGrp *groups, const vshCmdDef *set);
311 bool vshInitReload(vshControl *ctl);
312 void vshDeinit(vshControl *ctl);
313 void vshDebug(vshControl *ctl, int level, const char *format, ...)
314     G_GNUC_PRINTF(3, 4);
315 
316 /* User visible sort, so we want locale-specific case comparison.  */
317 #define vshStrcasecmp(S1, S2) strcasecmp(S1, S2)
318 int vshNameSorter(const void *a, const void *b);
319 
320 virTypedParameterPtr vshFindTypedParamByName(const char *name,
321                                              virTypedParameterPtr list,
322                                              int count);
323 char *vshGetTypedParamValue(vshControl *ctl, virTypedParameterPtr item)
324     ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2);
325 
326 double vshPrettyCapacity(unsigned long long val, const char **unit);
327 int vshStringToArray(const char *str, char ***array);
328 
329 /* Given an index, return either the name of that device (non-NULL) or
330  * of its parent (NULL if a root).  */
331 typedef const char * (*vshTreeLookup)(int devid, bool parent, void *opaque);
332 int vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque,
333                  int num_devices, int devid);
334 
335 /* error handling */
336 extern virErrorPtr last_error;
337 void vshErrorHandler(void *opaque, virErrorPtr error);
338 void vshReportError(vshControl *ctl);
339 void vshResetLibvirtError(void);
340 void vshSaveLibvirtError(void);
341 void vshSaveLibvirtHelperError(void);
342 
343 /* file handling */
344 char *vshEditWriteToTempFile(vshControl *ctl, const char *doc);
345 int vshEditFile(vshControl *ctl, const char *filename);
346 char *vshEditReadBackFile(vshControl *ctl, const char *filename);
347 int vshAskReedit(vshControl *ctl, const char *msg, bool relax_avail);
348 
349 /* terminal modifications */
350 bool vshTTYIsInterruptCharacter(vshControl *ctl, const char chr);
351 int vshTTYDisableInterrupt(vshControl *ctl);
352 int vshTTYRestore(vshControl *ctl);
353 int vshTTYMakeRaw(vshControl *ctl, bool report_errors);
354 bool vshTTYAvailable(vshControl *ctl);
355 
356 /* waiting for events */
357 enum {
358     VSH_EVENT_INTERRUPT,
359     VSH_EVENT_TIMEOUT,
360     VSH_EVENT_DONE,
361 };
362 void vshEventCleanup(vshControl *ctl);
363 void vshEventDone(vshControl *ctl);
364 void vshEventLoop(void *opaque);
365 int vshEventStart(vshControl *ctl, int timeout_ms);
366 void vshEventTimeout(int timer, void *opaque);
367 int vshEventWait(vshControl *ctl);
368 
369 /* generic commands */
370 extern const vshCmdOptDef opts_help[];
371 extern const vshCmdInfo info_help[];
372 extern const vshCmdOptDef opts_cd[];
373 extern const vshCmdInfo info_cd[];
374 extern const vshCmdOptDef opts_echo[];
375 extern const vshCmdInfo info_echo[];
376 extern const vshCmdInfo info_pwd[];
377 extern const vshCmdInfo info_quit[];
378 extern const vshCmdOptDef opts_selftest[];
379 extern const vshCmdInfo info_selftest[];
380 extern const vshCmdOptDef opts_complete[];
381 extern const vshCmdInfo info_complete[];
382 
383 bool cmdHelp(vshControl *ctl, const vshCmd *cmd);
384 bool cmdCd(vshControl *ctl, const vshCmd *cmd);
385 bool cmdEcho(vshControl *ctl, const vshCmd *cmd);
386 bool cmdPwd(vshControl *ctl, const vshCmd *cmd);
387 bool cmdQuit(vshControl *ctl, const vshCmd *cmd);
388 bool cmdSelfTest(vshControl *ctl, const vshCmd *cmd);
389 bool cmdComplete(vshControl *ctl, const vshCmd *cmd);
390 
391 #define VSH_CMD_CD \
392     { \
393         .name = "cd", \
394         .handler = cmdCd, \
395         .opts = opts_cd, \
396         .info = info_cd, \
397         .flags = VSH_CMD_FLAG_NOCONNECT \
398     }
399 
400 #define VSH_CMD_ECHO \
401     { \
402         .name = "echo", \
403         .handler = cmdEcho, \
404         .opts = opts_echo, \
405         .info = info_echo, \
406         .flags = VSH_CMD_FLAG_NOCONNECT \
407     }
408 
409 #define VSH_CMD_EXIT \
410     { \
411         .name = "exit", \
412         .handler = cmdQuit, \
413         .opts = NULL, \
414         .info = info_quit, \
415         .flags = VSH_CMD_FLAG_NOCONNECT \
416     }
417 
418 #define VSH_CMD_HELP \
419     { \
420         .name = "help", \
421         .handler = cmdHelp, \
422         .opts = opts_help, \
423         .info = info_help, \
424         .flags = VSH_CMD_FLAG_NOCONNECT \
425     }
426 
427 #define VSH_CMD_PWD \
428     { \
429         .name = "pwd", \
430         .handler = cmdPwd, \
431         .opts = NULL, \
432         .info = info_pwd, \
433         .flags = VSH_CMD_FLAG_NOCONNECT \
434     }
435 
436 #define VSH_CMD_QUIT \
437     { \
438         .name = "quit", \
439         .handler = cmdQuit, \
440         .opts = NULL, \
441         .info = info_quit, \
442         .flags = VSH_CMD_FLAG_NOCONNECT \
443     }
444 
445 #define VSH_CMD_SELF_TEST \
446     { \
447         .name = "self-test", \
448         .handler = cmdSelfTest, \
449         .opts = opts_selftest, \
450         .info = info_selftest, \
451         .flags = VSH_CMD_FLAG_NOCONNECT | VSH_CMD_FLAG_HIDDEN, \
452     }
453 
454 #define VSH_CMD_COMPLETE \
455     { \
456         .name = "complete", \
457         .handler = cmdComplete, \
458         .opts = opts_complete, \
459         .info = info_complete, \
460         .flags = VSH_CMD_FLAG_NOCONNECT | VSH_CMD_FLAG_HIDDEN, \
461     }
462 
463 
464 
465 /* readline */
466 char * vshReadline(vshControl *ctl, const char *prompt);
467 
468 void vshReadlineHistoryAdd(const char *cmd);
469 
470 /* Macros to help dealing with mutually exclusive options. */
471 
472 /* VSH_EXCLUSIVE_OPTIONS_EXPR:
473  *
474  * @NAME1: String containing the name of the option.
475  * @EXPR1: Expression to validate the variable (boolean variable)
476  * @NAME2: String containing the name of the option.
477  * @EXPR2: Expression to validate the variable (boolean variable)
478  *
479  * Reject mutually exclusive command options in virsh. Use the
480  * provided expression to check the variables.
481  *
482  * This helper does an early return and therefore it has to be called
483  * before anything that would require cleanup.
484  */
485 #define VSH_EXCLUSIVE_OPTIONS_EXPR(NAME1, EXPR1, NAME2, EXPR2) \
486     if ((EXPR1) && (EXPR2)) { \
487         vshError(ctl, _("Options --%s and --%s are mutually exclusive"), \
488                  NAME1, NAME2); \
489         return false; \
490     }
491 
492 /* VSH_EXCLUSIVE_OPTIONS:
493  *
494  * @NAME1: String containing the name of the option.
495  * @NAME2: String containing the name of the option.
496  *
497  * Reject mutually exclusive command options in virsh. Use the
498  * vshCommandOptBool call to request them.
499  *
500  * This helper does an early return and therefore it has to be called
501  * before anything that would require cleanup.
502  */
503 #define VSH_EXCLUSIVE_OPTIONS(NAME1, NAME2) \
504     VSH_EXCLUSIVE_OPTIONS_EXPR(NAME1, vshCommandOptBool(cmd, NAME1), \
505                                NAME2, vshCommandOptBool(cmd, NAME2))
506 
507 /* VSH_EXCLUSIVE_OPTIONS_VAR:
508  *
509  * @VARNAME1: Boolean variable containing the value of the option of same name
510  * @VARNAME2: Boolean variable containing the value of the option of same name
511  *
512  * Reject mutually exclusive command options in virsh. Check in variables that
513  * contain the value and have same name as the option.
514  *
515  * This helper does an early return and therefore it has to be called
516  * before anything that would require cleanup.
517  */
518 #define VSH_EXCLUSIVE_OPTIONS_VAR(VARNAME1, VARNAME2) \
519     VSH_EXCLUSIVE_OPTIONS_EXPR(#VARNAME1, VARNAME1, #VARNAME2, VARNAME2)
520 
521 /* Macros to help dealing with required options. */
522 
523 /* VSH_REQUIRE_OPTION_EXPR:
524  *
525  * @NAME1: String containing the name of the option.
526  * @EXPR1: Expression to validate the variable (boolean variable).
527  * @NAME2: String containing the name of required option.
528  * @EXPR2: Expression to validate the variable (boolean variable).
529  *
530  * Check if required command options in virsh was set.  Use the
531  * provided expression to check the variables.
532  *
533  * This helper does an early return and therefore it has to be called
534  * before anything that would require cleanup.
535  */
536 #define VSH_REQUIRE_OPTION_EXPR(NAME1, EXPR1, NAME2, EXPR2) \
537     do { \
538         if ((EXPR1) && !(EXPR2)) { \
539             vshError(ctl, _("Option --%s is required by option --%s"), \
540                      NAME2, NAME1); \
541             return false; \
542         } \
543     } while (0)
544 
545 /* VSH_REQUIRE_OPTION:
546  *
547  * @NAME1: String containing the name of the option.
548  * @NAME2: String containing the name of required option.
549  *
550  * Check if required command options in virsh was set.  Use the
551  * vshCommandOptBool call to request them.
552  *
553  * This helper does an early return and therefore it has to be called
554  * before anything that would require cleanup.
555  */
556 #define VSH_REQUIRE_OPTION(NAME1, NAME2) \
557     VSH_REQUIRE_OPTION_EXPR(NAME1, vshCommandOptBool(cmd, NAME1), \
558                             NAME2, vshCommandOptBool(cmd, NAME2))
559 
560 /* VSH_REQUIRE_OPTION_VAR:
561  *
562  * @VARNAME1: Boolean variable containing the value of the option of same name.
563  * @VARNAME2: Boolean variable containing the value of required option of
564  *            same name.
565  *
566  * Check if required command options in virsh was set.  Check in variables
567  * that contain the value and have same name as the option.
568  *
569  * This helper does an early return and therefore it has to be called
570  * before anything that would require cleanup.
571  */
572 #define VSH_REQUIRE_OPTION_VAR(VARNAME1, VARNAME2) \
573     VSH_REQUIRE_OPTION_EXPR(#VARNAME1, VARNAME1, #VARNAME2, VARNAME2)
574