xref: /openbsd/usr.sbin/vmctl/vmctl.c (revision 8f40ce4b)
1 /*	$OpenBSD: vmctl.c,v 1.69 2019/05/22 16:19:21 jasper Exp $	*/
2 
3 /*
4  * Copyright (c) 2014 Mike Larkin <mlarkin@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/queue.h>
20 #include <sys/uio.h>
21 #include <sys/stat.h>
22 #include <sys/socket.h>
23 #include <sys/un.h>
24 
25 #include <machine/vmmvar.h>
26 
27 #include <ctype.h>
28 #include <err.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <imsg.h>
32 #include <limits.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <util.h>
38 #include <pwd.h>
39 #include <grp.h>
40 
41 #include "vmd.h"
42 #include "virtio.h"
43 #include "vmctl.h"
44 #include "atomicio.h"
45 
46 extern char *__progname;
47 uint32_t info_id;
48 char info_name[VMM_MAX_NAME_LEN];
49 enum actions info_action;
50 unsigned int info_flags;
51 
52 /*
53  * vm_start
54  *
55  * Request vmd to start the VM defined by the supplied parameters
56  *
57  * Parameters:
58  *  start_id: optional ID of the VM
59  *  name: optional name of the VM
60  *  memsize: memory size (MB) of the VM to create
61  *  nnics: number of vionet network interfaces to create
62  *  nics: switch names of the network interfaces to create
63  *  ndisks: number of disk images
64  *  disks: disk image file names
65  *  kernel: kernel image to load
66  *  iso: iso image file
67  *  instance: create instance from vm
68  *
69  * Return:
70  *  0 if the request to start the VM was sent successfully.
71  *  ENOMEM if a memory allocation failure occurred.
72  */
73 int
74 vm_start(uint32_t start_id, const char *name, int memsize, int nnics,
75     char **nics, int ndisks, char **disks, int *disktypes, char *kernel,
76     char *iso, char *instance, unsigned int bootdevice)
77 {
78 	struct vmop_create_params *vmc;
79 	struct vm_create_params *vcp;
80 	unsigned int flags = 0;
81 	int i;
82 	const char *s;
83 
84 	if (memsize)
85 		flags |= VMOP_CREATE_MEMORY;
86 	if (nnics)
87 		flags |= VMOP_CREATE_NETWORK;
88 	if (ndisks)
89 		flags |= VMOP_CREATE_DISK;
90 	if (kernel)
91 		flags |= VMOP_CREATE_KERNEL;
92 	if (iso)
93 		flags |= VMOP_CREATE_CDROM;
94 	if (instance)
95 		flags |= VMOP_CREATE_INSTANCE;
96 	else if (flags != 0) {
97 		if (memsize < 1)
98 			memsize = VM_DEFAULT_MEMORY;
99 		if (ndisks > VMM_MAX_DISKS_PER_VM)
100 			errx(1, "too many disks");
101 		else if (ndisks == 0)
102 			warnx("starting without disks");
103 		if (kernel == NULL && ndisks == 0 && !iso)
104 			errx(1, "no kernel or disk/cdrom specified");
105 		if (nnics == -1)
106 			nnics = 0;
107 		if (nnics > VMM_MAX_NICS_PER_VM)
108 			errx(1, "too many network interfaces");
109 		if (nnics == 0)
110 			warnx("starting without network interfaces");
111 	}
112 
113 	if ((vmc = calloc(1, sizeof(struct vmop_create_params))) == NULL)
114 		return (ENOMEM);
115 
116 	vmc->vmc_flags = flags;
117 
118 	/* vcp includes configuration that is shared with the kernel */
119 	vcp = &vmc->vmc_params;
120 
121 	/*
122 	 * XXX: vmd(8) fills in the actual memory ranges. vmctl(8)
123 	 * just passes in the actual memory size in MB here.
124 	 */
125 	vcp->vcp_nmemranges = 1;
126 	vcp->vcp_memranges[0].vmr_size = memsize;
127 
128 	vcp->vcp_ncpus = 1;
129 	vcp->vcp_ndisks = ndisks;
130 	vcp->vcp_nnics = nnics;
131 	vcp->vcp_id = start_id;
132 
133 	for (i = 0 ; i < ndisks; i++) {
134 		if (strlcpy(vcp->vcp_disks[i], disks[i],
135 		    sizeof(vcp->vcp_disks[i])) >=
136 		    sizeof(vcp->vcp_disks[i]))
137 			errx(1, "disk path too long");
138 		vmc->vmc_disktypes[i] = disktypes[i];
139 	}
140 	for (i = 0 ; i < nnics; i++) {
141 		vmc->vmc_ifflags[i] = VMIFF_UP;
142 
143 		if (strcmp(".", nics[i]) == 0) {
144 			/* Add a "local" interface */
145 			(void)strlcpy(vmc->vmc_ifswitch[i], "",
146 			    sizeof(vmc->vmc_ifswitch[i]));
147 			vmc->vmc_ifflags[i] |= VMIFF_LOCAL;
148 		} else {
149 			/* Add an interface to a switch */
150 			if (strlcpy(vmc->vmc_ifswitch[i], nics[i],
151 			    sizeof(vmc->vmc_ifswitch[i])) >=
152 			    sizeof(vmc->vmc_ifswitch[i]))
153 				errx(1, "interface name too long");
154 		}
155 	}
156 	if (name != NULL) {
157 		/*
158 		 * Allow VMs names with alphanumeric characters, dot, hyphen
159 		 * and underscore. But disallow dot, hyphen and underscore at
160 		 * the start.
161 		 */
162 		if (*name == '-' || *name == '.' || *name == '_')
163 			errx(1, "invalid VM name");
164 
165 		for (s = name; *s != '\0'; ++s) {
166 			if (!(isalnum(*s) || *s == '.' || *s == '-' ||
167 			    *s == '_'))
168 				errx(1, "invalid VM name");
169 		}
170 
171 		if (strlcpy(vcp->vcp_name, name,
172 		    sizeof(vcp->vcp_name)) >= sizeof(vcp->vcp_name))
173 			errx(1, "vm name too long");
174 	}
175 	if (kernel != NULL)
176 		if (strlcpy(vcp->vcp_kernel, kernel,
177 		    sizeof(vcp->vcp_kernel)) >= sizeof(vcp->vcp_kernel))
178 			errx(1, "kernel name too long");
179 	if (iso != NULL)
180 		if (strlcpy(vcp->vcp_cdrom, iso,
181 		    sizeof(vcp->vcp_cdrom)) >= sizeof(vcp->vcp_cdrom))
182 			errx(1, "cdrom name too long");
183 	if (instance != NULL)
184 		if (strlcpy(vmc->vmc_instance, instance,
185 		    sizeof(vmc->vmc_instance)) >= sizeof(vmc->vmc_instance))
186 			errx(1, "instance vm name too long");
187 	vmc->vmc_bootdevice = bootdevice;
188 
189 	imsg_compose(ibuf, IMSG_VMDOP_START_VM_REQUEST, 0, 0, -1,
190 	    vmc, sizeof(struct vmop_create_params));
191 
192 	free(vcp);
193 	return (0);
194 }
195 
196 /*
197  * vm_start_complete
198  *
199  * Callback function invoked when we are expecting an
200  * IMSG_VMDOP_START_VMM_RESPONSE message indicating the completion of
201  * a start vm operation.
202  *
203  * Parameters:
204  *  imsg : response imsg received from vmd
205  *  ret  : return value
206  *  autoconnect : open the console after startup
207  *
208  * Return:
209  *  Always 1 to indicate we have processed the return message (even if it
210  *  was an incorrect/failure message)
211  *
212  *  The function also sets 'ret' to the error code as follows:
213  *   0     : Message successfully processed
214  *   EINVAL: Invalid or unexpected response from vmd
215  *   EIO   : vm_start command failed
216  *   ENOENT: a specified component of the VM could not be found (disk image,
217  *    BIOS firmware image, etc)
218  */
219 int
220 vm_start_complete(struct imsg *imsg, int *ret, int autoconnect)
221 {
222 	struct vmop_result *vmr;
223 	int res;
224 
225 	if (imsg->hdr.type == IMSG_VMDOP_START_VM_RESPONSE) {
226 		vmr = (struct vmop_result *)imsg->data;
227 		res = vmr->vmr_result;
228 		if (res) {
229 			switch (res) {
230 			case VMD_BIOS_MISSING:
231 				warnx("vmm bios firmware file not found.");
232 				*ret = ENOENT;
233 				break;
234 			case VMD_DISK_MISSING:
235 				warnx("could not open disk image(s)");
236 				*ret = ENOENT;
237 				break;
238 			case VMD_DISK_INVALID:
239 				warnx("specified disk image(s) are "
240 				    "not regular files");
241 				*ret = ENOENT;
242 				break;
243 			case VMD_CDROM_MISSING:
244 				warnx("could not find specified iso image");
245 				*ret = ENOENT;
246 				break;
247 			case VMD_CDROM_INVALID:
248 				warnx("specified iso image is not a regular "
249 				    "file");
250 				*ret = ENOENT;
251 				break;
252 			default:
253 				errno = res;
254 				warn("start vm command failed");
255 				*ret = EIO;
256 			}
257 		} else if (autoconnect) {
258 			/* does not return */
259 			ctl_openconsole(vmr->vmr_ttyname);
260 		} else {
261 			warnx("started vm %d successfully, tty %s",
262 			    vmr->vmr_id, vmr->vmr_ttyname);
263 			*ret = 0;
264 		}
265 	} else {
266 		warnx("unexpected response received from vmd");
267 		*ret = EINVAL;
268 	}
269 
270 	return (1);
271 }
272 
273 void
274 send_vm(uint32_t id, const char *name)
275 {
276 	struct vmop_id vid;
277 	int fds[2], readn, writen;
278 	long pagesz;
279 	char *buf;
280 
281 	pagesz = getpagesize();
282 	buf = malloc(pagesz);
283 	if (buf == NULL)
284 		errx(1, "%s: memory allocation failure", __func__);
285 
286 	memset(&vid, 0, sizeof(vid));
287 	vid.vid_id = id;
288 	if (name != NULL)
289 		strlcpy(vid.vid_name, name, sizeof(vid.vid_name));
290 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, fds) == -1) {
291 		warnx("%s: socketpair creation failed", __func__);
292 	} else {
293 		imsg_compose(ibuf, IMSG_VMDOP_SEND_VM_REQUEST, 0, 0, fds[0],
294 				&vid, sizeof(vid));
295 		imsg_flush(ibuf);
296 		while (1) {
297 			readn = atomicio(read, fds[1], buf, pagesz);
298 			if (!readn)
299 				break;
300 			writen = atomicio(vwrite, STDOUT_FILENO, buf,
301 					readn);
302 			if (writen != readn)
303 				break;
304 		}
305 		if (vid.vid_id)
306 			warnx("sent vm %d successfully", vid.vid_id);
307 		else
308 			warnx("sent vm %s successfully", vid.vid_name);
309 	}
310 
311 	free(buf);
312 }
313 
314 void
315 vm_receive(uint32_t id, const char *name)
316 {
317 	struct vmop_id vid;
318 	int fds[2], readn, writen;
319 	long pagesz;
320 	char *buf;
321 
322 	pagesz = getpagesize();
323 	buf = malloc(pagesz);
324 	if (buf == NULL)
325 		errx(1, "%s: memory allocation failure", __func__);
326 
327 	memset(&vid, 0, sizeof(vid));
328 	if (name != NULL)
329 		strlcpy(vid.vid_name, name, sizeof(vid.vid_name));
330 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, fds) == -1) {
331 		warnx("%s: socketpair creation failed", __func__);
332 	} else {
333 		imsg_compose(ibuf, IMSG_VMDOP_RECEIVE_VM_REQUEST, 0, 0, fds[0],
334 		    &vid, sizeof(vid));
335 		imsg_flush(ibuf);
336 		while (1) {
337 			readn = atomicio(read, STDIN_FILENO, buf, pagesz);
338 			if (!readn) {
339 				close(fds[1]);
340 				break;
341 			}
342 			writen = atomicio(vwrite, fds[1], buf, readn);
343 			if (writen != readn)
344 				break;
345 		}
346 	}
347 
348 	free(buf);
349 }
350 
351 void
352 pause_vm(uint32_t pause_id, const char *name)
353 {
354 	struct vmop_id vid;
355 
356 	memset(&vid, 0, sizeof(vid));
357 	vid.vid_id = pause_id;
358 	if (name != NULL)
359 		(void)strlcpy(vid.vid_name, name, sizeof(vid.vid_name));
360 
361 	imsg_compose(ibuf, IMSG_VMDOP_PAUSE_VM, 0, 0, -1,
362 	    &vid, sizeof(vid));
363 }
364 
365 int
366 pause_vm_complete(struct imsg *imsg, int *ret)
367 {
368 	struct vmop_result *vmr;
369 	int res;
370 
371 	if (imsg->hdr.type == IMSG_VMDOP_PAUSE_VM_RESPONSE) {
372 		vmr = (struct vmop_result *)imsg->data;
373 		res = vmr->vmr_result;
374 		if (res) {
375 			errno = res;
376 			warn("pause vm command failed");
377 			*ret = EIO;
378 		} else {
379 			warnx("paused vm %d successfully", vmr->vmr_id);
380 			*ret = 0;
381 		}
382 	} else {
383 		warnx("unexpected response received from vmd");
384 		*ret = EINVAL;
385 	}
386 
387 	return (1);
388 }
389 
390 void
391 unpause_vm(uint32_t pause_id, const char *name)
392 {
393 	struct vmop_id vid;
394 
395 	memset(&vid, 0, sizeof(vid));
396 	vid.vid_id = pause_id;
397 	if (name != NULL)
398 		(void)strlcpy(vid.vid_name, name, sizeof(vid.vid_name));
399 
400 	imsg_compose(ibuf, IMSG_VMDOP_UNPAUSE_VM, 0, 0, -1,
401 	    &vid, sizeof(vid));
402 }
403 
404 int
405 unpause_vm_complete(struct imsg *imsg, int *ret)
406 {
407 	struct vmop_result *vmr;
408 	int res;
409 
410 	if (imsg->hdr.type == IMSG_VMDOP_UNPAUSE_VM_RESPONSE) {
411 		vmr = (struct vmop_result *)imsg->data;
412 		res = vmr->vmr_result;
413 		if (res) {
414 			errno = res;
415 			warn("unpause vm command failed");
416 			*ret = EIO;
417 		} else {
418 			warnx("unpaused vm %d successfully", vmr->vmr_id);
419 			*ret = 0;
420 		}
421 	} else {
422 		warnx("unexpected response received from vmd");
423 		*ret = EINVAL;
424 	}
425 
426 	return (1);
427 }
428 
429 /*
430  * terminate_vm
431  *
432  * Request vmd to stop the VM indicated
433  *
434  * Parameters:
435  *  terminate_id: ID of the vm to be terminated
436  *  name: optional name of the VM to be terminated
437  *  flags: VMOP_FORCE or VMOP_WAIT flags
438  */
439 void
440 terminate_vm(uint32_t terminate_id, const char *name, unsigned int flags)
441 {
442 	struct vmop_id vid;
443 
444 	memset(&vid, 0, sizeof(vid));
445 	vid.vid_id = terminate_id;
446 	if (name != NULL) {
447 		(void)strlcpy(vid.vid_name, name, sizeof(vid.vid_name));
448 		fprintf(stderr, "stopping vm %s: ", name);
449 	} else {
450 		fprintf(stderr, "stopping vm: ");
451 	}
452 
453 	vid.vid_flags = flags & (VMOP_FORCE|VMOP_WAIT);
454 
455 	imsg_compose(ibuf, IMSG_VMDOP_TERMINATE_VM_REQUEST,
456 	    0, 0, -1, &vid, sizeof(vid));
457 }
458 
459 /*
460  * terminate_vm_complete
461  *
462  * Callback function invoked when we are expecting an
463  * IMSG_VMDOP_TERMINATE_VMM_RESPONSE message indicating the completion of
464  * a terminate vm operation.
465  *
466  * Parameters:
467  *  imsg : response imsg received from vmd
468  *  ret  : return value
469  *  flags: VMOP_FORCE or VMOP_WAIT flags
470  *
471  * Return:
472  *  Always 1 to indicate we have processed the return message (even if it
473  *  was an incorrect/failure message)
474  *
475  *  The function also sets 'ret' to the error code as follows:
476  *   0     : Message successfully processed
477  *   EINVAL: Invalid or unexpected response from vmd
478  *   EIO   : terminate_vm command failed
479  */
480 int
481 terminate_vm_complete(struct imsg *imsg, int *ret, unsigned int flags)
482 {
483 	struct vmop_result *vmr;
484 	int res;
485 
486 	if (imsg->hdr.type == IMSG_VMDOP_TERMINATE_VM_RESPONSE) {
487 		vmr = (struct vmop_result *)imsg->data;
488 		res = vmr->vmr_result;
489 		if (res) {
490 			switch (res) {
491 			case VMD_VM_STOP_INVALID:
492 				fprintf(stderr,
493 				    "cannot stop vm that is not running\n");
494 				*ret = EINVAL;
495 				break;
496 			case ENOENT:
497 				fprintf(stderr, "vm not found\n");
498 				*ret = EIO;
499 				break;
500 			case EINTR:
501 				fprintf(stderr, "interrupted call\n");
502 				*ret = EIO;
503 				break;
504 			default:
505 				errno = res;
506 				fprintf(stderr, "failed: %s\n",
507 				    strerror(res));
508 				*ret = EIO;
509 			}
510 		} else if (flags & VMOP_WAIT) {
511 			fprintf(stderr, "terminated vm %d\n", vmr->vmr_id);
512 		} else if (flags & VMOP_FORCE) {
513 			fprintf(stderr, "forced to terminate vm %d\n",
514 			    vmr->vmr_id);
515 		} else {
516 			fprintf(stderr, "requested to shutdown vm %d\n",
517 			    vmr->vmr_id);
518 			*ret = 0;
519 		}
520 	} else {
521 		fprintf(stderr, "unexpected response received from vmd\n");
522 		*ret = EINVAL;
523 	}
524 	errno = *ret;
525 
526 	return (1);
527 }
528 
529 /*
530  * terminate_all
531  *
532  * Request to stop all VMs gracefully
533  *
534  * Parameters
535  *  list: the vm information (consolidated) returned from vmd via imsg
536  *  ct  : the size (number of elements in 'list') of the result
537  *  flags: VMOP_FORCE or VMOP_WAIT flags
538  */
539 void
540 terminate_all(struct vmop_info_result *list, size_t ct, unsigned int flags)
541 {
542 	struct vm_info_result *vir;
543 	struct vmop_info_result *vmi;
544 	struct parse_result res;
545 	size_t i;
546 
547 	for (i = 0; i < ct; i++) {
548 		vmi = &list[i];
549 		vir = &vmi->vir_info;
550 
551 		/* The VM is already stopped */
552 		if (vir->vir_creator_pid == 0 || vir->vir_id == 0)
553 			continue;
554 
555 		memset(&res, 0, sizeof(res));
556 		res.action = CMD_STOP;
557 		res.id = 0;
558 		res.flags = info_flags;
559 
560 		if ((res.name = strdup(vir->vir_name)) == NULL)
561 			errx(1, "strdup");
562 
563 		vmmaction(&res);
564 	}
565 }
566 
567 /*
568  * waitfor_vm
569  *
570  * Wait until vmd stopped the indicated VM
571  *
572  * Parameters:
573  *  terminate_id: ID of the vm to be terminated
574  *  name: optional name of the VM to be terminated
575  */
576 void
577 waitfor_vm(uint32_t terminate_id, const char *name)
578 {
579 	struct vmop_id vid;
580 
581 	memset(&vid, 0, sizeof(vid));
582 	vid.vid_id = terminate_id;
583 	if (name != NULL) {
584 		(void)strlcpy(vid.vid_name, name, sizeof(vid.vid_name));
585 		fprintf(stderr, "waiting for vm %s: ", name);
586 	} else {
587 		fprintf(stderr, "waiting for vm: ");
588 	}
589 
590 	imsg_compose(ibuf, IMSG_VMDOP_WAIT_VM_REQUEST,
591 	    0, 0, -1, &vid, sizeof(vid));
592 }
593 
594 /*
595  * get_info_vm
596  *
597  * Return the list of all running VMs or find a specific VM by ID or name.
598  *
599  * Parameters:
600  *  id: optional ID of a VM to list
601  *  name: optional name of a VM to list
602  *  action: if CMD_CONSOLE or CMD_STOP open a console or terminate the VM.
603  *  flags: optional flags used by the CMD_STOP action.
604  *
605  * Request a list of running VMs from vmd
606  */
607 void
608 get_info_vm(uint32_t id, const char *name, enum actions action,
609     unsigned int flags)
610 {
611 	info_id = id;
612 	if (name != NULL)
613 		(void)strlcpy(info_name, name, sizeof(info_name));
614 	info_action = action;
615 	info_flags = flags;
616 	imsg_compose(ibuf, IMSG_VMDOP_GET_INFO_VM_REQUEST, 0, 0, -1, NULL, 0);
617 }
618 
619 /*
620  * check_info_id
621  *
622  * Check if requested name or ID of a VM matches specified arguments
623  *
624  * Parameters:
625  *  name: name of the VM
626  *  id: ID of the VM
627  */
628 int
629 check_info_id(const char *name, uint32_t id)
630 {
631 	if (info_id == 0 && *info_name == '\0')
632 		return (-1);
633 	if (info_id != 0 && info_id == id)
634 		return (1);
635 	if (*info_name != '\0' && name && strcmp(info_name, name) == 0)
636 		return (1);
637 	return (0);
638 }
639 
640 /*
641  * add_info
642  *
643  * Callback function invoked when we are expecting an
644  * IMSG_VMDOP_GET_INFO_VM_DATA message indicating the receipt of additional
645  * "list vm" data, or an IMSG_VMDOP_GET_INFO_VM_END_DATA message indicating
646  * that no additional "list vm" data will be forthcoming.
647  *
648  * Parameters:
649  *  imsg : response imsg received from vmd
650  *  ret  : return value
651  *
652  * Return:
653  *  0     : the returned data was successfully added to the "list vm" data.
654  *          The caller can expect more data.
655  *  1     : IMSG_VMDOP_GET_INFO_VM_END_DATA received (caller should not call
656  *          add_info again), or an error occurred adding the returned data
657  *          to the "list vm" data. The caller should check the value of
658  *          'ret' to determine which case occurred.
659  *
660  * This function does not return if a VM is found and info_action is CMD_CONSOLE
661  *
662  *  The function also sets 'ret' to the error code as follows:
663  *   0     : Message successfully processed
664  *   EINVAL: Invalid or unexpected response from vmd
665  *   ENOMEM: memory allocation failure
666  */
667 int
668 add_info(struct imsg *imsg, int *ret)
669 {
670 	static size_t ct = 0;
671 	static struct vmop_info_result *vir = NULL;
672 
673 	if (imsg->hdr.type == IMSG_VMDOP_GET_INFO_VM_DATA) {
674 		vir = reallocarray(vir, ct + 1,
675 		    sizeof(struct vmop_info_result));
676 		if (vir == NULL) {
677 			*ret = ENOMEM;
678 			return (1);
679 		}
680 		memcpy(&vir[ct], imsg->data, sizeof(struct vmop_info_result));
681 		ct++;
682 		*ret = 0;
683 		return (0);
684 	} else if (imsg->hdr.type == IMSG_VMDOP_GET_INFO_VM_END_DATA) {
685 		switch (info_action) {
686 		case CMD_CONSOLE:
687 			vm_console(vir, ct);
688 			break;
689 		case CMD_STOPALL:
690 			terminate_all(vir, ct, info_flags);
691 			break;
692 		default:
693 			print_vm_info(vir, ct);
694 			break;
695 		}
696 		free(vir);
697 		*ret = 0;
698 		return (1);
699 	} else {
700 		*ret = EINVAL;
701 		return (1);
702 	}
703 }
704 
705 /*
706  * vm_state
707  *
708  * Returns a string representing the current VM state, note that the order
709  * matters. A paused VM does have the VM_STATE_RUNNING bit set, but
710  * VM_STATE_PAUSED is more significant to report.
711  *
712  * Parameters
713  *  vm_state: mask indicating the vm state
714  */
715 const char *
716 vm_state(unsigned int mask)
717 {
718 	if (mask & VM_STATE_PAUSED)
719 		return "paused";
720 	else if (mask & VM_STATE_RUNNING)
721 		return "running";
722 	else if (mask & VM_STATE_SHUTDOWN)
723 		return "stopping";
724 	/* Presence of absence of other flags */
725 	else if (!mask || (mask & VM_STATE_DISABLED))
726 		return "stopped";
727 
728 	return "unknown";
729 }
730 
731 /*
732  * print_vm_info
733  *
734  * Prints the vm information returned from vmd in 'list' to stdout.
735  *
736  * Parameters
737  *  list: the vm information (consolidated) returned from vmd via imsg
738  *  ct  : the size (number of elements in 'list') of the result
739  */
740 void
741 print_vm_info(struct vmop_info_result *list, size_t ct)
742 {
743 	struct vm_info_result *vir;
744 	struct vmop_info_result *vmi;
745 	size_t i;
746 	char *tty;
747 	char curmem[FMT_SCALED_STRSIZE];
748 	char maxmem[FMT_SCALED_STRSIZE];
749 	char user[16], group[16];
750 	const char *name;
751 	int running;
752 
753 	printf("%5s %5s %5s %7s %7s %7s %12s %8s %s\n", "ID", "PID", "VCPUS",
754 	    "MAXMEM", "CURMEM", "TTY", "OWNER", "STATE", "NAME");
755 
756 	for (i = 0; i < ct; i++) {
757 		vmi = &list[i];
758 		vir = &vmi->vir_info;
759 		running = (vir->vir_creator_pid != 0 && vir->vir_id != 0);
760 		if (check_info_id(vir->vir_name, vir->vir_id)) {
761 			/* get user name */
762 			name = user_from_uid(vmi->vir_uid, 1);
763 			if (name == NULL)
764 				(void)snprintf(user, sizeof(user),
765 				    "%d", vmi->vir_uid);
766 			else
767 				(void)strlcpy(user, name, sizeof(user));
768 			/* get group name */
769 			if (vmi->vir_gid != -1) {
770 				if (vmi->vir_uid == 0)
771 					*user = '\0';
772 				name = group_from_gid(vmi->vir_gid, 1);
773 				if (name == NULL)
774 					(void)snprintf(group, sizeof(group),
775 					    ":%lld", vmi->vir_gid);
776 				else
777 					(void)snprintf(group, sizeof(group),
778 					    ":%s", name);
779 				(void)strlcat(user, group, sizeof(user));
780 			}
781 
782 			(void)strlcpy(curmem, "-", sizeof(curmem));
783 			(void)strlcpy(maxmem, "-", sizeof(maxmem));
784 
785 			(void)fmt_scaled(vir->vir_memory_size * 1024 * 1024,
786 			    maxmem);
787 
788 			if (running) {
789 				if (*vmi->vir_ttyname == '\0')
790 					tty = "-";
791 				/* get tty - skip /dev/ path */
792 				else if ((tty = strrchr(vmi->vir_ttyname,
793 				    '/')) == NULL || ++tty == '\0')
794 					tty = list[i].vir_ttyname;
795 
796 				(void)fmt_scaled(vir->vir_used_size, curmem);
797 
798 				/* running vm */
799 				printf("%5u %5u %5zd %7s %7s %7s %12s %8s %s\n",
800 				    vir->vir_id, vir->vir_creator_pid,
801 				    vir->vir_ncpus, maxmem, curmem,
802 				    tty, user, vm_state(vmi->vir_state),
803 				    vir->vir_name);
804 			} else {
805 				/* disabled vm */
806 				printf("%5u %5s %5zd %7s %7s %7s %12s %8s %s\n",
807 				    vir->vir_id, "-",
808 				    vir->vir_ncpus, maxmem, curmem,
809 				    "-", user, vm_state(vmi->vir_state),
810 				    vir->vir_name);
811 			}
812 		}
813 	}
814 }
815 
816 /*
817  * vm_console
818  *
819  * Connects to the vm console returned from vmd in 'list'.
820  *
821  * Parameters
822  *  list: the vm information (consolidated) returned from vmd via imsg
823  *  ct  : the size (number of elements in 'list') of the result
824  */
825 __dead void
826 vm_console(struct vmop_info_result *list, size_t ct)
827 {
828 	struct vmop_info_result *vir;
829 	size_t i;
830 
831 	for (i = 0; i < ct; i++) {
832 		vir = &list[i];
833 		if ((check_info_id(vir->vir_info.vir_name,
834 		    vir->vir_info.vir_id) > 0) &&
835 			(vir->vir_ttyname[0] != '\0')) {
836 			/* does not return */
837 			ctl_openconsole(vir->vir_ttyname);
838 		}
839 	}
840 
841 	errx(1, "console not found");
842 }
843 
844 /*
845  * open_imagefile
846  *
847  * Open an imagefile with the specified type, path and size.
848  *
849  * Parameters:
850  *  type        : format of the image file
851  *  imgfile_path: path to the image file to create
852  *  flags       : flags for open(2), e.g. O_RDONLY
853  *  file        : file structure
854  *  sz		: size of the image file
855  *
856  * Return:
857  *  fd          : Returns file descriptor of the new image file
858  *  -1          : Operation failed.  errno is set.
859  */
860 int
861 open_imagefile(int type, const char *imgfile_path, int flags,
862     struct virtio_backing *file, off_t *sz)
863 {
864 	int	 fd, ret, basefd[VM_MAX_BASE_PER_DISK], nfd, i;
865 	char	 path[PATH_MAX];
866 
867 	*sz = 0;
868 	if ((fd = open(imgfile_path, flags)) == -1)
869 		return (-1);
870 
871 	basefd[0] = fd;
872 	nfd = 1;
873 
874 	errno = 0;
875 	switch (type) {
876 	case VMDF_QCOW2:
877 		if (strlcpy(path, imgfile_path, sizeof(path)) >= sizeof(path))
878 			return (-1);
879 		for (i = 0; i < VM_MAX_BASE_PER_DISK - 1; i++, nfd++) {
880 			if ((ret = virtio_qcow2_get_base(basefd[i],
881 			    path, sizeof(path), imgfile_path)) == -1) {
882 				log_debug("%s: failed to get base %d", __func__, i);
883 				return -1;
884 			} else if (ret == 0)
885 				break;
886 
887 			/*
888 			 * This might be called after unveil is already
889 			 * locked but it is save to ignore the EPERM error
890 			 * here as the subsequent open would fail as well.
891 			 */
892 			if ((ret = unveil(path, "r")) != 0 &&
893 			    (ret != EPERM))
894 				err(1, "unveil");
895 			if ((basefd[i + 1] = open(path, O_RDONLY)) == -1) {
896 				log_warn("%s: failed to open base %s",
897 				    __func__, path);
898 				return (-1);
899 			}
900 		}
901 		ret = virtio_qcow2_init(file, sz, basefd, nfd);
902 		break;
903 	default:
904 		ret = virtio_raw_init(file, sz, &fd, 1);
905 		break;
906 	}
907 
908 	if (ret == -1) {
909 		for (i = 0; i < nfd; i++)
910 			close(basefd[i]);
911 		return (-1);
912 	}
913 
914 	return (fd);
915 }
916 
917 /*
918  * create_imagefile
919  *
920  * Create an empty imagefile with the specified type, path and size.
921  *
922  * Parameters:
923  *  type        : format of the image file
924  *  imgfile_path: path to the image file to create
925  *  base_path   : path to the qcow2 base image
926  *  imgsize     : size of the image file to create (in MB)
927  *  format      : string identifying the format
928  *
929  * Return:
930  *  EEXIST: The requested image file already exists
931  *  0     : Image file successfully created
932  *  Exxxx : Various other Exxxx errno codes due to other I/O errors
933  */
934 int
935 create_imagefile(int type, const char *imgfile_path, const char *base_path,
936     long imgsize, const char **format)
937 {
938 	int	 ret;
939 
940 	switch (type) {
941 	case VMDF_QCOW2:
942 		*format = "qcow2";
943 		ret = virtio_qcow2_create(imgfile_path, base_path, imgsize);
944 		break;
945 	default:
946 		*format = "raw";
947 		ret = virtio_raw_create(imgfile_path, imgsize);
948 		break;
949 	}
950 
951 	return (ret);
952 }
953 
954