xref: /openbsd-src/usr.sbin/vmctl/main.c (revision c90a81c56dcebd6a1b73fe4aff9b03385b8e63b3)
1 /*	$OpenBSD: main.c,v 1.52 2018/12/14 07:56:17 jmc Exp $	*/
2 
3 /*
4  * Copyright (c) 2015 Reyk Floeter <reyk@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/queue.h>
22 #include <sys/un.h>
23 
24 #include <machine/vmmvar.h>
25 
26 #include <err.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <limits.h>
32 #include <string.h>
33 #include <syslog.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <util.h>
37 #include <imsg.h>
38 
39 #include "vmd.h"
40 #include "virtio.h"
41 #include "proc.h"
42 #include "vmctl.h"
43 
44 #define RAW_FMT		"raw"
45 #define QCOW2_FMT	"qcow2"
46 
47 static const char	*socket_name = SOCKET_NAME;
48 static int		 ctl_sock = -1;
49 static int		 tty_autoconnect = 0;
50 
51 __dead void	 usage(void);
52 __dead void	 ctl_usage(struct ctl_command *);
53 
54 int		 vmm_action(struct parse_result *);
55 
56 int		 ctl_console(struct parse_result *, int, char *[]);
57 int		 ctl_convert(const char *, const char *, int, size_t);
58 int		 ctl_create(struct parse_result *, int, char *[]);
59 int		 ctl_load(struct parse_result *, int, char *[]);
60 int		 ctl_log(struct parse_result *, int, char *[]);
61 int		 ctl_reload(struct parse_result *, int, char *[]);
62 int		 ctl_reset(struct parse_result *, int, char *[]);
63 int		 ctl_start(struct parse_result *, int, char *[]);
64 int		 ctl_status(struct parse_result *, int, char *[]);
65 int		 ctl_stop(struct parse_result *, int, char *[]);
66 int		 ctl_waitfor(struct parse_result *, int, char *[]);
67 int		 ctl_pause(struct parse_result *, int, char *[]);
68 int		 ctl_unpause(struct parse_result *, int, char *[]);
69 int		 ctl_send(struct parse_result *, int, char *[]);
70 int		 ctl_receive(struct parse_result *, int, char *[]);
71 
72 struct ctl_command ctl_commands[] = {
73 	{ "console",	CMD_CONSOLE,	ctl_console,	"id" },
74 	{ "create",	CMD_CREATE,	ctl_create,
75 		"disk [-b base | -i disk] [-s size]", 1 },
76 	{ "load",	CMD_LOAD,	ctl_load,	"filename" },
77 	{ "log",	CMD_LOG,	ctl_log,	"[brief | verbose]" },
78 	{ "pause",	CMD_PAUSE,	ctl_pause,	"id" },
79 	{ "receive",	CMD_RECEIVE,	ctl_receive,	"name" ,	1},
80 	{ "reload",	CMD_RELOAD,	ctl_reload,	"" },
81 	{ "reset",	CMD_RESET,	ctl_reset,	"[all | switches | vms]" },
82 	{ "send",	CMD_SEND,	ctl_send,	"id",	1},
83 	{ "show",	CMD_STATUS,	ctl_status,	"[id]" },
84 	{ "start",	CMD_START,	ctl_start,	"name"
85 	    " [-cL] [-B device] [-b path] [-d disk] [-i count]\n"
86 	    "\t\t[-m size] [-n switch] [-r path] [-t name]" },
87 	{ "status",	CMD_STATUS,	ctl_status,	"[id]" },
88 	{ "stop",	CMD_STOP,	ctl_stop,	"[id | -a] [-fw]" },
89 	{ "unpause",	CMD_UNPAUSE,	ctl_unpause,	"id" },
90 	{ "wait",	CMD_WAITFOR,	ctl_waitfor,	"id" },
91 	{ NULL }
92 };
93 
94 __dead void
95 usage(void)
96 {
97 	extern char	*__progname;
98 	int		 i;
99 
100 	fprintf(stderr, "usage:\t%s [-v] command [arg ...]\n",
101 	    __progname);
102 	for (i = 0; ctl_commands[i].name != NULL; i++) {
103 		fprintf(stderr, "\t%s %s %s\n", __progname,
104 		    ctl_commands[i].name, ctl_commands[i].usage);
105 	}
106 	exit(1);
107 }
108 
109 __dead void
110 ctl_usage(struct ctl_command *ctl)
111 {
112 	extern char	*__progname;
113 
114 	fprintf(stderr, "usage:\t%s [-v] %s %s\n", __progname,
115 	    ctl->name, ctl->usage);
116 	exit(1);
117 }
118 
119 int
120 main(int argc, char *argv[])
121 {
122 	int	 ch, verbose = 1;
123 
124 	while ((ch = getopt(argc, argv, "v")) != -1) {
125 		switch (ch) {
126 		case 'v':
127 			verbose = 2;
128 			break;
129 		default:
130 			usage();
131 			/* NOTREACHED */
132 		}
133 	}
134 	argc -= optind;
135 	argv += optind;
136 	optreset = 1;
137 	optind = 1;
138 
139 	if (argc < 1)
140 		usage();
141 
142 	log_init(verbose, LOG_DAEMON);
143 
144 	return (parse(argc, argv));
145 }
146 
147 int
148 parse(int argc, char *argv[])
149 {
150 	struct ctl_command	*ctl = NULL;
151 	struct parse_result	 res;
152 	int			 i;
153 
154 	memset(&res, 0, sizeof(res));
155 	res.nifs = -1;
156 
157 	for (i = 0; ctl_commands[i].name != NULL; i++) {
158 		if (strncmp(ctl_commands[i].name,
159 		    argv[0], strlen(argv[0])) == 0) {
160 			if (ctl != NULL) {
161 				fprintf(stderr,
162 				    "ambiguous argument: %s\n", argv[0]);
163 				usage();
164 			}
165 			ctl = &ctl_commands[i];
166 		}
167 	}
168 
169 	if (ctl == NULL) {
170 		fprintf(stderr, "unknown argument: %s\n", argv[0]);
171 		usage();
172 	}
173 
174 	res.action = ctl->action;
175 	res.ctl = ctl;
176 
177 	if (!ctl->has_pledge) {
178 		/* pledge(2) default if command doesn't have its own pledge */
179 		if (pledge("stdio rpath exec unix getpw unveil", NULL) == -1)
180 			err(1, "pledge");
181 	}
182 	if (ctl->main(&res, argc, argv) != 0)
183 		exit(1);
184 
185 	if (ctl_sock != -1) {
186 		close(ibuf->fd);
187 		free(ibuf);
188 	}
189 
190 	return (0);
191 }
192 
193 int
194 vmmaction(struct parse_result *res)
195 {
196 	struct sockaddr_un	 sun;
197 	struct imsg		 imsg;
198 	int			 done = 0;
199 	int			 n;
200 	int			 ret, action;
201 	unsigned int		 flags;
202 
203 	if (ctl_sock == -1) {
204 		if (unveil(SOCKET_NAME, "r") == -1)
205 			err(1, "unveil");
206 		if ((ctl_sock = socket(AF_UNIX,
207 		    SOCK_STREAM|SOCK_CLOEXEC, 0)) == -1)
208 			err(1, "socket");
209 
210 		memset(&sun, 0, sizeof(sun));
211 		sun.sun_family = AF_UNIX;
212 		strlcpy(sun.sun_path, socket_name, sizeof(sun.sun_path));
213 
214 		if (connect(ctl_sock,
215 		    (struct sockaddr *)&sun, sizeof(sun)) == -1)
216 			err(1, "connect: %s", socket_name);
217 
218 		if ((ibuf = malloc(sizeof(struct imsgbuf))) == NULL)
219 			err(1, "malloc");
220 		imsg_init(ibuf, ctl_sock);
221 	}
222 
223 	switch (res->action) {
224 	case CMD_START:
225 		ret = vm_start(res->id, res->name, res->size, res->nifs,
226 		    res->nets, res->ndisks, res->disks, res->disktypes,
227 		    res->path, res->isopath, res->instance, res->bootdevice);
228 		if (ret) {
229 			errno = ret;
230 			err(1, "start VM operation failed");
231 		}
232 		break;
233 	case CMD_STOP:
234 		terminate_vm(res->id, res->name, res->flags);
235 		break;
236 	case CMD_STATUS:
237 	case CMD_CONSOLE:
238 	case CMD_STOPALL:
239 		get_info_vm(res->id, res->name, res->action, res->flags);
240 		break;
241 	case CMD_LOAD:
242 		imsg_compose(ibuf, IMSG_VMDOP_LOAD, 0, 0, -1,
243 		    res->path, strlen(res->path) + 1);
244 		break;
245 	case CMD_LOG:
246 		imsg_compose(ibuf, IMSG_CTL_VERBOSE, 0, 0, -1,
247 		    &res->verbose, sizeof(res->verbose));
248 		break;
249 	case CMD_RELOAD:
250 		imsg_compose(ibuf, IMSG_VMDOP_RELOAD, 0, 0, -1, NULL, 0);
251 		break;
252 	case CMD_RESET:
253 		imsg_compose(ibuf, IMSG_CTL_RESET, 0, 0, -1,
254 		    &res->mode, sizeof(res->mode));
255 		break;
256 	case CMD_WAITFOR:
257 		waitfor_vm(res->id, res->name);
258 		break;
259 	case CMD_PAUSE:
260 		pause_vm(res->id, res->name);
261 		break;
262 	case CMD_UNPAUSE:
263 		unpause_vm(res->id, res->name);
264 		break;
265 	case CMD_SEND:
266 		send_vm(res->id, res->name);
267 		done = 1;
268 		break;
269 	case CMD_RECEIVE:
270 		vm_receive(res->id, res->name);
271 		break;
272 	case CMD_CREATE:
273 	case NONE:
274 		/* The action is not expected here */
275 		errx(1, "invalid action %u", res->action);
276 		break;
277 	}
278 
279 	action = res->action;
280 	flags = res->flags;
281 	parse_free(res);
282 
283 	while (ibuf->w.queued)
284 		if (msgbuf_write(&ibuf->w) <= 0 && errno != EAGAIN)
285 			err(1, "write error");
286 
287 	while (!done) {
288 		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
289 			errx(1, "imsg_read error");
290 		if (n == 0)
291 			errx(1, "pipe closed");
292 
293 		while (!done) {
294 			if ((n = imsg_get(ibuf, &imsg)) == -1)
295 				errx(1, "imsg_get error");
296 			if (n == 0)
297 				break;
298 
299 			if (imsg.hdr.type == IMSG_CTL_FAIL) {
300 				if (IMSG_DATA_SIZE(&imsg) == sizeof(ret))
301 					memcpy(&ret, imsg.data, sizeof(ret));
302 				else
303 					ret = 0;
304 				if (ret != 0) {
305 					memcpy(&ret, imsg.data, sizeof(ret));
306 					errno = ret;
307 					err(1, "command failed");
308 				} else
309 					errx(1, "command failed");
310 			}
311 
312 			ret = 0;
313 			switch (action) {
314 			case CMD_START:
315 				done = vm_start_complete(&imsg, &ret,
316 				    tty_autoconnect);
317 				break;
318 			case CMD_WAITFOR:
319 				flags = VMOP_WAIT;
320 				/* FALLTHROUGH */
321 			case CMD_STOP:
322 				done = terminate_vm_complete(&imsg, &ret,
323 				    flags);
324 				break;
325 			case CMD_CONSOLE:
326 			case CMD_STATUS:
327 			case CMD_STOPALL:
328 				done = add_info(&imsg, &ret);
329 				break;
330 			case CMD_PAUSE:
331 				done = pause_vm_complete(&imsg, &ret);
332 				break;
333 			case CMD_RECEIVE:
334 				done = vm_start_complete(&imsg, &ret, 0);
335 				break;
336 			case CMD_UNPAUSE:
337 				done = unpause_vm_complete(&imsg, &ret);
338 				break;
339 			default:
340 				done = 1;
341 				break;
342 			}
343 
344 			imsg_free(&imsg);
345 		}
346 	}
347 
348 	if (ret)
349 		return (1);
350 	else
351 		return (0);
352 }
353 
354 void
355 parse_free(struct parse_result *res)
356 {
357 	size_t	 i;
358 
359 	free(res->name);
360 	free(res->path);
361 	free(res->isopath);
362 	free(res->instance);
363 	for (i = 0; i < res->ndisks; i++)
364 		free(res->disks[i]);
365 	free(res->disks);
366 	free(res->disktypes);
367 	memset(res, 0, sizeof(*res));
368 }
369 
370 int
371 parse_ifs(struct parse_result *res, char *word, int val)
372 {
373 	const char	*error;
374 
375 	if (word != NULL) {
376 		val = strtonum(word, 0, INT_MAX, &error);
377 		if (error != NULL)  {
378 			warnx("invalid count \"%s\": %s", word, error);
379 			return (-1);
380 		}
381 	}
382 	res->nifs = val;
383 
384 	return (0);
385 }
386 
387 int
388 parse_network(struct parse_result *res, char *word)
389 {
390 	char		**nets;
391 	char		*s;
392 
393 	if ((nets = reallocarray(res->nets, res->nnets + 1,
394 	    sizeof(char *))) == NULL) {
395 		warn("reallocarray");
396 		return (-1);
397 	}
398 	if ((s = strdup(word)) == NULL) {
399 		warn("strdup");
400 		return (-1);
401 	}
402 	nets[res->nnets] = s;
403 	res->nets = nets;
404 	res->nnets++;
405 
406 	return (0);
407 }
408 
409 int
410 parse_size(struct parse_result *res, char *word, long long val)
411 {
412 	if (word != NULL) {
413 		if (scan_scaled(word, &val) != 0) {
414 			warn("invalid size: %s", word);
415 			return (-1);
416 		}
417 	}
418 
419 	if (val < (1024 * 1024)) {
420 		warnx("size must be at least one megabyte");
421 		return (-1);
422 	} else
423 		res->size = val / 1024 / 1024;
424 
425 	if ((res->size * 1024 * 1024) != val)
426 		warnx("size rounded to %lld megabytes", res->size);
427 
428 	return (0);
429 }
430 
431 int
432 parse_disktype(const char *s, const char **ret)
433 {
434 	char		 buf[BUFSIZ];
435 	const char	*ext;
436 	int		 fd;
437 	ssize_t		 len;
438 
439 	*ret = s;
440 
441 	/* Try to parse the explicit format (qcow2:disk.qc2) */
442 	if (strstr(s, RAW_FMT) == s && *(s + strlen(RAW_FMT)) == ':') {
443 		*ret = s + strlen(RAW_FMT) + 1;
444 		return (VMDF_RAW);
445 	}
446 	if (strstr(s, QCOW2_FMT) == s && *(s + strlen(QCOW2_FMT)) == ':') {
447 		*ret = s + strlen(QCOW2_FMT) + 1;
448 		return (VMDF_QCOW2);
449 	}
450 
451 	/* Or try to derive the format from the file signature */
452 	if ((fd = open(s, O_RDONLY)) != -1) {
453 		len = read(fd, buf, sizeof(buf));
454 		close(fd);
455 
456 		if (len >= (ssize_t)strlen(VM_MAGIC_QCOW) &&
457 		    strncmp(buf, VM_MAGIC_QCOW,
458 		    strlen(VM_MAGIC_QCOW)) == 0) {
459 			/* Return qcow2, the version will be checked later */
460 			return (VMDF_QCOW2);
461 		}
462 	}
463 
464 	/*
465 	 * Use the extension as a last option.  This is needed for
466 	 * 'vmctl create' as the file, and the signature, doesn't
467 	 * exist yet.
468 	 */
469 	if ((ext = strrchr(s, '.')) != NULL && *(++ext) != '\0') {
470 		if (strcasecmp(ext, RAW_FMT) == 0)
471 			return (VMDF_RAW);
472 		else if (strcasecmp(ext, QCOW2_FMT) == 0)
473 			return (VMDF_QCOW2);
474 	}
475 
476 	/* Fallback to raw */
477 	return (VMDF_RAW);
478 }
479 
480 int
481 parse_disk(struct parse_result *res, char *word, int type)
482 {
483 	char		**disks;
484 	int		*disktypes;
485 	char		*s;
486 
487 	if ((disks = reallocarray(res->disks, res->ndisks + 1,
488 	    sizeof(char *))) == NULL) {
489 		warn("reallocarray");
490 		return (-1);
491 	}
492 	if ((disktypes = reallocarray(res->disktypes, res->ndisks + 1,
493 	    sizeof(int))) == NULL) {
494 		warn("reallocarray");
495 		return -1;
496 	}
497 	if ((s = strdup(word)) == NULL) {
498 		warn("strdup");
499 		return (-1);
500 	}
501 	disks[res->ndisks] = s;
502 	disktypes[res->ndisks] = type;
503 	res->disks = disks;
504 	res->disktypes = disktypes;
505 	res->ndisks++;
506 
507 	return (0);
508 }
509 
510 int
511 parse_vmid(struct parse_result *res, char *word, int needname)
512 {
513 	const char	*error;
514 	uint32_t	 id;
515 
516 	if (word == NULL) {
517 		warnx("missing vmid argument");
518 		return (-1);
519 	}
520 	if (*word == '-') {
521 		/* don't print a warning to allow command line options */
522 		return (-1);
523 	}
524 	id = strtonum(word, 0, UINT32_MAX, &error);
525 	if (error == NULL) {
526 		if (needname) {
527 			warnx("invalid vm name");
528 			return (-1);
529 		} else {
530 			res->id = id;
531 			res->name = NULL;
532 		}
533 	} else {
534 		if (strlen(word) >= VMM_MAX_NAME_LEN) {
535 			warnx("name too long");
536 			return (-1);
537 		}
538 		res->id = 0;
539 		if ((res->name = strdup(word)) == NULL)
540 			errx(1, "strdup");
541 	}
542 
543 	return (0);
544 }
545 
546 int
547 parse_instance(struct parse_result *res, char *word)
548 {
549 	if (strlen(word) >= VMM_MAX_NAME_LEN) {
550 		warnx("instance vm name too long");
551 		return (-1);
552 	}
553 	res->id = 0;
554 	if ((res->instance = strdup(word)) == NULL)
555 		errx(1, "strdup");
556 
557 	return (0);
558 }
559 
560 int
561 ctl_create(struct parse_result *res, int argc, char *argv[])
562 {
563 	int		 ch, ret, type;
564 	const char	*disk, *format, *base, *input;
565 
566 	if (argc < 2)
567 		ctl_usage(res->ctl);
568 
569 	base = input = NULL;
570 	type = parse_disktype(argv[1], &disk);
571 
572 	if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
573 		err(1, "pledge");
574 	if (unveil(disk, "rwc") == -1)
575 		err(1, "unveil");
576 
577 	argc--;
578 	argv++;
579 
580 	while ((ch = getopt(argc, argv, "b:i:s:")) != -1) {
581 		switch (ch) {
582 		case 'b':
583 			base = optarg;
584 			if (unveil(base, "r") == -1)
585 				err(1, "unveil");
586 			break;
587 		case 'i':
588 			input = optarg;
589 			if (unveil(input, "r") == -1)
590 				err(1, "unveil");
591 			break;
592 		case 's':
593 			if (parse_size(res, optarg, 0) != 0)
594 				errx(1, "invalid size: %s", optarg);
595 			break;
596 		default:
597 			ctl_usage(res->ctl);
598 			/* NOTREACHED */
599 		}
600 	}
601 
602 	if (input) {
603 		if (base && input)
604 			errx(1, "conflicting -b and -i arguments");
605 		return ctl_convert(input, disk, type, res->size);
606 	}
607 
608 	if (unveil(NULL, NULL))
609 		err(1, "unveil");
610 
611 	if (base && type != VMDF_QCOW2)
612 		errx(1, "base images require qcow2 disk format");
613 	if (res->size == 0 && !base) {
614 		fprintf(stderr, "could not create %s: missing size argument\n",
615 		    disk);
616 		ctl_usage(res->ctl);
617 	}
618 
619 	if ((ret = create_imagefile(type, disk, base, res->size, &format)) != 0) {
620 		errno = ret;
621 		err(1, "create imagefile operation failed");
622 	} else
623 		warnx("%s imagefile created", format);
624 
625 	return (0);
626 }
627 
628 int
629 ctl_convert(const char *srcfile, const char *dstfile, int dsttype, size_t dstsize)
630 {
631 	struct {
632 		int			 fd;
633 		int			 type;
634 		struct virtio_backing	 file;
635 		const char		*disk;
636 		off_t			 size;
637 	}	 src, dst;
638 	int		 ret;
639 	const char	*format, *errstr = NULL;
640 	uint8_t		*buf = NULL, *zerobuf = NULL;
641 	size_t		 buflen;
642 	ssize_t		 len, rlen;
643 	off_t		 off;
644 
645 	memset(&src, 0, sizeof(src));
646 	memset(&dst, 0, sizeof(dst));
647 
648 	src.type = parse_disktype(srcfile, &src.disk);
649 	dst.type = dsttype;
650 	dst.disk = dstfile;
651 
652 	if ((src.fd = open_imagefile(src.type, src.disk, O_RDONLY,
653 	    &src.file, &src.size)) == -1) {
654 		errstr = "failed to open source image file";
655 		goto done;
656 	}
657 
658 	/* We can only lock unveil after opening the disk and all base images */
659 	if (unveil(NULL, NULL))
660 		err(1, "unveil");
661 
662 	if (dstsize == 0)
663 		dstsize = src.size;
664 	else
665 		dstsize *= 1048576;
666 	if (dstsize < (size_t)src.size) {
667 		errstr = "size cannot be smaller than input disk size";
668 		goto done;
669 	}
670 
671 	/* align to megabytes */
672 	dst.size = ALIGNSZ(dstsize, 1048576);
673 
674 	if ((ret = create_imagefile(dst.type, dst.disk, NULL,
675 	   dst.size / 1048576, &format)) != 0) {
676 		errno = ret;
677 		errstr = "failed to create destination image file";
678 		goto done;
679 	}
680 
681 	if ((dst.fd = open_imagefile(dst.type, dst.disk, O_RDWR,
682 	    &dst.file, &dst.size)) == -1) {
683 		errstr = "failed to open destination image file";
684 		goto done;
685 	}
686 
687 	if (pledge("stdio", NULL) == -1)
688 		err(1, "pledge");
689 
690 	/*
691 	 * Use 64k buffers by default.  This could also be adjusted to
692 	 * the backend cluster size.
693 	 */
694 	buflen = 1 << 16;
695 	if ((buf = calloc(1, buflen)) == NULL ||
696 	    (zerobuf = calloc(1, buflen)) == NULL) {
697 		errstr = "failed to allocated buffers";
698 		goto done;
699 	}
700 
701 	for (off = 0; off < dst.size; off += len) {
702 		/* Read input from the source image */
703 		if (off < src.size) {
704 			len = MIN((off_t)buflen, src.size - off);
705 			if ((rlen = src.file.pread(src.file.p,
706 			    buf, (size_t)len, off)) != len) {
707 				errno = EIO;
708 				errstr = "failed to read from source";
709 				goto done;
710 			}
711 		} else
712 			len = 0;
713 
714 		/* and pad the remaining bytes */
715 		if (len < (ssize_t)buflen) {
716 			log_debug("%s: padding %zd zero bytes at offset %lld",
717 			    format, buflen - len, off + len);
718 			memset(buf + len, 0, buflen - len);
719 			len = buflen;
720 		}
721 
722 		/*
723 		 * No need to copy empty buffers.  This allows the backend,
724 		 * sparse files or QCOW2 images, to save space in the
725 		 * destination file.
726 		 */
727 		if (memcmp(buf, zerobuf, buflen) == 0)
728 			continue;
729 
730 		log_debug("%s: writing %zd of %lld bytes at offset %lld",
731 		    format, len, dst.size, off);
732 
733 		if ((rlen = dst.file.pwrite(dst.file.p,
734 		    buf, (size_t)len, off)) != len) {
735 			errno = EIO;
736 			errstr = "failed to write to destination";
737 			goto done;
738 		}
739 	}
740 
741 	if (dstsize < (size_t)dst.size)
742 		warnx("destination size rounded to %lld megabytes",
743 		    dst.size / 1048576);
744 
745  done:
746 	free(buf);
747 	free(zerobuf);
748 	if (src.file.p != NULL)
749 		src.file.close(src.file.p, 0);
750 	if (dst.file.p != NULL)
751 		dst.file.close(dst.file.p, 0);
752 	if (errstr != NULL)
753 		errx(1, "%s", errstr);
754 	else
755 		warnx("%s imagefile created", format);
756 
757 	return (0);
758 }
759 
760 int
761 ctl_status(struct parse_result *res, int argc, char *argv[])
762 {
763 	if (argc == 2) {
764 		if (parse_vmid(res, argv[1], 0) == -1)
765 			errx(1, "invalid id: %s", argv[1]);
766 	} else if (argc > 2)
767 		ctl_usage(res->ctl);
768 
769 	return (vmmaction(res));
770 }
771 
772 int
773 ctl_load(struct parse_result *res, int argc, char *argv[])
774 {
775 	if (argc != 2)
776 		ctl_usage(res->ctl);
777 
778 	if ((res->path = strdup(argv[1])) == NULL)
779 		err(1, "strdup");
780 
781 	return (vmmaction(res));
782 }
783 
784 int
785 ctl_log(struct parse_result *res, int argc, char *argv[])
786 {
787 	if (argc != 2)
788 		ctl_usage(res->ctl);
789 
790 	if (strncasecmp("brief", argv[1], strlen(argv[1])) == 0)
791 		res->verbose = 0;
792 	else if (strncasecmp("verbose", argv[1], strlen(argv[1])) == 0)
793 		res->verbose = 2;
794 	else
795 		ctl_usage(res->ctl);
796 
797 	return (vmmaction(res));
798 }
799 
800 int
801 ctl_reload(struct parse_result *res, int argc, char *argv[])
802 {
803 	if (argc != 1)
804 		ctl_usage(res->ctl);
805 
806 	return (vmmaction(res));
807 }
808 
809 int
810 ctl_reset(struct parse_result *res, int argc, char *argv[])
811 {
812 	if (argc == 2) {
813 		if (strcasecmp("all", argv[1]) == 0)
814 			res->mode = CONFIG_ALL;
815 		else if (strcasecmp("vms", argv[1]) == 0)
816 			res->mode = CONFIG_VMS;
817 		else if (strcasecmp("switches", argv[1]) == 0)
818 			res->mode = CONFIG_SWITCHES;
819 		else
820 			ctl_usage(res->ctl);
821 	} else if (argc > 2)
822 		ctl_usage(res->ctl);
823 
824 	if (res->mode == 0)
825 		res->mode = CONFIG_ALL;
826 
827 	return (vmmaction(res));
828 }
829 
830 int
831 ctl_start(struct parse_result *res, int argc, char *argv[])
832 {
833 	int		 ch, i, type;
834 	char		 path[PATH_MAX];
835 	const char	*s;
836 
837 	if (argc < 2)
838 		ctl_usage(res->ctl);
839 
840 	if (parse_vmid(res, argv[1], 0) == -1)
841 		errx(1, "invalid id: %s", argv[1]);
842 
843 	argc--;
844 	argv++;
845 
846 	while ((ch = getopt(argc, argv, "b:B:cd:i:Lm:n:r:t:")) != -1) {
847 		switch (ch) {
848 		case 'b':
849 			if (res->path)
850 				errx(1, "boot image specified multiple times");
851 			if (realpath(optarg, path) == NULL)
852 				err(1, "invalid boot image path");
853 			if ((res->path = strdup(path)) == NULL)
854 				errx(1, "strdup");
855 			break;
856 		case 'B':
857 			if (res->bootdevice)
858 				errx(1, "boot device specified multiple times");
859 			if (strcmp("disk", optarg) == 0)
860 				res->bootdevice = VMBOOTDEV_DISK;
861 			else if (strcmp("cdrom", optarg) == 0)
862 				res->bootdevice = VMBOOTDEV_CDROM;
863 			else if (strcmp("net", optarg) == 0)
864 				res->bootdevice = VMBOOTDEV_NET;
865 			else
866 				errx(1, "unknown boot device %s", optarg);
867 			break;
868 		case 'r':
869 			if (res->isopath)
870 				errx(1, "iso image specified multiple times");
871 			if (realpath(optarg, path) == NULL)
872 				err(1, "invalid iso image path");
873 			if ((res->isopath = strdup(path)) == NULL)
874 				errx(1, "strdup");
875 			break;
876 		case 'c':
877 			tty_autoconnect = 1;
878 			break;
879 		case 'L':
880 			if (parse_network(res, ".") != 0)
881 				errx(1, "invalid network: %s", optarg);
882 			break;
883 		case 'm':
884 			if (res->size)
885 				errx(1, "memory specified multiple times");
886 			if (parse_size(res, optarg, 0) != 0)
887 				errx(1, "invalid memory size: %s", optarg);
888 			break;
889 		case 'n':
890 			if (parse_network(res, optarg) != 0)
891 				errx(1, "invalid network: %s", optarg);
892 			break;
893 		case 'd':
894 			type = parse_disktype(optarg, &s);
895 			if (realpath(s, path) == NULL)
896 				err(1, "invalid disk path");
897 			if (parse_disk(res, path, type) != 0)
898 				errx(1, "invalid disk: %s", optarg);
899 			break;
900 		case 'i':
901 			if (res->nifs != -1)
902 				errx(1, "interfaces specified multiple times");
903 			if (parse_ifs(res, optarg, 0) != 0)
904 				errx(1, "invalid interface count: %s", optarg);
905 			break;
906 		case 't':
907 			if (parse_instance(res, optarg) == -1)
908 				errx(1, "invalid name: %s", optarg);
909 			break;
910 		default:
911 			ctl_usage(res->ctl);
912 			/* NOTREACHED */
913 		}
914 	}
915 
916 	for (i = res->nnets; i < res->nifs; i++) {
917 		/* Add interface that is not attached to a switch */
918 		if (parse_network(res, "") == -1)
919 			return (-1);
920 	}
921 	if (res->nnets > res->nifs)
922 		res->nifs = res->nnets;
923 
924 	return (vmmaction(res));
925 }
926 
927 int
928 ctl_stop(struct parse_result *res, int argc, char *argv[])
929 {
930 	int		 ch, ret;
931 
932 	if (argc < 2)
933 		ctl_usage(res->ctl);
934 
935 	if ((ret = parse_vmid(res, argv[1], 0)) == 0) {
936 		argc--;
937 		argv++;
938 	}
939 
940 	while ((ch = getopt(argc, argv, "afw")) != -1) {
941 		switch (ch) {
942 		case 'f':
943 			res->flags |= VMOP_FORCE;
944 			break;
945 		case 'w':
946 			res->flags |= VMOP_WAIT;
947 			break;
948 		case 'a':
949 			res->action = CMD_STOPALL;
950 			break;
951 		default:
952 			ctl_usage(res->ctl);
953 			/* NOTREACHED */
954 		}
955 	}
956 
957 	/* VM id is only expected without the -a flag */
958 	if ((res->action != CMD_STOPALL && ret == -1) ||
959 	    (res->action == CMD_STOPALL && ret != -1))
960 		errx(1, "invalid id: %s", argv[1]);
961 
962 	return (vmmaction(res));
963 }
964 
965 int
966 ctl_console(struct parse_result *res, int argc, char *argv[])
967 {
968 	if (argc == 2) {
969 		if (parse_vmid(res, argv[1], 0) == -1)
970 			errx(1, "invalid id: %s", argv[1]);
971 	} else if (argc != 2)
972 		ctl_usage(res->ctl);
973 
974 	return (vmmaction(res));
975 }
976 
977 int
978 ctl_waitfor(struct parse_result *res, int argc, char *argv[])
979 {
980 	if (argc == 2) {
981 		if (parse_vmid(res, argv[1], 0) == -1)
982 			errx(1, "invalid id: %s", argv[1]);
983 	} else if (argc != 2)
984 		ctl_usage(res->ctl);
985 
986 	return (vmmaction(res));
987 }
988 
989 int
990 ctl_pause(struct parse_result *res, int argc, char *argv[])
991 {
992 	if (argc == 2) {
993 		if (parse_vmid(res, argv[1], 0) == -1)
994 			errx(1, "invalid id: %s", argv[1]);
995 	} else if (argc != 2)
996 		ctl_usage(res->ctl);
997 
998 	return (vmmaction(res));
999 }
1000 
1001 int
1002 ctl_unpause(struct parse_result *res, int argc, char *argv[])
1003 {
1004 	if (argc == 2) {
1005 		if (parse_vmid(res, argv[1], 0) == -1)
1006 			errx(1, "invalid id: %s", argv[1]);
1007 	} else if (argc != 2)
1008 		ctl_usage(res->ctl);
1009 
1010 	return (vmmaction(res));
1011 }
1012 
1013 int
1014 ctl_send(struct parse_result *res, int argc, char *argv[])
1015 {
1016 	if (pledge("stdio unix sendfd unveil", NULL) == -1)
1017 		err(1, "pledge");
1018 	if (argc == 2) {
1019 		if (parse_vmid(res, argv[1], 0) == -1)
1020 			errx(1, "invalid id: %s", argv[1]);
1021 	} else if (argc != 2)
1022 		ctl_usage(res->ctl);
1023 
1024 	return (vmmaction(res));
1025 }
1026 
1027 int
1028 ctl_receive(struct parse_result *res, int argc, char *argv[])
1029 {
1030 	if (pledge("stdio unix sendfd unveil", NULL) == -1)
1031 		err(1, "pledge");
1032 	if (argc == 2) {
1033 		if (parse_vmid(res, argv[1], 1) == -1)
1034 			errx(1, "invalid id: %s", argv[1]);
1035 	} else if (argc != 2)
1036 		ctl_usage(res->ctl);
1037 
1038 	return (vmmaction(res));
1039 }
1040 
1041 __dead void
1042 ctl_openconsole(const char *name)
1043 {
1044 	closefrom(STDERR_FILENO + 1);
1045 	if (unveil(VMCTL_CU, "x") == -1)
1046 		err(1, "unveil");
1047 	execl(VMCTL_CU, VMCTL_CU, "-l", name, "-s", "115200", (char *)NULL);
1048 	err(1, "failed to open the console");
1049 }
1050