Merge remote-tracking branch 'remotes/berrange/tags/pull-qcrypto-2016-03-17-3' into...
[sdk/emulator/qemu.git] / qemu-io.c
1 /*
2  * Command line utility to exercise the QEMU I/O path.
3  *
4  * Copyright (C) 2009 Red Hat, Inc.
5  * Copyright (c) 2003-2005 Silicon Graphics, Inc.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or later.
8  * See the COPYING file in the top-level directory.
9  */
10 #include "qemu/osdep.h"
11 #include <getopt.h>
12 #include <libgen.h>
13
14 #include "qemu-io.h"
15 #include "qemu/error-report.h"
16 #include "qemu/main-loop.h"
17 #include "qemu/option.h"
18 #include "qemu/config-file.h"
19 #include "qemu/readline.h"
20 #include "qapi/qmp/qstring.h"
21 #include "qom/object_interfaces.h"
22 #include "sysemu/block-backend.h"
23 #include "block/block_int.h"
24 #include "trace/control.h"
25
26 #define CMD_NOFILE_OK   0x01
27
28 static char *progname;
29
30 static BlockBackend *qemuio_blk;
31
32 /* qemu-io commands passed using -c */
33 static int ncmdline;
34 static char **cmdline;
35 static bool imageOpts;
36
37 static ReadLineState *readline_state;
38
39 static int close_f(BlockBackend *blk, int argc, char **argv)
40 {
41     blk_unref(qemuio_blk);
42     qemuio_blk = NULL;
43     return 0;
44 }
45
46 static const cmdinfo_t close_cmd = {
47     .name       = "close",
48     .altname    = "c",
49     .cfunc      = close_f,
50     .oneline    = "close the current open file",
51 };
52
53 static int openfile(char *name, int flags, QDict *opts)
54 {
55     Error *local_err = NULL;
56     BlockDriverState *bs;
57
58     if (qemuio_blk) {
59         error_report("file open already, try 'help close'");
60         QDECREF(opts);
61         return 1;
62     }
63
64     qemuio_blk = blk_new_open(name, NULL, opts, flags, &local_err);
65     if (!qemuio_blk) {
66         error_reportf_err(local_err, "can't open%s%s: ",
67                           name ? " device " : "", name ?: "");
68         return 1;
69     }
70
71     bs = blk_bs(qemuio_blk);
72     if (bdrv_is_encrypted(bs)) {
73         char password[256];
74         printf("Disk image '%s' is encrypted.\n", name);
75         if (qemu_read_password(password, sizeof(password)) < 0) {
76             error_report("No password given");
77             goto error;
78         }
79         if (bdrv_set_key(bs, password) < 0) {
80             error_report("invalid password");
81             goto error;
82         }
83     }
84
85
86     return 0;
87
88  error:
89     blk_unref(qemuio_blk);
90     qemuio_blk = NULL;
91     return 1;
92 }
93
94 static void open_help(void)
95 {
96     printf(
97 "\n"
98 " opens a new file in the requested mode\n"
99 "\n"
100 " Example:\n"
101 " 'open -Cn /tmp/data' - creates/opens data file read-write and uncached\n"
102 "\n"
103 " Opens a file for subsequent use by all of the other qemu-io commands.\n"
104 " -r, -- open file read-only\n"
105 " -s, -- use snapshot file\n"
106 " -n, -- disable host cache\n"
107 " -o, -- options to be given to the block driver"
108 "\n");
109 }
110
111 static int open_f(BlockBackend *blk, int argc, char **argv);
112
113 static const cmdinfo_t open_cmd = {
114     .name       = "open",
115     .altname    = "o",
116     .cfunc      = open_f,
117     .argmin     = 1,
118     .argmax     = -1,
119     .flags      = CMD_NOFILE_OK,
120     .args       = "[-Crsn] [-o options] [path]",
121     .oneline    = "open the file specified by path",
122     .help       = open_help,
123 };
124
125 static QemuOptsList empty_opts = {
126     .name = "drive",
127     .merge_lists = true,
128     .head = QTAILQ_HEAD_INITIALIZER(empty_opts.head),
129     .desc = {
130         /* no elements => accept any params */
131         { /* end of list */ }
132     },
133 };
134
135 static int open_f(BlockBackend *blk, int argc, char **argv)
136 {
137     int flags = 0;
138     int readonly = 0;
139     int c;
140     QemuOpts *qopts;
141     QDict *opts;
142
143     while ((c = getopt(argc, argv, "snrgo:")) != -1) {
144         switch (c) {
145         case 's':
146             flags |= BDRV_O_SNAPSHOT;
147             break;
148         case 'n':
149             flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
150             break;
151         case 'r':
152             readonly = 1;
153             break;
154         case 'o':
155             if (imageOpts) {
156                 printf("--image-opts and 'open -o' are mutually exclusive\n");
157                 return 0;
158             }
159             if (!qemu_opts_parse_noisily(&empty_opts, optarg, false)) {
160                 qemu_opts_reset(&empty_opts);
161                 return 0;
162             }
163             break;
164         default:
165             qemu_opts_reset(&empty_opts);
166             return qemuio_command_usage(&open_cmd);
167         }
168     }
169
170     if (!readonly) {
171         flags |= BDRV_O_RDWR;
172     }
173
174     if (imageOpts && (optind == argc - 1)) {
175         if (!qemu_opts_parse_noisily(&empty_opts, argv[optind], false)) {
176             qemu_opts_reset(&empty_opts);
177             return 0;
178         }
179         optind++;
180     }
181
182     qopts = qemu_opts_find(&empty_opts, NULL);
183     opts = qopts ? qemu_opts_to_qdict(qopts, NULL) : NULL;
184     qemu_opts_reset(&empty_opts);
185
186     if (optind == argc - 1) {
187         return openfile(argv[optind], flags, opts);
188     } else if (optind == argc) {
189         return openfile(NULL, flags, opts);
190     } else {
191         QDECREF(opts);
192         return qemuio_command_usage(&open_cmd);
193     }
194 }
195
196 static int quit_f(BlockBackend *blk, int argc, char **argv)
197 {
198     return 1;
199 }
200
201 static const cmdinfo_t quit_cmd = {
202     .name       = "quit",
203     .altname    = "q",
204     .cfunc      = quit_f,
205     .argmin     = -1,
206     .argmax     = -1,
207     .flags      = CMD_FLAG_GLOBAL,
208     .oneline    = "exit the program",
209 };
210
211 static void usage(const char *name)
212 {
213     printf(
214 "Usage: %s [-h] [-V] [-rsnm] [-f FMT] [-c STRING] ... [file]\n"
215 "QEMU Disk exerciser\n"
216 "\n"
217 "  --object OBJECTDEF   define an object such as 'secret' for\n"
218 "                       passwords and/or encryption keys\n"
219 "  -c, --cmd STRING     execute command with its arguments\n"
220 "                       from the given string\n"
221 "  -f, --format FMT     specifies the block driver to use\n"
222 "  -r, --read-only      export read-only\n"
223 "  -s, --snapshot       use snapshot file\n"
224 "  -n, --nocache        disable host cache\n"
225 "  -m, --misalign       misalign allocations for O_DIRECT\n"
226 "  -k, --native-aio     use kernel AIO implementation (on Linux only)\n"
227 "  -t, --cache=MODE     use the given cache mode for the image\n"
228 "  -T, --trace FILE     enable trace events listed in the given file\n"
229 "  -h, --help           display this help and exit\n"
230 "  -V, --version        output version information and exit\n"
231 "\n"
232 "See '%s -c help' for information on available commands."
233 "\n",
234     name, name);
235 }
236
237 static char *get_prompt(void)
238 {
239     static char prompt[FILENAME_MAX + 2 /*"> "*/ + 1 /*"\0"*/ ];
240
241     if (!prompt[0]) {
242         snprintf(prompt, sizeof(prompt), "%s> ", progname);
243     }
244
245     return prompt;
246 }
247
248 static void GCC_FMT_ATTR(2, 3) readline_printf_func(void *opaque,
249                                                     const char *fmt, ...)
250 {
251     va_list ap;
252     va_start(ap, fmt);
253     vprintf(fmt, ap);
254     va_end(ap);
255 }
256
257 static void readline_flush_func(void *opaque)
258 {
259     fflush(stdout);
260 }
261
262 static void readline_func(void *opaque, const char *str, void *readline_opaque)
263 {
264     char **line = readline_opaque;
265     *line = g_strdup(str);
266 }
267
268 static void completion_match(const char *cmd, void *opaque)
269 {
270     readline_add_completion(readline_state, cmd);
271 }
272
273 static void readline_completion_func(void *opaque, const char *str)
274 {
275     readline_set_completion_index(readline_state, strlen(str));
276     qemuio_complete_command(str, completion_match, NULL);
277 }
278
279 static char *fetchline_readline(void)
280 {
281     char *line = NULL;
282
283     readline_start(readline_state, get_prompt(), 0, readline_func, &line);
284     while (!line) {
285         int ch = getchar();
286         if (ch == EOF) {
287             break;
288         }
289         readline_handle_byte(readline_state, ch);
290     }
291     return line;
292 }
293
294 #define MAXREADLINESZ 1024
295 static char *fetchline_fgets(void)
296 {
297     char *p, *line = g_malloc(MAXREADLINESZ);
298
299     if (!fgets(line, MAXREADLINESZ, stdin)) {
300         g_free(line);
301         return NULL;
302     }
303
304     p = line + strlen(line);
305     if (p != line && p[-1] == '\n') {
306         p[-1] = '\0';
307     }
308
309     return line;
310 }
311
312 static char *fetchline(void)
313 {
314     if (readline_state) {
315         return fetchline_readline();
316     } else {
317         return fetchline_fgets();
318     }
319 }
320
321 static void prep_fetchline(void *opaque)
322 {
323     int *fetchable = opaque;
324
325     qemu_set_fd_handler(STDIN_FILENO, NULL, NULL, NULL);
326     *fetchable= 1;
327 }
328
329 static void command_loop(void)
330 {
331     int i, done = 0, fetchable = 0, prompted = 0;
332     char *input;
333
334     for (i = 0; !done && i < ncmdline; i++) {
335         done = qemuio_command(qemuio_blk, cmdline[i]);
336     }
337     if (cmdline) {
338         g_free(cmdline);
339         return;
340     }
341
342     while (!done) {
343         if (!prompted) {
344             printf("%s", get_prompt());
345             fflush(stdout);
346             qemu_set_fd_handler(STDIN_FILENO, prep_fetchline, NULL, &fetchable);
347             prompted = 1;
348         }
349
350         main_loop_wait(false);
351
352         if (!fetchable) {
353             continue;
354         }
355
356         input = fetchline();
357         if (input == NULL) {
358             break;
359         }
360         done = qemuio_command(qemuio_blk, input);
361         g_free(input);
362
363         prompted = 0;
364         fetchable = 0;
365     }
366     qemu_set_fd_handler(STDIN_FILENO, NULL, NULL, NULL);
367 }
368
369 static void add_user_command(char *optarg)
370 {
371     cmdline = g_renew(char *, cmdline, ++ncmdline);
372     cmdline[ncmdline-1] = optarg;
373 }
374
375 static void reenable_tty_echo(void)
376 {
377     qemu_set_tty_echo(STDIN_FILENO, true);
378 }
379
380 enum {
381     OPTION_OBJECT = 256,
382     OPTION_IMAGE_OPTS = 257,
383 };
384
385 static QemuOptsList qemu_object_opts = {
386     .name = "object",
387     .implied_opt_name = "qom-type",
388     .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
389     .desc = {
390         { }
391     },
392 };
393
394
395 static QemuOptsList file_opts = {
396     .name = "file",
397     .implied_opt_name = "file",
398     .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
399     .desc = {
400         /* no elements => accept any params */
401         { /* end of list */ }
402     },
403 };
404
405 int main(int argc, char **argv)
406 {
407     int readonly = 0;
408     const char *sopt = "hVc:d:f:rsnmgkt:T:";
409     const struct option lopt[] = {
410         { "help", no_argument, NULL, 'h' },
411         { "version", no_argument, NULL, 'V' },
412         { "offset", required_argument, NULL, 'o' },
413         { "cmd", required_argument, NULL, 'c' },
414         { "format", required_argument, NULL, 'f' },
415         { "read-only", no_argument, NULL, 'r' },
416         { "snapshot", no_argument, NULL, 's' },
417         { "nocache", no_argument, NULL, 'n' },
418         { "misalign", no_argument, NULL, 'm' },
419         { "native-aio", no_argument, NULL, 'k' },
420         { "discard", required_argument, NULL, 'd' },
421         { "cache", required_argument, NULL, 't' },
422         { "trace", required_argument, NULL, 'T' },
423         { "object", required_argument, NULL, OPTION_OBJECT },
424         { "image-opts", no_argument, NULL, OPTION_IMAGE_OPTS },
425         { NULL, 0, NULL, 0 }
426     };
427     int c;
428     int opt_index = 0;
429     int flags = BDRV_O_UNMAP;
430     Error *local_error = NULL;
431     QDict *opts = NULL;
432     const char *format = NULL;
433
434 #ifdef CONFIG_POSIX
435     signal(SIGPIPE, SIG_IGN);
436 #endif
437
438     progname = basename(argv[0]);
439     qemu_init_exec_dir(argv[0]);
440
441     module_call_init(MODULE_INIT_QOM);
442     qemu_add_opts(&qemu_object_opts);
443     bdrv_init();
444
445     while ((c = getopt_long(argc, argv, sopt, lopt, &opt_index)) != -1) {
446         switch (c) {
447         case 's':
448             flags |= BDRV_O_SNAPSHOT;
449             break;
450         case 'n':
451             flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
452             break;
453         case 'd':
454             if (bdrv_parse_discard_flags(optarg, &flags) < 0) {
455                 error_report("Invalid discard option: %s", optarg);
456                 exit(1);
457             }
458             break;
459         case 'f':
460             format = optarg;
461             break;
462         case 'c':
463             add_user_command(optarg);
464             break;
465         case 'r':
466             readonly = 1;
467             break;
468         case 'm':
469             qemuio_misalign = true;
470             break;
471         case 'k':
472             flags |= BDRV_O_NATIVE_AIO;
473             break;
474         case 't':
475             if (bdrv_parse_cache_flags(optarg, &flags) < 0) {
476                 error_report("Invalid cache option: %s", optarg);
477                 exit(1);
478             }
479             break;
480         case 'T':
481             if (!trace_init_backends()) {
482                 exit(1); /* error message will have been printed */
483             }
484             break;
485         case 'V':
486             printf("%s version %s\n", progname, QEMU_VERSION);
487             exit(0);
488         case 'h':
489             usage(progname);
490             exit(0);
491         case OPTION_OBJECT: {
492             QemuOpts *qopts;
493             qopts = qemu_opts_parse_noisily(&qemu_object_opts,
494                                             optarg, true);
495             if (!qopts) {
496                 exit(1);
497             }
498         }   break;
499         case OPTION_IMAGE_OPTS:
500             imageOpts = true;
501             break;
502         default:
503             usage(progname);
504             exit(1);
505         }
506     }
507
508     if ((argc - optind) > 1) {
509         usage(progname);
510         exit(1);
511     }
512
513     if (format && imageOpts) {
514         error_report("--image-opts and -f are mutually exclusive");
515         exit(1);
516     }
517
518     if (qemu_init_main_loop(&local_error)) {
519         error_report_err(local_error);
520         exit(1);
521     }
522
523     if (qemu_opts_foreach(&qemu_object_opts,
524                           user_creatable_add_opts_foreach,
525                           NULL, &local_error)) {
526         error_report_err(local_error);
527         exit(1);
528     }
529
530     /* initialize commands */
531     qemuio_add_command(&quit_cmd);
532     qemuio_add_command(&open_cmd);
533     qemuio_add_command(&close_cmd);
534
535     if (isatty(STDIN_FILENO)) {
536         readline_state = readline_init(readline_printf_func,
537                                        readline_flush_func,
538                                        NULL,
539                                        readline_completion_func);
540         qemu_set_tty_echo(STDIN_FILENO, false);
541         atexit(reenable_tty_echo);
542     }
543
544     /* open the device */
545     if (!readonly) {
546         flags |= BDRV_O_RDWR;
547     }
548
549     if ((argc - optind) == 1) {
550         if (imageOpts) {
551             QemuOpts *qopts = NULL;
552             qopts = qemu_opts_parse_noisily(&file_opts, argv[optind], false);
553             if (!qopts) {
554                 exit(1);
555             }
556             opts = qemu_opts_to_qdict(qopts, NULL);
557             openfile(NULL, flags, opts);
558         } else {
559             if (format) {
560                 opts = qdict_new();
561                 qdict_put(opts, "driver", qstring_from_str(format));
562             }
563             openfile(argv[optind], flags, opts);
564         }
565     }
566     command_loop();
567
568     /*
569      * Make sure all outstanding requests complete before the program exits.
570      */
571     bdrv_drain_all();
572
573     blk_unref(qemuio_blk);
574     g_free(readline_state);
575     return 0;
576 }