]> git.proxmox.com Git - mirror_qemu.git/blob - qga/commands-posix.c
qga/commands-posix: 'guest-shutdown' for Solaris
[mirror_qemu.git] / qga / commands-posix.c
1 /*
2 * QEMU Guest Agent POSIX-specific command implementations
3 *
4 * Copyright IBM Corp. 2011
5 *
6 * Authors:
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
8 * Michal Privoznik <mprivozn@redhat.com>
9 *
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
12 */
13
14 #include "qemu/osdep.h"
15 #include <sys/ioctl.h>
16 #include <sys/utsname.h>
17 #include <sys/wait.h>
18 #include <dirent.h>
19 #include "guest-agent-core.h"
20 #include "qga-qapi-commands.h"
21 #include "qapi/error.h"
22 #include "qapi/qmp/qerror.h"
23 #include "qemu/queue.h"
24 #include "qemu/host-utils.h"
25 #include "qemu/sockets.h"
26 #include "qemu/base64.h"
27 #include "qemu/cutils.h"
28 #include "commands-common.h"
29
30 #ifdef HAVE_UTMPX
31 #include <utmpx.h>
32 #endif
33
34 #if defined(__linux__)
35 #include <mntent.h>
36 #include <linux/fs.h>
37 #include <sys/statvfs.h>
38
39 #ifdef CONFIG_LIBUDEV
40 #include <libudev.h>
41 #endif
42
43 #ifdef FIFREEZE
44 #define CONFIG_FSFREEZE
45 #endif
46 #ifdef FITRIM
47 #define CONFIG_FSTRIM
48 #endif
49 #endif
50
51 #ifdef HAVE_GETIFADDRS
52 #include <arpa/inet.h>
53 #include <sys/socket.h>
54 #include <net/if.h>
55 #include <sys/types.h>
56 #include <ifaddrs.h>
57 #ifdef CONFIG_SOLARIS
58 #include <sys/sockio.h>
59 #endif
60 #endif
61
62 static void ga_wait_child(pid_t pid, int *status, Error **errp)
63 {
64 pid_t rpid;
65
66 *status = 0;
67
68 do {
69 rpid = waitpid(pid, status, 0);
70 } while (rpid == -1 && errno == EINTR);
71
72 if (rpid == -1) {
73 error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
74 pid);
75 return;
76 }
77
78 g_assert(rpid == pid);
79 }
80
81 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
82 {
83 const char *shutdown_flag;
84 Error *local_err = NULL;
85 pid_t pid;
86 int status;
87
88 #ifdef CONFIG_SOLARIS
89 const char *powerdown_flag = "-i5";
90 const char *halt_flag = "-i0";
91 const char *reboot_flag = "-i6";
92 #else
93 const char *powerdown_flag = "-P";
94 const char *halt_flag = "-H";
95 const char *reboot_flag = "-r";
96 #endif
97
98 slog("guest-shutdown called, mode: %s", mode);
99 if (!has_mode || strcmp(mode, "powerdown") == 0) {
100 shutdown_flag = powerdown_flag;
101 } else if (strcmp(mode, "halt") == 0) {
102 shutdown_flag = halt_flag;
103 } else if (strcmp(mode, "reboot") == 0) {
104 shutdown_flag = reboot_flag;
105 } else {
106 error_setg(errp,
107 "mode is invalid (valid values are: halt|powerdown|reboot");
108 return;
109 }
110
111 pid = fork();
112 if (pid == 0) {
113 /* child, start the shutdown */
114 setsid();
115 reopen_fd_to_null(0);
116 reopen_fd_to_null(1);
117 reopen_fd_to_null(2);
118
119 #ifdef CONFIG_SOLARIS
120 execl("/sbin/shutdown", "shutdown", shutdown_flag, "-g0", "-y",
121 "hypervisor initiated shutdown", (char *)NULL);
122 #else
123 execl("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
124 "hypervisor initiated shutdown", (char *)NULL);
125 #endif
126 _exit(EXIT_FAILURE);
127 } else if (pid < 0) {
128 error_setg_errno(errp, errno, "failed to create child process");
129 return;
130 }
131
132 ga_wait_child(pid, &status, &local_err);
133 if (local_err) {
134 error_propagate(errp, local_err);
135 return;
136 }
137
138 if (!WIFEXITED(status)) {
139 error_setg(errp, "child process has terminated abnormally");
140 return;
141 }
142
143 if (WEXITSTATUS(status)) {
144 error_setg(errp, "child process has failed to shutdown");
145 return;
146 }
147
148 /* succeeded */
149 }
150
151 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
152 {
153 int ret;
154 int status;
155 pid_t pid;
156 Error *local_err = NULL;
157 struct timeval tv;
158 static const char hwclock_path[] = "/sbin/hwclock";
159 static int hwclock_available = -1;
160
161 if (hwclock_available < 0) {
162 hwclock_available = (access(hwclock_path, X_OK) == 0);
163 }
164
165 if (!hwclock_available) {
166 error_setg(errp, QERR_UNSUPPORTED);
167 return;
168 }
169
170 /* If user has passed a time, validate and set it. */
171 if (has_time) {
172 GDate date = { 0, };
173
174 /* year-2038 will overflow in case time_t is 32bit */
175 if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
176 error_setg(errp, "Time %" PRId64 " is too large", time_ns);
177 return;
178 }
179
180 tv.tv_sec = time_ns / 1000000000;
181 tv.tv_usec = (time_ns % 1000000000) / 1000;
182 g_date_set_time_t(&date, tv.tv_sec);
183 if (date.year < 1970 || date.year >= 2070) {
184 error_setg_errno(errp, errno, "Invalid time");
185 return;
186 }
187
188 ret = settimeofday(&tv, NULL);
189 if (ret < 0) {
190 error_setg_errno(errp, errno, "Failed to set time to guest");
191 return;
192 }
193 }
194
195 /* Now, if user has passed a time to set and the system time is set, we
196 * just need to synchronize the hardware clock. However, if no time was
197 * passed, user is requesting the opposite: set the system time from the
198 * hardware clock (RTC). */
199 pid = fork();
200 if (pid == 0) {
201 setsid();
202 reopen_fd_to_null(0);
203 reopen_fd_to_null(1);
204 reopen_fd_to_null(2);
205
206 /* Use '/sbin/hwclock -w' to set RTC from the system time,
207 * or '/sbin/hwclock -s' to set the system time from RTC. */
208 execl(hwclock_path, "hwclock", has_time ? "-w" : "-s", NULL);
209 _exit(EXIT_FAILURE);
210 } else if (pid < 0) {
211 error_setg_errno(errp, errno, "failed to create child process");
212 return;
213 }
214
215 ga_wait_child(pid, &status, &local_err);
216 if (local_err) {
217 error_propagate(errp, local_err);
218 return;
219 }
220
221 if (!WIFEXITED(status)) {
222 error_setg(errp, "child process has terminated abnormally");
223 return;
224 }
225
226 if (WEXITSTATUS(status)) {
227 error_setg(errp, "hwclock failed to set hardware clock to system time");
228 return;
229 }
230 }
231
232 typedef enum {
233 RW_STATE_NEW,
234 RW_STATE_READING,
235 RW_STATE_WRITING,
236 } RwState;
237
238 struct GuestFileHandle {
239 uint64_t id;
240 FILE *fh;
241 RwState state;
242 QTAILQ_ENTRY(GuestFileHandle) next;
243 };
244
245 static struct {
246 QTAILQ_HEAD(, GuestFileHandle) filehandles;
247 } guest_file_state = {
248 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
249 };
250
251 static int64_t guest_file_handle_add(FILE *fh, Error **errp)
252 {
253 GuestFileHandle *gfh;
254 int64_t handle;
255
256 handle = ga_get_fd_handle(ga_state, errp);
257 if (handle < 0) {
258 return -1;
259 }
260
261 gfh = g_new0(GuestFileHandle, 1);
262 gfh->id = handle;
263 gfh->fh = fh;
264 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
265
266 return handle;
267 }
268
269 GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
270 {
271 GuestFileHandle *gfh;
272
273 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
274 {
275 if (gfh->id == id) {
276 return gfh;
277 }
278 }
279
280 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
281 return NULL;
282 }
283
284 typedef const char * const ccpc;
285
286 #ifndef O_BINARY
287 #define O_BINARY 0
288 #endif
289
290 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
291 static const struct {
292 ccpc *forms;
293 int oflag_base;
294 } guest_file_open_modes[] = {
295 { (ccpc[]){ "r", NULL }, O_RDONLY },
296 { (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
297 { (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
298 { (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
299 { (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
300 { (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
301 { (ccpc[]){ "r+", NULL }, O_RDWR },
302 { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
303 { (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
304 { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
305 { (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
306 { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
307 };
308
309 static int
310 find_open_flag(const char *mode_str, Error **errp)
311 {
312 unsigned mode;
313
314 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
315 ccpc *form;
316
317 form = guest_file_open_modes[mode].forms;
318 while (*form != NULL && strcmp(*form, mode_str) != 0) {
319 ++form;
320 }
321 if (*form != NULL) {
322 break;
323 }
324 }
325
326 if (mode == ARRAY_SIZE(guest_file_open_modes)) {
327 error_setg(errp, "invalid file open mode '%s'", mode_str);
328 return -1;
329 }
330 return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
331 }
332
333 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
334 S_IRGRP | S_IWGRP | \
335 S_IROTH | S_IWOTH)
336
337 static FILE *
338 safe_open_or_create(const char *path, const char *mode, Error **errp)
339 {
340 Error *local_err = NULL;
341 int oflag;
342
343 oflag = find_open_flag(mode, &local_err);
344 if (local_err == NULL) {
345 int fd;
346
347 /* If the caller wants / allows creation of a new file, we implement it
348 * with a two step process: open() + (open() / fchmod()).
349 *
350 * First we insist on creating the file exclusively as a new file. If
351 * that succeeds, we're free to set any file-mode bits on it. (The
352 * motivation is that we want to set those file-mode bits independently
353 * of the current umask.)
354 *
355 * If the exclusive creation fails because the file already exists
356 * (EEXIST is not possible for any other reason), we just attempt to
357 * open the file, but in this case we won't be allowed to change the
358 * file-mode bits on the preexistent file.
359 *
360 * The pathname should never disappear between the two open()s in
361 * practice. If it happens, then someone very likely tried to race us.
362 * In this case just go ahead and report the ENOENT from the second
363 * open() to the caller.
364 *
365 * If the caller wants to open a preexistent file, then the first
366 * open() is decisive and its third argument is ignored, and the second
367 * open() and the fchmod() are never called.
368 */
369 fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
370 if (fd == -1 && errno == EEXIST) {
371 oflag &= ~(unsigned)O_CREAT;
372 fd = open(path, oflag);
373 }
374
375 if (fd == -1) {
376 error_setg_errno(&local_err, errno, "failed to open file '%s' "
377 "(mode: '%s')", path, mode);
378 } else {
379 qemu_set_cloexec(fd);
380
381 if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
382 error_setg_errno(&local_err, errno, "failed to set permission "
383 "0%03o on new file '%s' (mode: '%s')",
384 (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
385 } else {
386 FILE *f;
387
388 f = fdopen(fd, mode);
389 if (f == NULL) {
390 error_setg_errno(&local_err, errno, "failed to associate "
391 "stdio stream with file descriptor %d, "
392 "file '%s' (mode: '%s')", fd, path, mode);
393 } else {
394 return f;
395 }
396 }
397
398 close(fd);
399 if (oflag & O_CREAT) {
400 unlink(path);
401 }
402 }
403 }
404
405 error_propagate(errp, local_err);
406 return NULL;
407 }
408
409 int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
410 Error **errp)
411 {
412 FILE *fh;
413 Error *local_err = NULL;
414 int64_t handle;
415
416 if (!has_mode) {
417 mode = "r";
418 }
419 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
420 fh = safe_open_or_create(path, mode, &local_err);
421 if (local_err != NULL) {
422 error_propagate(errp, local_err);
423 return -1;
424 }
425
426 /* set fd non-blocking to avoid common use cases (like reading from a
427 * named pipe) from hanging the agent
428 */
429 if (!g_unix_set_fd_nonblocking(fileno(fh), true, NULL)) {
430 fclose(fh);
431 error_setg_errno(errp, errno, "Failed to set FD nonblocking");
432 return -1;
433 }
434
435 handle = guest_file_handle_add(fh, errp);
436 if (handle < 0) {
437 fclose(fh);
438 return -1;
439 }
440
441 slog("guest-file-open, handle: %" PRId64, handle);
442 return handle;
443 }
444
445 void qmp_guest_file_close(int64_t handle, Error **errp)
446 {
447 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
448 int ret;
449
450 slog("guest-file-close called, handle: %" PRId64, handle);
451 if (!gfh) {
452 return;
453 }
454
455 ret = fclose(gfh->fh);
456 if (ret == EOF) {
457 error_setg_errno(errp, errno, "failed to close handle");
458 return;
459 }
460
461 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
462 g_free(gfh);
463 }
464
465 GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
466 int64_t count, Error **errp)
467 {
468 GuestFileRead *read_data = NULL;
469 guchar *buf;
470 FILE *fh = gfh->fh;
471 size_t read_count;
472
473 /* explicitly flush when switching from writing to reading */
474 if (gfh->state == RW_STATE_WRITING) {
475 int ret = fflush(fh);
476 if (ret == EOF) {
477 error_setg_errno(errp, errno, "failed to flush file");
478 return NULL;
479 }
480 gfh->state = RW_STATE_NEW;
481 }
482
483 buf = g_malloc0(count + 1);
484 read_count = fread(buf, 1, count, fh);
485 if (ferror(fh)) {
486 error_setg_errno(errp, errno, "failed to read file");
487 } else {
488 buf[read_count] = 0;
489 read_data = g_new0(GuestFileRead, 1);
490 read_data->count = read_count;
491 read_data->eof = feof(fh);
492 if (read_count) {
493 read_data->buf_b64 = g_base64_encode(buf, read_count);
494 }
495 gfh->state = RW_STATE_READING;
496 }
497 g_free(buf);
498 clearerr(fh);
499
500 return read_data;
501 }
502
503 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
504 bool has_count, int64_t count,
505 Error **errp)
506 {
507 GuestFileWrite *write_data = NULL;
508 guchar *buf;
509 gsize buf_len;
510 int write_count;
511 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
512 FILE *fh;
513
514 if (!gfh) {
515 return NULL;
516 }
517
518 fh = gfh->fh;
519
520 if (gfh->state == RW_STATE_READING) {
521 int ret = fseek(fh, 0, SEEK_CUR);
522 if (ret == -1) {
523 error_setg_errno(errp, errno, "failed to seek file");
524 return NULL;
525 }
526 gfh->state = RW_STATE_NEW;
527 }
528
529 buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
530 if (!buf) {
531 return NULL;
532 }
533
534 if (!has_count) {
535 count = buf_len;
536 } else if (count < 0 || count > buf_len) {
537 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
538 count);
539 g_free(buf);
540 return NULL;
541 }
542
543 write_count = fwrite(buf, 1, count, fh);
544 if (ferror(fh)) {
545 error_setg_errno(errp, errno, "failed to write to file");
546 slog("guest-file-write failed, handle: %" PRId64, handle);
547 } else {
548 write_data = g_new0(GuestFileWrite, 1);
549 write_data->count = write_count;
550 write_data->eof = feof(fh);
551 gfh->state = RW_STATE_WRITING;
552 }
553 g_free(buf);
554 clearerr(fh);
555
556 return write_data;
557 }
558
559 struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
560 GuestFileWhence *whence_code,
561 Error **errp)
562 {
563 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
564 GuestFileSeek *seek_data = NULL;
565 FILE *fh;
566 int ret;
567 int whence;
568 Error *err = NULL;
569
570 if (!gfh) {
571 return NULL;
572 }
573
574 /* We stupidly exposed 'whence':'int' in our qapi */
575 whence = ga_parse_whence(whence_code, &err);
576 if (err) {
577 error_propagate(errp, err);
578 return NULL;
579 }
580
581 fh = gfh->fh;
582 ret = fseek(fh, offset, whence);
583 if (ret == -1) {
584 error_setg_errno(errp, errno, "failed to seek file");
585 if (errno == ESPIPE) {
586 /* file is non-seekable, stdio shouldn't be buffering anyways */
587 gfh->state = RW_STATE_NEW;
588 }
589 } else {
590 seek_data = g_new0(GuestFileSeek, 1);
591 seek_data->position = ftell(fh);
592 seek_data->eof = feof(fh);
593 gfh->state = RW_STATE_NEW;
594 }
595 clearerr(fh);
596
597 return seek_data;
598 }
599
600 void qmp_guest_file_flush(int64_t handle, Error **errp)
601 {
602 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
603 FILE *fh;
604 int ret;
605
606 if (!gfh) {
607 return;
608 }
609
610 fh = gfh->fh;
611 ret = fflush(fh);
612 if (ret == EOF) {
613 error_setg_errno(errp, errno, "failed to flush file");
614 } else {
615 gfh->state = RW_STATE_NEW;
616 }
617 }
618
619 /* linux-specific implementations. avoid this if at all possible. */
620 #if defined(__linux__)
621
622 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
623 typedef struct FsMount {
624 char *dirname;
625 char *devtype;
626 unsigned int devmajor, devminor;
627 QTAILQ_ENTRY(FsMount) next;
628 } FsMount;
629
630 typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
631
632 static void free_fs_mount_list(FsMountList *mounts)
633 {
634 FsMount *mount, *temp;
635
636 if (!mounts) {
637 return;
638 }
639
640 QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
641 QTAILQ_REMOVE(mounts, mount, next);
642 g_free(mount->dirname);
643 g_free(mount->devtype);
644 g_free(mount);
645 }
646 }
647
648 static int dev_major_minor(const char *devpath,
649 unsigned int *devmajor, unsigned int *devminor)
650 {
651 struct stat st;
652
653 *devmajor = 0;
654 *devminor = 0;
655
656 if (stat(devpath, &st) < 0) {
657 slog("failed to stat device file '%s': %s", devpath, strerror(errno));
658 return -1;
659 }
660 if (S_ISDIR(st.st_mode)) {
661 /* It is bind mount */
662 return -2;
663 }
664 if (S_ISBLK(st.st_mode)) {
665 *devmajor = major(st.st_rdev);
666 *devminor = minor(st.st_rdev);
667 return 0;
668 }
669 return -1;
670 }
671
672 /*
673 * Walk the mount table and build a list of local file systems
674 */
675 static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
676 {
677 struct mntent *ment;
678 FsMount *mount;
679 char const *mtab = "/proc/self/mounts";
680 FILE *fp;
681 unsigned int devmajor, devminor;
682
683 fp = setmntent(mtab, "r");
684 if (!fp) {
685 error_setg(errp, "failed to open mtab file: '%s'", mtab);
686 return;
687 }
688
689 while ((ment = getmntent(fp))) {
690 /*
691 * An entry which device name doesn't start with a '/' is
692 * either a dummy file system or a network file system.
693 * Add special handling for smbfs and cifs as is done by
694 * coreutils as well.
695 */
696 if ((ment->mnt_fsname[0] != '/') ||
697 (strcmp(ment->mnt_type, "smbfs") == 0) ||
698 (strcmp(ment->mnt_type, "cifs") == 0)) {
699 continue;
700 }
701 if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
702 /* Skip bind mounts */
703 continue;
704 }
705
706 mount = g_new0(FsMount, 1);
707 mount->dirname = g_strdup(ment->mnt_dir);
708 mount->devtype = g_strdup(ment->mnt_type);
709 mount->devmajor = devmajor;
710 mount->devminor = devminor;
711
712 QTAILQ_INSERT_TAIL(mounts, mount, next);
713 }
714
715 endmntent(fp);
716 }
717
718 static void decode_mntname(char *name, int len)
719 {
720 int i, j = 0;
721 for (i = 0; i <= len; i++) {
722 if (name[i] != '\\') {
723 name[j++] = name[i];
724 } else if (name[i + 1] == '\\') {
725 name[j++] = '\\';
726 i++;
727 } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
728 name[i + 2] >= '0' && name[i + 2] <= '7' &&
729 name[i + 3] >= '0' && name[i + 3] <= '7') {
730 name[j++] = (name[i + 1] - '0') * 64 +
731 (name[i + 2] - '0') * 8 +
732 (name[i + 3] - '0');
733 i += 3;
734 } else {
735 name[j++] = name[i];
736 }
737 }
738 }
739
740 static void build_fs_mount_list(FsMountList *mounts, Error **errp)
741 {
742 FsMount *mount;
743 char const *mountinfo = "/proc/self/mountinfo";
744 FILE *fp;
745 char *line = NULL, *dash;
746 size_t n;
747 char check;
748 unsigned int devmajor, devminor;
749 int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
750
751 fp = fopen(mountinfo, "r");
752 if (!fp) {
753 build_fs_mount_list_from_mtab(mounts, errp);
754 return;
755 }
756
757 while (getline(&line, &n, fp) != -1) {
758 ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
759 &devmajor, &devminor, &dir_s, &dir_e, &check);
760 if (ret < 3) {
761 continue;
762 }
763 dash = strstr(line + dir_e, " - ");
764 if (!dash) {
765 continue;
766 }
767 ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
768 &type_s, &type_e, &dev_s, &dev_e, &check);
769 if (ret < 1) {
770 continue;
771 }
772 line[dir_e] = 0;
773 dash[type_e] = 0;
774 dash[dev_e] = 0;
775 decode_mntname(line + dir_s, dir_e - dir_s);
776 decode_mntname(dash + dev_s, dev_e - dev_s);
777 if (devmajor == 0) {
778 /* btrfs reports major number = 0 */
779 if (strcmp("btrfs", dash + type_s) != 0 ||
780 dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
781 continue;
782 }
783 }
784
785 mount = g_new0(FsMount, 1);
786 mount->dirname = g_strdup(line + dir_s);
787 mount->devtype = g_strdup(dash + type_s);
788 mount->devmajor = devmajor;
789 mount->devminor = devminor;
790
791 QTAILQ_INSERT_TAIL(mounts, mount, next);
792 }
793 free(line);
794
795 fclose(fp);
796 }
797 #endif
798
799 #if defined(CONFIG_FSFREEZE)
800
801 static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
802 {
803 char *path;
804 char *dpath;
805 char *driver = NULL;
806 char buf[PATH_MAX];
807 ssize_t len;
808
809 path = g_strndup(syspath, pathlen);
810 dpath = g_strdup_printf("%s/driver", path);
811 len = readlink(dpath, buf, sizeof(buf) - 1);
812 if (len != -1) {
813 buf[len] = 0;
814 driver = g_path_get_basename(buf);
815 }
816 g_free(dpath);
817 g_free(path);
818 return driver;
819 }
820
821 static int compare_uint(const void *_a, const void *_b)
822 {
823 unsigned int a = *(unsigned int *)_a;
824 unsigned int b = *(unsigned int *)_b;
825
826 return a < b ? -1 : a > b ? 1 : 0;
827 }
828
829 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
830 static int build_hosts(char const *syspath, char const *host, bool ata,
831 unsigned int *hosts, int hosts_max, Error **errp)
832 {
833 char *path;
834 DIR *dir;
835 struct dirent *entry;
836 int i = 0;
837
838 path = g_strndup(syspath, host - syspath);
839 dir = opendir(path);
840 if (!dir) {
841 error_setg_errno(errp, errno, "opendir(\"%s\")", path);
842 g_free(path);
843 return -1;
844 }
845
846 while (i < hosts_max) {
847 entry = readdir(dir);
848 if (!entry) {
849 break;
850 }
851 if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
852 ++i;
853 } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
854 ++i;
855 }
856 }
857
858 qsort(hosts, i, sizeof(hosts[0]), compare_uint);
859
860 g_free(path);
861 closedir(dir);
862 return i;
863 }
864
865 /*
866 * Store disk device info for devices on the PCI bus.
867 * Returns true if information has been stored, or false for failure.
868 */
869 static bool build_guest_fsinfo_for_pci_dev(char const *syspath,
870 GuestDiskAddress *disk,
871 Error **errp)
872 {
873 unsigned int pci[4], host, hosts[8], tgt[3];
874 int i, nhosts = 0, pcilen;
875 GuestPCIAddress *pciaddr = disk->pci_controller;
876 bool has_ata = false, has_host = false, has_tgt = false;
877 char *p, *q, *driver = NULL;
878 bool ret = false;
879
880 p = strstr(syspath, "/devices/pci");
881 if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
882 pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
883 g_debug("only pci device is supported: sysfs path '%s'", syspath);
884 return false;
885 }
886
887 p += 12 + pcilen;
888 while (true) {
889 driver = get_pci_driver(syspath, p - syspath, errp);
890 if (driver && (g_str_equal(driver, "ata_piix") ||
891 g_str_equal(driver, "sym53c8xx") ||
892 g_str_equal(driver, "virtio-pci") ||
893 g_str_equal(driver, "ahci"))) {
894 break;
895 }
896
897 g_free(driver);
898 if (sscanf(p, "/%x:%x:%x.%x%n",
899 pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) {
900 p += pcilen;
901 continue;
902 }
903
904 g_debug("unsupported driver or sysfs path '%s'", syspath);
905 return false;
906 }
907
908 p = strstr(syspath, "/target");
909 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
910 tgt, tgt + 1, tgt + 2) == 3) {
911 has_tgt = true;
912 }
913
914 p = strstr(syspath, "/ata");
915 if (p) {
916 q = p + 4;
917 has_ata = true;
918 } else {
919 p = strstr(syspath, "/host");
920 q = p + 5;
921 }
922 if (p && sscanf(q, "%u", &host) == 1) {
923 has_host = true;
924 nhosts = build_hosts(syspath, p, has_ata, hosts,
925 ARRAY_SIZE(hosts), errp);
926 if (nhosts < 0) {
927 goto cleanup;
928 }
929 }
930
931 pciaddr->domain = pci[0];
932 pciaddr->bus = pci[1];
933 pciaddr->slot = pci[2];
934 pciaddr->function = pci[3];
935
936 if (strcmp(driver, "ata_piix") == 0) {
937 /* a host per ide bus, target*:0:<unit>:0 */
938 if (!has_host || !has_tgt) {
939 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
940 goto cleanup;
941 }
942 for (i = 0; i < nhosts; i++) {
943 if (host == hosts[i]) {
944 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
945 disk->bus = i;
946 disk->unit = tgt[1];
947 break;
948 }
949 }
950 if (i >= nhosts) {
951 g_debug("no host for '%s' (driver '%s')", syspath, driver);
952 goto cleanup;
953 }
954 } else if (strcmp(driver, "sym53c8xx") == 0) {
955 /* scsi(LSI Logic): target*:0:<unit>:0 */
956 if (!has_tgt) {
957 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
958 goto cleanup;
959 }
960 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
961 disk->unit = tgt[1];
962 } else if (strcmp(driver, "virtio-pci") == 0) {
963 if (has_tgt) {
964 /* virtio-scsi: target*:0:0:<unit> */
965 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
966 disk->unit = tgt[2];
967 } else {
968 /* virtio-blk: 1 disk per 1 device */
969 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
970 }
971 } else if (strcmp(driver, "ahci") == 0) {
972 /* ahci: 1 host per 1 unit */
973 if (!has_host || !has_tgt) {
974 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
975 goto cleanup;
976 }
977 for (i = 0; i < nhosts; i++) {
978 if (host == hosts[i]) {
979 disk->unit = i;
980 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
981 break;
982 }
983 }
984 if (i >= nhosts) {
985 g_debug("no host for '%s' (driver '%s')", syspath, driver);
986 goto cleanup;
987 }
988 } else {
989 g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
990 goto cleanup;
991 }
992
993 ret = true;
994
995 cleanup:
996 g_free(driver);
997 return ret;
998 }
999
1000 /*
1001 * Store disk device info for non-PCI virtio devices (for example s390x
1002 * channel I/O devices). Returns true if information has been stored, or
1003 * false for failure.
1004 */
1005 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath,
1006 GuestDiskAddress *disk,
1007 Error **errp)
1008 {
1009 unsigned int tgt[3];
1010 char *p;
1011
1012 if (!strstr(syspath, "/virtio") || !strstr(syspath, "/block")) {
1013 g_debug("Unsupported virtio device '%s'", syspath);
1014 return false;
1015 }
1016
1017 p = strstr(syspath, "/target");
1018 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1019 &tgt[0], &tgt[1], &tgt[2]) == 3) {
1020 /* virtio-scsi: target*:0:<target>:<unit> */
1021 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
1022 disk->bus = tgt[0];
1023 disk->target = tgt[1];
1024 disk->unit = tgt[2];
1025 } else {
1026 /* virtio-blk: 1 disk per 1 device */
1027 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
1028 }
1029
1030 return true;
1031 }
1032
1033 /*
1034 * Store disk device info for CCW devices (s390x channel I/O devices).
1035 * Returns true if information has been stored, or false for failure.
1036 */
1037 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath,
1038 GuestDiskAddress *disk,
1039 Error **errp)
1040 {
1041 unsigned int cssid, ssid, subchno, devno;
1042 char *p;
1043
1044 p = strstr(syspath, "/devices/css");
1045 if (!p || sscanf(p + 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1046 &cssid, &ssid, &subchno, &devno) < 4) {
1047 g_debug("could not parse ccw device sysfs path: %s", syspath);
1048 return false;
1049 }
1050
1051 disk->has_ccw_address = true;
1052 disk->ccw_address = g_new0(GuestCCWAddress, 1);
1053 disk->ccw_address->cssid = cssid;
1054 disk->ccw_address->ssid = ssid;
1055 disk->ccw_address->subchno = subchno;
1056 disk->ccw_address->devno = devno;
1057
1058 if (strstr(p, "/virtio")) {
1059 build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
1060 }
1061
1062 return true;
1063 }
1064
1065 /* Store disk device info specified by @sysfs into @fs */
1066 static void build_guest_fsinfo_for_real_device(char const *syspath,
1067 GuestFilesystemInfo *fs,
1068 Error **errp)
1069 {
1070 GuestDiskAddress *disk;
1071 GuestPCIAddress *pciaddr;
1072 bool has_hwinf;
1073 #ifdef CONFIG_LIBUDEV
1074 struct udev *udev = NULL;
1075 struct udev_device *udevice = NULL;
1076 #endif
1077
1078 pciaddr = g_new0(GuestPCIAddress, 1);
1079 pciaddr->domain = -1; /* -1 means field is invalid */
1080 pciaddr->bus = -1;
1081 pciaddr->slot = -1;
1082 pciaddr->function = -1;
1083
1084 disk = g_new0(GuestDiskAddress, 1);
1085 disk->pci_controller = pciaddr;
1086 disk->bus_type = GUEST_DISK_BUS_TYPE_UNKNOWN;
1087
1088 #ifdef CONFIG_LIBUDEV
1089 udev = udev_new();
1090 udevice = udev_device_new_from_syspath(udev, syspath);
1091 if (udev == NULL || udevice == NULL) {
1092 g_debug("failed to query udev");
1093 } else {
1094 const char *devnode, *serial;
1095 devnode = udev_device_get_devnode(udevice);
1096 if (devnode != NULL) {
1097 disk->dev = g_strdup(devnode);
1098 disk->has_dev = true;
1099 }
1100 serial = udev_device_get_property_value(udevice, "ID_SERIAL");
1101 if (serial != NULL && *serial != 0) {
1102 disk->serial = g_strdup(serial);
1103 disk->has_serial = true;
1104 }
1105 }
1106
1107 udev_unref(udev);
1108 udev_device_unref(udevice);
1109 #endif
1110
1111 if (strstr(syspath, "/devices/pci")) {
1112 has_hwinf = build_guest_fsinfo_for_pci_dev(syspath, disk, errp);
1113 } else if (strstr(syspath, "/devices/css")) {
1114 has_hwinf = build_guest_fsinfo_for_ccw_dev(syspath, disk, errp);
1115 } else if (strstr(syspath, "/virtio")) {
1116 has_hwinf = build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
1117 } else {
1118 g_debug("Unsupported device type for '%s'", syspath);
1119 has_hwinf = false;
1120 }
1121
1122 if (has_hwinf || disk->has_dev || disk->has_serial) {
1123 QAPI_LIST_PREPEND(fs->disk, disk);
1124 } else {
1125 qapi_free_GuestDiskAddress(disk);
1126 }
1127 }
1128
1129 static void build_guest_fsinfo_for_device(char const *devpath,
1130 GuestFilesystemInfo *fs,
1131 Error **errp);
1132
1133 /* Store a list of slave devices of virtual volume specified by @syspath into
1134 * @fs */
1135 static void build_guest_fsinfo_for_virtual_device(char const *syspath,
1136 GuestFilesystemInfo *fs,
1137 Error **errp)
1138 {
1139 Error *err = NULL;
1140 DIR *dir;
1141 char *dirpath;
1142 struct dirent *entry;
1143
1144 dirpath = g_strdup_printf("%s/slaves", syspath);
1145 dir = opendir(dirpath);
1146 if (!dir) {
1147 if (errno != ENOENT) {
1148 error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
1149 }
1150 g_free(dirpath);
1151 return;
1152 }
1153
1154 for (;;) {
1155 errno = 0;
1156 entry = readdir(dir);
1157 if (entry == NULL) {
1158 if (errno) {
1159 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
1160 }
1161 break;
1162 }
1163
1164 if (entry->d_type == DT_LNK) {
1165 char *path;
1166
1167 g_debug(" slave device '%s'", entry->d_name);
1168 path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
1169 build_guest_fsinfo_for_device(path, fs, &err);
1170 g_free(path);
1171
1172 if (err) {
1173 error_propagate(errp, err);
1174 break;
1175 }
1176 }
1177 }
1178
1179 g_free(dirpath);
1180 closedir(dir);
1181 }
1182
1183 static bool is_disk_virtual(const char *devpath, Error **errp)
1184 {
1185 g_autofree char *syspath = realpath(devpath, NULL);
1186
1187 if (!syspath) {
1188 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1189 return false;
1190 }
1191 return strstr(syspath, "/devices/virtual/block/") != NULL;
1192 }
1193
1194 /* Dispatch to functions for virtual/real device */
1195 static void build_guest_fsinfo_for_device(char const *devpath,
1196 GuestFilesystemInfo *fs,
1197 Error **errp)
1198 {
1199 ERRP_GUARD();
1200 g_autofree char *syspath = NULL;
1201 bool is_virtual = false;
1202
1203 syspath = realpath(devpath, NULL);
1204 if (!syspath) {
1205 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1206 return;
1207 }
1208
1209 if (!fs->name) {
1210 fs->name = g_path_get_basename(syspath);
1211 }
1212
1213 g_debug(" parse sysfs path '%s'", syspath);
1214 is_virtual = is_disk_virtual(syspath, errp);
1215 if (*errp != NULL) {
1216 return;
1217 }
1218 if (is_virtual) {
1219 build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1220 } else {
1221 build_guest_fsinfo_for_real_device(syspath, fs, errp);
1222 }
1223 }
1224
1225 #ifdef CONFIG_LIBUDEV
1226
1227 /*
1228 * Wrapper around build_guest_fsinfo_for_device() for getting just
1229 * the disk address.
1230 */
1231 static GuestDiskAddress *get_disk_address(const char *syspath, Error **errp)
1232 {
1233 g_autoptr(GuestFilesystemInfo) fs = NULL;
1234
1235 fs = g_new0(GuestFilesystemInfo, 1);
1236 build_guest_fsinfo_for_device(syspath, fs, errp);
1237 if (fs->disk != NULL) {
1238 return g_steal_pointer(&fs->disk->value);
1239 }
1240 return NULL;
1241 }
1242
1243 static char *get_alias_for_syspath(const char *syspath)
1244 {
1245 struct udev *udev = NULL;
1246 struct udev_device *udevice = NULL;
1247 char *ret = NULL;
1248
1249 udev = udev_new();
1250 if (udev == NULL) {
1251 g_debug("failed to query udev");
1252 goto out;
1253 }
1254 udevice = udev_device_new_from_syspath(udev, syspath);
1255 if (udevice == NULL) {
1256 g_debug("failed to query udev for path: %s", syspath);
1257 goto out;
1258 } else {
1259 const char *alias = udev_device_get_property_value(
1260 udevice, "DM_NAME");
1261 /*
1262 * NULL means there was an error and empty string means there is no
1263 * alias. In case of no alias we return NULL instead of empty string.
1264 */
1265 if (alias == NULL) {
1266 g_debug("failed to query udev for device alias for: %s",
1267 syspath);
1268 } else if (*alias != 0) {
1269 ret = g_strdup(alias);
1270 }
1271 }
1272
1273 out:
1274 udev_unref(udev);
1275 udev_device_unref(udevice);
1276 return ret;
1277 }
1278
1279 static char *get_device_for_syspath(const char *syspath)
1280 {
1281 struct udev *udev = NULL;
1282 struct udev_device *udevice = NULL;
1283 char *ret = NULL;
1284
1285 udev = udev_new();
1286 if (udev == NULL) {
1287 g_debug("failed to query udev");
1288 goto out;
1289 }
1290 udevice = udev_device_new_from_syspath(udev, syspath);
1291 if (udevice == NULL) {
1292 g_debug("failed to query udev for path: %s", syspath);
1293 goto out;
1294 } else {
1295 ret = g_strdup(udev_device_get_devnode(udevice));
1296 }
1297
1298 out:
1299 udev_unref(udev);
1300 udev_device_unref(udevice);
1301 return ret;
1302 }
1303
1304 static void get_disk_deps(const char *disk_dir, GuestDiskInfo *disk)
1305 {
1306 g_autofree char *deps_dir = NULL;
1307 const gchar *dep;
1308 GDir *dp_deps = NULL;
1309
1310 /* List dependent disks */
1311 deps_dir = g_strdup_printf("%s/slaves", disk_dir);
1312 g_debug(" listing entries in: %s", deps_dir);
1313 dp_deps = g_dir_open(deps_dir, 0, NULL);
1314 if (dp_deps == NULL) {
1315 g_debug("failed to list entries in %s", deps_dir);
1316 return;
1317 }
1318 disk->has_dependencies = true;
1319 while ((dep = g_dir_read_name(dp_deps)) != NULL) {
1320 g_autofree char *dep_dir = NULL;
1321 char *dev_name;
1322
1323 /* Add dependent disks */
1324 dep_dir = g_strdup_printf("%s/%s", deps_dir, dep);
1325 dev_name = get_device_for_syspath(dep_dir);
1326 if (dev_name != NULL) {
1327 g_debug(" adding dependent device: %s", dev_name);
1328 QAPI_LIST_PREPEND(disk->dependencies, dev_name);
1329 }
1330 }
1331 g_dir_close(dp_deps);
1332 }
1333
1334 /*
1335 * Detect partitions subdirectory, name is "<disk_name><number>" or
1336 * "<disk_name>p<number>"
1337 *
1338 * @disk_name -- last component of /sys path (e.g. sda)
1339 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1340 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1341 */
1342 static GuestDiskInfoList *get_disk_partitions(
1343 GuestDiskInfoList *list,
1344 const char *disk_name, const char *disk_dir,
1345 const char *disk_dev)
1346 {
1347 GuestDiskInfoList *ret = list;
1348 struct dirent *de_disk;
1349 DIR *dp_disk = NULL;
1350 size_t len = strlen(disk_name);
1351
1352 dp_disk = opendir(disk_dir);
1353 while ((de_disk = readdir(dp_disk)) != NULL) {
1354 g_autofree char *partition_dir = NULL;
1355 char *dev_name;
1356 GuestDiskInfo *partition;
1357
1358 if (!(de_disk->d_type & DT_DIR)) {
1359 continue;
1360 }
1361
1362 if (!(strncmp(disk_name, de_disk->d_name, len) == 0 &&
1363 ((*(de_disk->d_name + len) == 'p' &&
1364 isdigit(*(de_disk->d_name + len + 1))) ||
1365 isdigit(*(de_disk->d_name + len))))) {
1366 continue;
1367 }
1368
1369 partition_dir = g_strdup_printf("%s/%s",
1370 disk_dir, de_disk->d_name);
1371 dev_name = get_device_for_syspath(partition_dir);
1372 if (dev_name == NULL) {
1373 g_debug("Failed to get device name for syspath: %s",
1374 disk_dir);
1375 continue;
1376 }
1377 partition = g_new0(GuestDiskInfo, 1);
1378 partition->name = dev_name;
1379 partition->partition = true;
1380 partition->has_dependencies = true;
1381 /* Add parent disk as dependent for easier tracking of hierarchy */
1382 QAPI_LIST_PREPEND(partition->dependencies, g_strdup(disk_dev));
1383
1384 QAPI_LIST_PREPEND(ret, partition);
1385 }
1386 closedir(dp_disk);
1387
1388 return ret;
1389 }
1390
1391 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1392 {
1393 GuestDiskInfoList *ret = NULL;
1394 GuestDiskInfo *disk;
1395 DIR *dp = NULL;
1396 struct dirent *de = NULL;
1397
1398 g_debug("listing /sys/block directory");
1399 dp = opendir("/sys/block");
1400 if (dp == NULL) {
1401 error_setg_errno(errp, errno, "Can't open directory \"/sys/block\"");
1402 return NULL;
1403 }
1404 while ((de = readdir(dp)) != NULL) {
1405 g_autofree char *disk_dir = NULL, *line = NULL,
1406 *size_path = NULL;
1407 char *dev_name;
1408 Error *local_err = NULL;
1409 if (de->d_type != DT_LNK) {
1410 g_debug(" skipping entry: %s", de->d_name);
1411 continue;
1412 }
1413
1414 /* Check size and skip zero-sized disks */
1415 g_debug(" checking disk size");
1416 size_path = g_strdup_printf("/sys/block/%s/size", de->d_name);
1417 if (!g_file_get_contents(size_path, &line, NULL, NULL)) {
1418 g_debug(" failed to read disk size");
1419 continue;
1420 }
1421 if (g_strcmp0(line, "0\n") == 0) {
1422 g_debug(" skipping zero-sized disk");
1423 continue;
1424 }
1425
1426 g_debug(" adding %s", de->d_name);
1427 disk_dir = g_strdup_printf("/sys/block/%s", de->d_name);
1428 dev_name = get_device_for_syspath(disk_dir);
1429 if (dev_name == NULL) {
1430 g_debug("Failed to get device name for syspath: %s",
1431 disk_dir);
1432 continue;
1433 }
1434 disk = g_new0(GuestDiskInfo, 1);
1435 disk->name = dev_name;
1436 disk->partition = false;
1437 disk->alias = get_alias_for_syspath(disk_dir);
1438 disk->has_alias = (disk->alias != NULL);
1439 QAPI_LIST_PREPEND(ret, disk);
1440
1441 /* Get address for non-virtual devices */
1442 bool is_virtual = is_disk_virtual(disk_dir, &local_err);
1443 if (local_err != NULL) {
1444 g_debug(" failed to check disk path, ignoring error: %s",
1445 error_get_pretty(local_err));
1446 error_free(local_err);
1447 local_err = NULL;
1448 /* Don't try to get the address */
1449 is_virtual = true;
1450 }
1451 if (!is_virtual) {
1452 disk->address = get_disk_address(disk_dir, &local_err);
1453 if (local_err != NULL) {
1454 g_debug(" failed to get device info, ignoring error: %s",
1455 error_get_pretty(local_err));
1456 error_free(local_err);
1457 local_err = NULL;
1458 } else if (disk->address != NULL) {
1459 disk->has_address = true;
1460 }
1461 }
1462
1463 get_disk_deps(disk_dir, disk);
1464 ret = get_disk_partitions(ret, de->d_name, disk_dir, dev_name);
1465 }
1466
1467 closedir(dp);
1468
1469 return ret;
1470 }
1471
1472 #else
1473
1474 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1475 {
1476 error_setg(errp, QERR_UNSUPPORTED);
1477 return NULL;
1478 }
1479
1480 #endif
1481
1482 /* Return a list of the disk device(s)' info which @mount lies on */
1483 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1484 Error **errp)
1485 {
1486 GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1487 struct statvfs buf;
1488 unsigned long used, nonroot_total, fr_size;
1489 char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1490 mount->devmajor, mount->devminor);
1491
1492 fs->mountpoint = g_strdup(mount->dirname);
1493 fs->type = g_strdup(mount->devtype);
1494 build_guest_fsinfo_for_device(devpath, fs, errp);
1495
1496 if (statvfs(fs->mountpoint, &buf) == 0) {
1497 fr_size = buf.f_frsize;
1498 used = buf.f_blocks - buf.f_bfree;
1499 nonroot_total = used + buf.f_bavail;
1500 fs->used_bytes = used * fr_size;
1501 fs->total_bytes = nonroot_total * fr_size;
1502
1503 fs->has_total_bytes = true;
1504 fs->has_used_bytes = true;
1505 }
1506
1507 g_free(devpath);
1508
1509 return fs;
1510 }
1511
1512 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1513 {
1514 FsMountList mounts;
1515 struct FsMount *mount;
1516 GuestFilesystemInfoList *ret = NULL;
1517 Error *local_err = NULL;
1518
1519 QTAILQ_INIT(&mounts);
1520 build_fs_mount_list(&mounts, &local_err);
1521 if (local_err) {
1522 error_propagate(errp, local_err);
1523 return NULL;
1524 }
1525
1526 QTAILQ_FOREACH(mount, &mounts, next) {
1527 g_debug("Building guest fsinfo for '%s'", mount->dirname);
1528
1529 QAPI_LIST_PREPEND(ret, build_guest_fsinfo(mount, &local_err));
1530 if (local_err) {
1531 error_propagate(errp, local_err);
1532 qapi_free_GuestFilesystemInfoList(ret);
1533 ret = NULL;
1534 break;
1535 }
1536 }
1537
1538 free_fs_mount_list(&mounts);
1539 return ret;
1540 }
1541
1542
1543 typedef enum {
1544 FSFREEZE_HOOK_THAW = 0,
1545 FSFREEZE_HOOK_FREEZE,
1546 } FsfreezeHookArg;
1547
1548 static const char *fsfreeze_hook_arg_string[] = {
1549 "thaw",
1550 "freeze",
1551 };
1552
1553 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
1554 {
1555 int status;
1556 pid_t pid;
1557 const char *hook;
1558 const char *arg_str = fsfreeze_hook_arg_string[arg];
1559 Error *local_err = NULL;
1560
1561 hook = ga_fsfreeze_hook(ga_state);
1562 if (!hook) {
1563 return;
1564 }
1565 if (access(hook, X_OK) != 0) {
1566 error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
1567 return;
1568 }
1569
1570 slog("executing fsfreeze hook with arg '%s'", arg_str);
1571 pid = fork();
1572 if (pid == 0) {
1573 setsid();
1574 reopen_fd_to_null(0);
1575 reopen_fd_to_null(1);
1576 reopen_fd_to_null(2);
1577
1578 execl(hook, hook, arg_str, NULL);
1579 _exit(EXIT_FAILURE);
1580 } else if (pid < 0) {
1581 error_setg_errno(errp, errno, "failed to create child process");
1582 return;
1583 }
1584
1585 ga_wait_child(pid, &status, &local_err);
1586 if (local_err) {
1587 error_propagate(errp, local_err);
1588 return;
1589 }
1590
1591 if (!WIFEXITED(status)) {
1592 error_setg(errp, "fsfreeze hook has terminated abnormally");
1593 return;
1594 }
1595
1596 status = WEXITSTATUS(status);
1597 if (status) {
1598 error_setg(errp, "fsfreeze hook has failed with status %d", status);
1599 return;
1600 }
1601 }
1602
1603 /*
1604 * Return status of freeze/thaw
1605 */
1606 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1607 {
1608 if (ga_is_frozen(ga_state)) {
1609 return GUEST_FSFREEZE_STATUS_FROZEN;
1610 }
1611
1612 return GUEST_FSFREEZE_STATUS_THAWED;
1613 }
1614
1615 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1616 {
1617 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1618 }
1619
1620 /*
1621 * Walk list of mounted file systems in the guest, and freeze the ones which
1622 * are real local file systems.
1623 */
1624 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1625 strList *mountpoints,
1626 Error **errp)
1627 {
1628 int ret = 0, i = 0;
1629 strList *list;
1630 FsMountList mounts;
1631 struct FsMount *mount;
1632 Error *local_err = NULL;
1633 int fd;
1634
1635 slog("guest-fsfreeze called");
1636
1637 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
1638 if (local_err) {
1639 error_propagate(errp, local_err);
1640 return -1;
1641 }
1642
1643 QTAILQ_INIT(&mounts);
1644 build_fs_mount_list(&mounts, &local_err);
1645 if (local_err) {
1646 error_propagate(errp, local_err);
1647 return -1;
1648 }
1649
1650 /* cannot risk guest agent blocking itself on a write in this state */
1651 ga_set_frozen(ga_state);
1652
1653 QTAILQ_FOREACH_REVERSE(mount, &mounts, next) {
1654 /* To issue fsfreeze in the reverse order of mounts, check if the
1655 * mount is listed in the list here */
1656 if (has_mountpoints) {
1657 for (list = mountpoints; list; list = list->next) {
1658 if (strcmp(list->value, mount->dirname) == 0) {
1659 break;
1660 }
1661 }
1662 if (!list) {
1663 continue;
1664 }
1665 }
1666
1667 fd = qemu_open_old(mount->dirname, O_RDONLY);
1668 if (fd == -1) {
1669 error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
1670 goto error;
1671 }
1672
1673 /* we try to cull filesystems we know won't work in advance, but other
1674 * filesystems may not implement fsfreeze for less obvious reasons.
1675 * these will report EOPNOTSUPP. we simply ignore these when tallying
1676 * the number of frozen filesystems.
1677 * if a filesystem is mounted more than once (aka bind mount) a
1678 * consecutive attempt to freeze an already frozen filesystem will
1679 * return EBUSY.
1680 *
1681 * any other error means a failure to freeze a filesystem we
1682 * expect to be freezable, so return an error in those cases
1683 * and return system to thawed state.
1684 */
1685 ret = ioctl(fd, FIFREEZE);
1686 if (ret == -1) {
1687 if (errno != EOPNOTSUPP && errno != EBUSY) {
1688 error_setg_errno(errp, errno, "failed to freeze %s",
1689 mount->dirname);
1690 close(fd);
1691 goto error;
1692 }
1693 } else {
1694 i++;
1695 }
1696 close(fd);
1697 }
1698
1699 free_fs_mount_list(&mounts);
1700 /* We may not issue any FIFREEZE here.
1701 * Just unset ga_state here and ready for the next call.
1702 */
1703 if (i == 0) {
1704 ga_unset_frozen(ga_state);
1705 }
1706 return i;
1707
1708 error:
1709 free_fs_mount_list(&mounts);
1710 qmp_guest_fsfreeze_thaw(NULL);
1711 return 0;
1712 }
1713
1714 /*
1715 * Walk list of frozen file systems in the guest, and thaw them.
1716 */
1717 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1718 {
1719 int ret;
1720 FsMountList mounts;
1721 FsMount *mount;
1722 int fd, i = 0, logged;
1723 Error *local_err = NULL;
1724
1725 QTAILQ_INIT(&mounts);
1726 build_fs_mount_list(&mounts, &local_err);
1727 if (local_err) {
1728 error_propagate(errp, local_err);
1729 return 0;
1730 }
1731
1732 QTAILQ_FOREACH(mount, &mounts, next) {
1733 logged = false;
1734 fd = qemu_open_old(mount->dirname, O_RDONLY);
1735 if (fd == -1) {
1736 continue;
1737 }
1738 /* we have no way of knowing whether a filesystem was actually unfrozen
1739 * as a result of a successful call to FITHAW, only that if an error
1740 * was returned the filesystem was *not* unfrozen by that particular
1741 * call.
1742 *
1743 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1744 * to unfreeze, continuing issuing FITHAW until an error is returned,
1745 * in which case either the filesystem is in an unfreezable state, or,
1746 * more likely, it was thawed previously (and remains so afterward).
1747 *
1748 * also, since the most recent successful call is the one that did
1749 * the actual unfreeze, we can use this to provide an accurate count
1750 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1751 * may * be useful for determining whether a filesystem was unfrozen
1752 * during the freeze/thaw phase by a process other than qemu-ga.
1753 */
1754 do {
1755 ret = ioctl(fd, FITHAW);
1756 if (ret == 0 && !logged) {
1757 i++;
1758 logged = true;
1759 }
1760 } while (ret == 0);
1761 close(fd);
1762 }
1763
1764 ga_unset_frozen(ga_state);
1765 free_fs_mount_list(&mounts);
1766
1767 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
1768
1769 return i;
1770 }
1771
1772 static void guest_fsfreeze_cleanup(void)
1773 {
1774 Error *err = NULL;
1775
1776 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1777 qmp_guest_fsfreeze_thaw(&err);
1778 if (err) {
1779 slog("failed to clean up frozen filesystems: %s",
1780 error_get_pretty(err));
1781 error_free(err);
1782 }
1783 }
1784 }
1785 #endif /* CONFIG_FSFREEZE */
1786
1787 #if defined(CONFIG_FSTRIM)
1788 /*
1789 * Walk list of mounted file systems in the guest, and trim them.
1790 */
1791 GuestFilesystemTrimResponse *
1792 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1793 {
1794 GuestFilesystemTrimResponse *response;
1795 GuestFilesystemTrimResult *result;
1796 int ret = 0;
1797 FsMountList mounts;
1798 struct FsMount *mount;
1799 int fd;
1800 Error *local_err = NULL;
1801 struct fstrim_range r;
1802
1803 slog("guest-fstrim called");
1804
1805 QTAILQ_INIT(&mounts);
1806 build_fs_mount_list(&mounts, &local_err);
1807 if (local_err) {
1808 error_propagate(errp, local_err);
1809 return NULL;
1810 }
1811
1812 response = g_malloc0(sizeof(*response));
1813
1814 QTAILQ_FOREACH(mount, &mounts, next) {
1815 result = g_malloc0(sizeof(*result));
1816 result->path = g_strdup(mount->dirname);
1817
1818 QAPI_LIST_PREPEND(response->paths, result);
1819
1820 fd = qemu_open_old(mount->dirname, O_RDONLY);
1821 if (fd == -1) {
1822 result->error = g_strdup_printf("failed to open: %s",
1823 strerror(errno));
1824 result->has_error = true;
1825 continue;
1826 }
1827
1828 /* We try to cull filesystems we know won't work in advance, but other
1829 * filesystems may not implement fstrim for less obvious reasons.
1830 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1831 * will be reported (e.g. CD-ROMs).
1832 * Any other error means an unexpected error.
1833 */
1834 r.start = 0;
1835 r.len = -1;
1836 r.minlen = has_minimum ? minimum : 0;
1837 ret = ioctl(fd, FITRIM, &r);
1838 if (ret == -1) {
1839 result->has_error = true;
1840 if (errno == ENOTTY || errno == EOPNOTSUPP) {
1841 result->error = g_strdup("trim not supported");
1842 } else {
1843 result->error = g_strdup_printf("failed to trim: %s",
1844 strerror(errno));
1845 }
1846 close(fd);
1847 continue;
1848 }
1849
1850 result->has_minimum = true;
1851 result->minimum = r.minlen;
1852 result->has_trimmed = true;
1853 result->trimmed = r.len;
1854 close(fd);
1855 }
1856
1857 free_fs_mount_list(&mounts);
1858 return response;
1859 }
1860 #endif /* CONFIG_FSTRIM */
1861
1862
1863 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1864 #define SUSPEND_SUPPORTED 0
1865 #define SUSPEND_NOT_SUPPORTED 1
1866
1867 typedef enum {
1868 SUSPEND_MODE_DISK = 0,
1869 SUSPEND_MODE_RAM = 1,
1870 SUSPEND_MODE_HYBRID = 2,
1871 } SuspendMode;
1872
1873 /*
1874 * Executes a command in a child process using g_spawn_sync,
1875 * returning an int >= 0 representing the exit status of the
1876 * process.
1877 *
1878 * If the program wasn't found in path, returns -1.
1879 *
1880 * If a problem happened when creating the child process,
1881 * returns -1 and errp is set.
1882 */
1883 static int run_process_child(const char *command[], Error **errp)
1884 {
1885 int exit_status, spawn_flag;
1886 GError *g_err = NULL;
1887 bool success;
1888
1889 spawn_flag = G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL |
1890 G_SPAWN_STDERR_TO_DEV_NULL;
1891
1892 success = g_spawn_sync(NULL, (char **)command, NULL, spawn_flag,
1893 NULL, NULL, NULL, NULL,
1894 &exit_status, &g_err);
1895
1896 if (success) {
1897 return WEXITSTATUS(exit_status);
1898 }
1899
1900 if (g_err && (g_err->code != G_SPAWN_ERROR_NOENT)) {
1901 error_setg(errp, "failed to create child process, error '%s'",
1902 g_err->message);
1903 }
1904
1905 g_error_free(g_err);
1906 return -1;
1907 }
1908
1909 static bool systemd_supports_mode(SuspendMode mode, Error **errp)
1910 {
1911 const char *systemctl_args[3] = {"systemd-hibernate", "systemd-suspend",
1912 "systemd-hybrid-sleep"};
1913 const char *cmd[4] = {"systemctl", "status", systemctl_args[mode], NULL};
1914 int status;
1915
1916 status = run_process_child(cmd, errp);
1917
1918 /*
1919 * systemctl status uses LSB return codes so we can expect
1920 * status > 0 and be ok. To assert if the guest has support
1921 * for the selected suspend mode, status should be < 4. 4 is
1922 * the code for unknown service status, the return value when
1923 * the service does not exist. A common value is status = 3
1924 * (program is not running).
1925 */
1926 if (status > 0 && status < 4) {
1927 return true;
1928 }
1929
1930 return false;
1931 }
1932
1933 static void systemd_suspend(SuspendMode mode, Error **errp)
1934 {
1935 Error *local_err = NULL;
1936 const char *systemctl_args[3] = {"hibernate", "suspend", "hybrid-sleep"};
1937 const char *cmd[3] = {"systemctl", systemctl_args[mode], NULL};
1938 int status;
1939
1940 status = run_process_child(cmd, &local_err);
1941
1942 if (status == 0) {
1943 return;
1944 }
1945
1946 if ((status == -1) && !local_err) {
1947 error_setg(errp, "the helper program 'systemctl %s' was not found",
1948 systemctl_args[mode]);
1949 return;
1950 }
1951
1952 if (local_err) {
1953 error_propagate(errp, local_err);
1954 } else {
1955 error_setg(errp, "the helper program 'systemctl %s' returned an "
1956 "unexpected exit status code (%d)",
1957 systemctl_args[mode], status);
1958 }
1959 }
1960
1961 static bool pmutils_supports_mode(SuspendMode mode, Error **errp)
1962 {
1963 Error *local_err = NULL;
1964 const char *pmutils_args[3] = {"--hibernate", "--suspend",
1965 "--suspend-hybrid"};
1966 const char *cmd[3] = {"pm-is-supported", pmutils_args[mode], NULL};
1967 int status;
1968
1969 status = run_process_child(cmd, &local_err);
1970
1971 if (status == SUSPEND_SUPPORTED) {
1972 return true;
1973 }
1974
1975 if ((status == -1) && !local_err) {
1976 return false;
1977 }
1978
1979 if (local_err) {
1980 error_propagate(errp, local_err);
1981 } else {
1982 error_setg(errp,
1983 "the helper program '%s' returned an unexpected exit"
1984 " status code (%d)", "pm-is-supported", status);
1985 }
1986
1987 return false;
1988 }
1989
1990 static void pmutils_suspend(SuspendMode mode, Error **errp)
1991 {
1992 Error *local_err = NULL;
1993 const char *pmutils_binaries[3] = {"pm-hibernate", "pm-suspend",
1994 "pm-suspend-hybrid"};
1995 const char *cmd[2] = {pmutils_binaries[mode], NULL};
1996 int status;
1997
1998 status = run_process_child(cmd, &local_err);
1999
2000 if (status == 0) {
2001 return;
2002 }
2003
2004 if ((status == -1) && !local_err) {
2005 error_setg(errp, "the helper program '%s' was not found",
2006 pmutils_binaries[mode]);
2007 return;
2008 }
2009
2010 if (local_err) {
2011 error_propagate(errp, local_err);
2012 } else {
2013 error_setg(errp,
2014 "the helper program '%s' returned an unexpected exit"
2015 " status code (%d)", pmutils_binaries[mode], status);
2016 }
2017 }
2018
2019 static bool linux_sys_state_supports_mode(SuspendMode mode, Error **errp)
2020 {
2021 const char *sysfile_strs[3] = {"disk", "mem", NULL};
2022 const char *sysfile_str = sysfile_strs[mode];
2023 char buf[32]; /* hopefully big enough */
2024 int fd;
2025 ssize_t ret;
2026
2027 if (!sysfile_str) {
2028 error_setg(errp, "unknown guest suspend mode");
2029 return false;
2030 }
2031
2032 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
2033 if (fd < 0) {
2034 return false;
2035 }
2036
2037 ret = read(fd, buf, sizeof(buf) - 1);
2038 close(fd);
2039 if (ret <= 0) {
2040 return false;
2041 }
2042 buf[ret] = '\0';
2043
2044 if (strstr(buf, sysfile_str)) {
2045 return true;
2046 }
2047 return false;
2048 }
2049
2050 static void linux_sys_state_suspend(SuspendMode mode, Error **errp)
2051 {
2052 Error *local_err = NULL;
2053 const char *sysfile_strs[3] = {"disk", "mem", NULL};
2054 const char *sysfile_str = sysfile_strs[mode];
2055 pid_t pid;
2056 int status;
2057
2058 if (!sysfile_str) {
2059 error_setg(errp, "unknown guest suspend mode");
2060 return;
2061 }
2062
2063 pid = fork();
2064 if (!pid) {
2065 /* child */
2066 int fd;
2067
2068 setsid();
2069 reopen_fd_to_null(0);
2070 reopen_fd_to_null(1);
2071 reopen_fd_to_null(2);
2072
2073 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
2074 if (fd < 0) {
2075 _exit(EXIT_FAILURE);
2076 }
2077
2078 if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
2079 _exit(EXIT_FAILURE);
2080 }
2081
2082 _exit(EXIT_SUCCESS);
2083 } else if (pid < 0) {
2084 error_setg_errno(errp, errno, "failed to create child process");
2085 return;
2086 }
2087
2088 ga_wait_child(pid, &status, &local_err);
2089 if (local_err) {
2090 error_propagate(errp, local_err);
2091 return;
2092 }
2093
2094 if (WEXITSTATUS(status)) {
2095 error_setg(errp, "child process has failed to suspend");
2096 }
2097
2098 }
2099
2100 static void guest_suspend(SuspendMode mode, Error **errp)
2101 {
2102 Error *local_err = NULL;
2103 bool mode_supported = false;
2104
2105 if (systemd_supports_mode(mode, &local_err)) {
2106 mode_supported = true;
2107 systemd_suspend(mode, &local_err);
2108 }
2109
2110 if (!local_err) {
2111 return;
2112 }
2113
2114 error_free(local_err);
2115 local_err = NULL;
2116
2117 if (pmutils_supports_mode(mode, &local_err)) {
2118 mode_supported = true;
2119 pmutils_suspend(mode, &local_err);
2120 }
2121
2122 if (!local_err) {
2123 return;
2124 }
2125
2126 error_free(local_err);
2127 local_err = NULL;
2128
2129 if (linux_sys_state_supports_mode(mode, &local_err)) {
2130 mode_supported = true;
2131 linux_sys_state_suspend(mode, &local_err);
2132 }
2133
2134 if (!mode_supported) {
2135 error_free(local_err);
2136 error_setg(errp,
2137 "the requested suspend mode is not supported by the guest");
2138 } else {
2139 error_propagate(errp, local_err);
2140 }
2141 }
2142
2143 void qmp_guest_suspend_disk(Error **errp)
2144 {
2145 guest_suspend(SUSPEND_MODE_DISK, errp);
2146 }
2147
2148 void qmp_guest_suspend_ram(Error **errp)
2149 {
2150 guest_suspend(SUSPEND_MODE_RAM, errp);
2151 }
2152
2153 void qmp_guest_suspend_hybrid(Error **errp)
2154 {
2155 guest_suspend(SUSPEND_MODE_HYBRID, errp);
2156 }
2157
2158 /* Transfer online/offline status between @vcpu and the guest system.
2159 *
2160 * On input either @errp or *@errp must be NULL.
2161 *
2162 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2163 * - R: vcpu->logical_id
2164 * - W: vcpu->online
2165 * - W: vcpu->can_offline
2166 *
2167 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2168 * - R: vcpu->logical_id
2169 * - R: vcpu->online
2170 *
2171 * Written members remain unmodified on error.
2172 */
2173 static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
2174 char *dirpath, Error **errp)
2175 {
2176 int fd;
2177 int res;
2178 int dirfd;
2179 static const char fn[] = "online";
2180
2181 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2182 if (dirfd == -1) {
2183 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2184 return;
2185 }
2186
2187 fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
2188 if (fd == -1) {
2189 if (errno != ENOENT) {
2190 error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
2191 } else if (sys2vcpu) {
2192 vcpu->online = true;
2193 vcpu->can_offline = false;
2194 } else if (!vcpu->online) {
2195 error_setg(errp, "logical processor #%" PRId64 " can't be "
2196 "offlined", vcpu->logical_id);
2197 } /* otherwise pretend successful re-onlining */
2198 } else {
2199 unsigned char status;
2200
2201 res = pread(fd, &status, 1, 0);
2202 if (res == -1) {
2203 error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
2204 } else if (res == 0) {
2205 error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
2206 fn);
2207 } else if (sys2vcpu) {
2208 vcpu->online = (status != '0');
2209 vcpu->can_offline = true;
2210 } else if (vcpu->online != (status != '0')) {
2211 status = '0' + vcpu->online;
2212 if (pwrite(fd, &status, 1, 0) == -1) {
2213 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
2214 fn);
2215 }
2216 } /* otherwise pretend successful re-(on|off)-lining */
2217
2218 res = close(fd);
2219 g_assert(res == 0);
2220 }
2221
2222 res = close(dirfd);
2223 g_assert(res == 0);
2224 }
2225
2226 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2227 {
2228 GuestLogicalProcessorList *head, **tail;
2229 const char *cpu_dir = "/sys/devices/system/cpu";
2230 const gchar *line;
2231 g_autoptr(GDir) cpu_gdir = NULL;
2232 Error *local_err = NULL;
2233
2234 head = NULL;
2235 tail = &head;
2236 cpu_gdir = g_dir_open(cpu_dir, 0, NULL);
2237
2238 if (cpu_gdir == NULL) {
2239 error_setg_errno(errp, errno, "failed to list entries: %s", cpu_dir);
2240 return NULL;
2241 }
2242
2243 while (local_err == NULL && (line = g_dir_read_name(cpu_gdir)) != NULL) {
2244 GuestLogicalProcessor *vcpu;
2245 int64_t id;
2246 if (sscanf(line, "cpu%" PRId64, &id)) {
2247 g_autofree char *path = g_strdup_printf("/sys/devices/system/cpu/"
2248 "cpu%" PRId64 "/", id);
2249 vcpu = g_malloc0(sizeof *vcpu);
2250 vcpu->logical_id = id;
2251 vcpu->has_can_offline = true; /* lolspeak ftw */
2252 transfer_vcpu(vcpu, true, path, &local_err);
2253 QAPI_LIST_APPEND(tail, vcpu);
2254 }
2255 }
2256
2257 if (local_err == NULL) {
2258 /* there's no guest with zero VCPUs */
2259 g_assert(head != NULL);
2260 return head;
2261 }
2262
2263 qapi_free_GuestLogicalProcessorList(head);
2264 error_propagate(errp, local_err);
2265 return NULL;
2266 }
2267
2268 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2269 {
2270 int64_t processed;
2271 Error *local_err = NULL;
2272
2273 processed = 0;
2274 while (vcpus != NULL) {
2275 char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
2276 vcpus->value->logical_id);
2277
2278 transfer_vcpu(vcpus->value, false, path, &local_err);
2279 g_free(path);
2280 if (local_err != NULL) {
2281 break;
2282 }
2283 ++processed;
2284 vcpus = vcpus->next;
2285 }
2286
2287 if (local_err != NULL) {
2288 if (processed == 0) {
2289 error_propagate(errp, local_err);
2290 } else {
2291 error_free(local_err);
2292 }
2293 }
2294
2295 return processed;
2296 }
2297
2298 void qmp_guest_set_user_password(const char *username,
2299 const char *password,
2300 bool crypted,
2301 Error **errp)
2302 {
2303 Error *local_err = NULL;
2304 char *passwd_path = NULL;
2305 pid_t pid;
2306 int status;
2307 int datafd[2] = { -1, -1 };
2308 char *rawpasswddata = NULL;
2309 size_t rawpasswdlen;
2310 char *chpasswddata = NULL;
2311 size_t chpasswdlen;
2312
2313 rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
2314 if (!rawpasswddata) {
2315 return;
2316 }
2317 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
2318 rawpasswddata[rawpasswdlen] = '\0';
2319
2320 if (strchr(rawpasswddata, '\n')) {
2321 error_setg(errp, "forbidden characters in raw password");
2322 goto out;
2323 }
2324
2325 if (strchr(username, '\n') ||
2326 strchr(username, ':')) {
2327 error_setg(errp, "forbidden characters in username");
2328 goto out;
2329 }
2330
2331 chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
2332 chpasswdlen = strlen(chpasswddata);
2333
2334 passwd_path = g_find_program_in_path("chpasswd");
2335
2336 if (!passwd_path) {
2337 error_setg(errp, "cannot find 'passwd' program in PATH");
2338 goto out;
2339 }
2340
2341 if (!g_unix_open_pipe(datafd, FD_CLOEXEC, NULL)) {
2342 error_setg(errp, "cannot create pipe FDs");
2343 goto out;
2344 }
2345
2346 pid = fork();
2347 if (pid == 0) {
2348 close(datafd[1]);
2349 /* child */
2350 setsid();
2351 dup2(datafd[0], 0);
2352 reopen_fd_to_null(1);
2353 reopen_fd_to_null(2);
2354
2355 if (crypted) {
2356 execl(passwd_path, "chpasswd", "-e", NULL);
2357 } else {
2358 execl(passwd_path, "chpasswd", NULL);
2359 }
2360 _exit(EXIT_FAILURE);
2361 } else if (pid < 0) {
2362 error_setg_errno(errp, errno, "failed to create child process");
2363 goto out;
2364 }
2365 close(datafd[0]);
2366 datafd[0] = -1;
2367
2368 if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
2369 error_setg_errno(errp, errno, "cannot write new account password");
2370 goto out;
2371 }
2372 close(datafd[1]);
2373 datafd[1] = -1;
2374
2375 ga_wait_child(pid, &status, &local_err);
2376 if (local_err) {
2377 error_propagate(errp, local_err);
2378 goto out;
2379 }
2380
2381 if (!WIFEXITED(status)) {
2382 error_setg(errp, "child process has terminated abnormally");
2383 goto out;
2384 }
2385
2386 if (WEXITSTATUS(status)) {
2387 error_setg(errp, "child process has failed to set user password");
2388 goto out;
2389 }
2390
2391 out:
2392 g_free(chpasswddata);
2393 g_free(rawpasswddata);
2394 g_free(passwd_path);
2395 if (datafd[0] != -1) {
2396 close(datafd[0]);
2397 }
2398 if (datafd[1] != -1) {
2399 close(datafd[1]);
2400 }
2401 }
2402
2403 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2404 int size, Error **errp)
2405 {
2406 int fd;
2407 int res;
2408
2409 errno = 0;
2410 fd = openat(dirfd, pathname, O_RDONLY);
2411 if (fd == -1) {
2412 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2413 return;
2414 }
2415
2416 res = pread(fd, buf, size, 0);
2417 if (res == -1) {
2418 error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2419 } else if (res == 0) {
2420 error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2421 }
2422 close(fd);
2423 }
2424
2425 static void ga_write_sysfs_file(int dirfd, const char *pathname,
2426 const char *buf, int size, Error **errp)
2427 {
2428 int fd;
2429
2430 errno = 0;
2431 fd = openat(dirfd, pathname, O_WRONLY);
2432 if (fd == -1) {
2433 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2434 return;
2435 }
2436
2437 if (pwrite(fd, buf, size, 0) == -1) {
2438 error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2439 }
2440
2441 close(fd);
2442 }
2443
2444 /* Transfer online/offline status between @mem_blk and the guest system.
2445 *
2446 * On input either @errp or *@errp must be NULL.
2447 *
2448 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2449 * - R: mem_blk->phys_index
2450 * - W: mem_blk->online
2451 * - W: mem_blk->can_offline
2452 *
2453 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2454 * - R: mem_blk->phys_index
2455 * - R: mem_blk->online
2456 *- R: mem_blk->can_offline
2457 * Written members remain unmodified on error.
2458 */
2459 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2460 GuestMemoryBlockResponse *result,
2461 Error **errp)
2462 {
2463 char *dirpath;
2464 int dirfd;
2465 char *status;
2466 Error *local_err = NULL;
2467
2468 if (!sys2memblk) {
2469 DIR *dp;
2470
2471 if (!result) {
2472 error_setg(errp, "Internal error, 'result' should not be NULL");
2473 return;
2474 }
2475 errno = 0;
2476 dp = opendir("/sys/devices/system/memory/");
2477 /* if there is no 'memory' directory in sysfs,
2478 * we think this VM does not support online/offline memory block,
2479 * any other solution?
2480 */
2481 if (!dp) {
2482 if (errno == ENOENT) {
2483 result->response =
2484 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2485 }
2486 goto out1;
2487 }
2488 closedir(dp);
2489 }
2490
2491 dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2492 mem_blk->phys_index);
2493 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2494 if (dirfd == -1) {
2495 if (sys2memblk) {
2496 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2497 } else {
2498 if (errno == ENOENT) {
2499 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2500 } else {
2501 result->response =
2502 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2503 }
2504 }
2505 g_free(dirpath);
2506 goto out1;
2507 }
2508 g_free(dirpath);
2509
2510 status = g_malloc0(10);
2511 ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2512 if (local_err) {
2513 /* treat with sysfs file that not exist in old kernel */
2514 if (errno == ENOENT) {
2515 error_free(local_err);
2516 if (sys2memblk) {
2517 mem_blk->online = true;
2518 mem_blk->can_offline = false;
2519 } else if (!mem_blk->online) {
2520 result->response =
2521 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2522 }
2523 } else {
2524 if (sys2memblk) {
2525 error_propagate(errp, local_err);
2526 } else {
2527 error_free(local_err);
2528 result->response =
2529 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2530 }
2531 }
2532 goto out2;
2533 }
2534
2535 if (sys2memblk) {
2536 char removable = '0';
2537
2538 mem_blk->online = (strncmp(status, "online", 6) == 0);
2539
2540 ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2541 if (local_err) {
2542 /* if no 'removable' file, it doesn't support offline mem blk */
2543 if (errno == ENOENT) {
2544 error_free(local_err);
2545 mem_blk->can_offline = false;
2546 } else {
2547 error_propagate(errp, local_err);
2548 }
2549 } else {
2550 mem_blk->can_offline = (removable != '0');
2551 }
2552 } else {
2553 if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2554 const char *new_state = mem_blk->online ? "online" : "offline";
2555
2556 ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2557 &local_err);
2558 if (local_err) {
2559 error_free(local_err);
2560 result->response =
2561 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2562 goto out2;
2563 }
2564
2565 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2566 result->has_error_code = false;
2567 } /* otherwise pretend successful re-(on|off)-lining */
2568 }
2569 g_free(status);
2570 close(dirfd);
2571 return;
2572
2573 out2:
2574 g_free(status);
2575 close(dirfd);
2576 out1:
2577 if (!sys2memblk) {
2578 result->has_error_code = true;
2579 result->error_code = errno;
2580 }
2581 }
2582
2583 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2584 {
2585 GuestMemoryBlockList *head, **tail;
2586 Error *local_err = NULL;
2587 struct dirent *de;
2588 DIR *dp;
2589
2590 head = NULL;
2591 tail = &head;
2592
2593 dp = opendir("/sys/devices/system/memory/");
2594 if (!dp) {
2595 /* it's ok if this happens to be a system that doesn't expose
2596 * memory blocks via sysfs, but otherwise we should report
2597 * an error
2598 */
2599 if (errno != ENOENT) {
2600 error_setg_errno(errp, errno, "Can't open directory"
2601 "\"/sys/devices/system/memory/\"");
2602 }
2603 return NULL;
2604 }
2605
2606 /* Note: the phys_index of memory block may be discontinuous,
2607 * this is because a memblk is the unit of the Sparse Memory design, which
2608 * allows discontinuous memory ranges (ex. NUMA), so here we should
2609 * traverse the memory block directory.
2610 */
2611 while ((de = readdir(dp)) != NULL) {
2612 GuestMemoryBlock *mem_blk;
2613
2614 if ((strncmp(de->d_name, "memory", 6) != 0) ||
2615 !(de->d_type & DT_DIR)) {
2616 continue;
2617 }
2618
2619 mem_blk = g_malloc0(sizeof *mem_blk);
2620 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2621 mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2622 mem_blk->has_can_offline = true; /* lolspeak ftw */
2623 transfer_memory_block(mem_blk, true, NULL, &local_err);
2624 if (local_err) {
2625 break;
2626 }
2627
2628 QAPI_LIST_APPEND(tail, mem_blk);
2629 }
2630
2631 closedir(dp);
2632 if (local_err == NULL) {
2633 /* there's no guest with zero memory blocks */
2634 if (head == NULL) {
2635 error_setg(errp, "guest reported zero memory blocks!");
2636 }
2637 return head;
2638 }
2639
2640 qapi_free_GuestMemoryBlockList(head);
2641 error_propagate(errp, local_err);
2642 return NULL;
2643 }
2644
2645 GuestMemoryBlockResponseList *
2646 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2647 {
2648 GuestMemoryBlockResponseList *head, **tail;
2649 Error *local_err = NULL;
2650
2651 head = NULL;
2652 tail = &head;
2653
2654 while (mem_blks != NULL) {
2655 GuestMemoryBlockResponse *result;
2656 GuestMemoryBlock *current_mem_blk = mem_blks->value;
2657
2658 result = g_malloc0(sizeof(*result));
2659 result->phys_index = current_mem_blk->phys_index;
2660 transfer_memory_block(current_mem_blk, false, result, &local_err);
2661 if (local_err) { /* should never happen */
2662 goto err;
2663 }
2664
2665 QAPI_LIST_APPEND(tail, result);
2666 mem_blks = mem_blks->next;
2667 }
2668
2669 return head;
2670 err:
2671 qapi_free_GuestMemoryBlockResponseList(head);
2672 error_propagate(errp, local_err);
2673 return NULL;
2674 }
2675
2676 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2677 {
2678 Error *local_err = NULL;
2679 char *dirpath;
2680 int dirfd;
2681 char *buf;
2682 GuestMemoryBlockInfo *info;
2683
2684 dirpath = g_strdup_printf("/sys/devices/system/memory/");
2685 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2686 if (dirfd == -1) {
2687 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2688 g_free(dirpath);
2689 return NULL;
2690 }
2691 g_free(dirpath);
2692
2693 buf = g_malloc0(20);
2694 ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
2695 close(dirfd);
2696 if (local_err) {
2697 g_free(buf);
2698 error_propagate(errp, local_err);
2699 return NULL;
2700 }
2701
2702 info = g_new0(GuestMemoryBlockInfo, 1);
2703 info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2704
2705 g_free(buf);
2706
2707 return info;
2708 }
2709
2710 #else /* defined(__linux__) */
2711
2712 void qmp_guest_suspend_disk(Error **errp)
2713 {
2714 error_setg(errp, QERR_UNSUPPORTED);
2715 }
2716
2717 void qmp_guest_suspend_ram(Error **errp)
2718 {
2719 error_setg(errp, QERR_UNSUPPORTED);
2720 }
2721
2722 void qmp_guest_suspend_hybrid(Error **errp)
2723 {
2724 error_setg(errp, QERR_UNSUPPORTED);
2725 }
2726
2727 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2728 {
2729 error_setg(errp, QERR_UNSUPPORTED);
2730 return NULL;
2731 }
2732
2733 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2734 {
2735 error_setg(errp, QERR_UNSUPPORTED);
2736 return -1;
2737 }
2738
2739 void qmp_guest_set_user_password(const char *username,
2740 const char *password,
2741 bool crypted,
2742 Error **errp)
2743 {
2744 error_setg(errp, QERR_UNSUPPORTED);
2745 }
2746
2747 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2748 {
2749 error_setg(errp, QERR_UNSUPPORTED);
2750 return NULL;
2751 }
2752
2753 GuestMemoryBlockResponseList *
2754 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2755 {
2756 error_setg(errp, QERR_UNSUPPORTED);
2757 return NULL;
2758 }
2759
2760 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2761 {
2762 error_setg(errp, QERR_UNSUPPORTED);
2763 return NULL;
2764 }
2765
2766 #endif
2767
2768 #ifdef HAVE_GETIFADDRS
2769 static GuestNetworkInterface *
2770 guest_find_interface(GuestNetworkInterfaceList *head,
2771 const char *name)
2772 {
2773 for (; head; head = head->next) {
2774 if (strcmp(head->value->name, name) == 0) {
2775 return head->value;
2776 }
2777 }
2778
2779 return NULL;
2780 }
2781
2782 static int guest_get_network_stats(const char *name,
2783 GuestNetworkInterfaceStat *stats)
2784 {
2785 #ifdef CONFIG_LINUX
2786 int name_len;
2787 char const *devinfo = "/proc/net/dev";
2788 FILE *fp;
2789 char *line = NULL, *colon;
2790 size_t n = 0;
2791 fp = fopen(devinfo, "r");
2792 if (!fp) {
2793 g_debug("failed to open network stats %s: %s", devinfo,
2794 g_strerror(errno));
2795 return -1;
2796 }
2797 name_len = strlen(name);
2798 while (getline(&line, &n, fp) != -1) {
2799 long long dummy;
2800 long long rx_bytes;
2801 long long rx_packets;
2802 long long rx_errs;
2803 long long rx_dropped;
2804 long long tx_bytes;
2805 long long tx_packets;
2806 long long tx_errs;
2807 long long tx_dropped;
2808 char *trim_line;
2809 trim_line = g_strchug(line);
2810 if (trim_line[0] == '\0') {
2811 continue;
2812 }
2813 colon = strchr(trim_line, ':');
2814 if (!colon) {
2815 continue;
2816 }
2817 if (colon - name_len == trim_line &&
2818 strncmp(trim_line, name, name_len) == 0) {
2819 if (sscanf(colon + 1,
2820 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2821 &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
2822 &dummy, &dummy, &dummy, &dummy,
2823 &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
2824 &dummy, &dummy, &dummy, &dummy) != 16) {
2825 continue;
2826 }
2827 stats->rx_bytes = rx_bytes;
2828 stats->rx_packets = rx_packets;
2829 stats->rx_errs = rx_errs;
2830 stats->rx_dropped = rx_dropped;
2831 stats->tx_bytes = tx_bytes;
2832 stats->tx_packets = tx_packets;
2833 stats->tx_errs = tx_errs;
2834 stats->tx_dropped = tx_dropped;
2835 fclose(fp);
2836 g_free(line);
2837 return 0;
2838 }
2839 }
2840 fclose(fp);
2841 g_free(line);
2842 g_debug("/proc/net/dev: Interface '%s' not found", name);
2843 #else /* !CONFIG_LINUX */
2844 g_debug("Network stats reporting available only for Linux");
2845 #endif /* !CONFIG_LINUX */
2846 return -1;
2847 }
2848
2849 /*
2850 * Build information about guest interfaces
2851 */
2852 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2853 {
2854 GuestNetworkInterfaceList *head = NULL, **tail = &head;
2855 struct ifaddrs *ifap, *ifa;
2856
2857 if (getifaddrs(&ifap) < 0) {
2858 error_setg_errno(errp, errno, "getifaddrs failed");
2859 goto error;
2860 }
2861
2862 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
2863 GuestNetworkInterface *info;
2864 GuestIpAddressList **address_tail;
2865 GuestIpAddress *address_item = NULL;
2866 GuestNetworkInterfaceStat *interface_stat = NULL;
2867 char addr4[INET_ADDRSTRLEN];
2868 char addr6[INET6_ADDRSTRLEN];
2869 int sock;
2870 struct ifreq ifr;
2871 unsigned char *mac_addr;
2872 void *p;
2873
2874 g_debug("Processing %s interface", ifa->ifa_name);
2875
2876 info = guest_find_interface(head, ifa->ifa_name);
2877
2878 if (!info) {
2879 info = g_malloc0(sizeof(*info));
2880 info->name = g_strdup(ifa->ifa_name);
2881
2882 QAPI_LIST_APPEND(tail, info);
2883 }
2884
2885 if (!info->has_hardware_address) {
2886 /* we haven't obtained HW address yet */
2887 sock = socket(PF_INET, SOCK_STREAM, 0);
2888 if (sock == -1) {
2889 error_setg_errno(errp, errno, "failed to create socket");
2890 goto error;
2891 }
2892
2893 memset(&ifr, 0, sizeof(ifr));
2894 pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->name);
2895 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
2896 /*
2897 * We can't get the hw addr of this interface, but that's not a
2898 * fatal error. Don't set info->hardware_address, but keep
2899 * going.
2900 */
2901 if (errno == EADDRNOTAVAIL) {
2902 /* The interface doesn't have a hw addr (e.g. loopback). */
2903 g_debug("failed to get MAC address of %s: %s",
2904 ifa->ifa_name, strerror(errno));
2905 } else{
2906 g_warning("failed to get MAC address of %s: %s",
2907 ifa->ifa_name, strerror(errno));
2908 }
2909
2910 } else {
2911 #ifdef CONFIG_SOLARIS
2912 mac_addr = (unsigned char *) &ifr.ifr_addr.sa_data;
2913 #else
2914 mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
2915 #endif
2916 info->hardware_address =
2917 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2918 (int) mac_addr[0], (int) mac_addr[1],
2919 (int) mac_addr[2], (int) mac_addr[3],
2920 (int) mac_addr[4], (int) mac_addr[5]);
2921
2922 info->has_hardware_address = true;
2923 }
2924 close(sock);
2925 }
2926
2927 if (ifa->ifa_addr &&
2928 ifa->ifa_addr->sa_family == AF_INET) {
2929 /* interface with IPv4 address */
2930 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
2931 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
2932 error_setg_errno(errp, errno, "inet_ntop failed");
2933 goto error;
2934 }
2935
2936 address_item = g_malloc0(sizeof(*address_item));
2937 address_item->ip_address = g_strdup(addr4);
2938 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
2939
2940 if (ifa->ifa_netmask) {
2941 /* Count the number of set bits in netmask.
2942 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2943 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
2944 address_item->prefix = ctpop32(((uint32_t *) p)[0]);
2945 }
2946 } else if (ifa->ifa_addr &&
2947 ifa->ifa_addr->sa_family == AF_INET6) {
2948 /* interface with IPv6 address */
2949 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
2950 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
2951 error_setg_errno(errp, errno, "inet_ntop failed");
2952 goto error;
2953 }
2954
2955 address_item = g_malloc0(sizeof(*address_item));
2956 address_item->ip_address = g_strdup(addr6);
2957 address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
2958
2959 if (ifa->ifa_netmask) {
2960 /* Count the number of set bits in netmask.
2961 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2962 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
2963 address_item->prefix =
2964 ctpop32(((uint32_t *) p)[0]) +
2965 ctpop32(((uint32_t *) p)[1]) +
2966 ctpop32(((uint32_t *) p)[2]) +
2967 ctpop32(((uint32_t *) p)[3]);
2968 }
2969 }
2970
2971 if (!address_item) {
2972 continue;
2973 }
2974
2975 address_tail = &info->ip_addresses;
2976 while (*address_tail) {
2977 address_tail = &(*address_tail)->next;
2978 }
2979 QAPI_LIST_APPEND(address_tail, address_item);
2980
2981 info->has_ip_addresses = true;
2982
2983 if (!info->has_statistics) {
2984 interface_stat = g_malloc0(sizeof(*interface_stat));
2985 if (guest_get_network_stats(info->name, interface_stat) == -1) {
2986 info->has_statistics = false;
2987 g_free(interface_stat);
2988 } else {
2989 info->statistics = interface_stat;
2990 info->has_statistics = true;
2991 }
2992 }
2993 }
2994
2995 freeifaddrs(ifap);
2996 return head;
2997
2998 error:
2999 freeifaddrs(ifap);
3000 qapi_free_GuestNetworkInterfaceList(head);
3001 return NULL;
3002 }
3003
3004 #else
3005
3006 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
3007 {
3008 error_setg(errp, QERR_UNSUPPORTED);
3009 return NULL;
3010 }
3011
3012 #endif /* HAVE_GETIFADDRS */
3013
3014 #if !defined(CONFIG_FSFREEZE)
3015
3016 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
3017 {
3018 error_setg(errp, QERR_UNSUPPORTED);
3019 return NULL;
3020 }
3021
3022 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
3023 {
3024 error_setg(errp, QERR_UNSUPPORTED);
3025
3026 return 0;
3027 }
3028
3029 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
3030 {
3031 error_setg(errp, QERR_UNSUPPORTED);
3032
3033 return 0;
3034 }
3035
3036 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
3037 strList *mountpoints,
3038 Error **errp)
3039 {
3040 error_setg(errp, QERR_UNSUPPORTED);
3041
3042 return 0;
3043 }
3044
3045 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
3046 {
3047 error_setg(errp, QERR_UNSUPPORTED);
3048
3049 return 0;
3050 }
3051
3052 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
3053 {
3054 error_setg(errp, QERR_UNSUPPORTED);
3055 return NULL;
3056 }
3057
3058 #endif /* CONFIG_FSFREEZE */
3059
3060 #if !defined(CONFIG_FSTRIM)
3061 GuestFilesystemTrimResponse *
3062 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
3063 {
3064 error_setg(errp, QERR_UNSUPPORTED);
3065 return NULL;
3066 }
3067 #endif
3068
3069 /* add unsupported commands to the blacklist */
3070 GList *ga_command_blacklist_init(GList *blacklist)
3071 {
3072 #if !defined(__linux__)
3073 {
3074 const char *list[] = {
3075 "guest-suspend-disk", "guest-suspend-ram",
3076 "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
3077 "guest-get-memory-blocks", "guest-set-memory-blocks",
3078 "guest-get-memory-block-size", "guest-get-memory-block-info",
3079 NULL};
3080 char **p = (char **)list;
3081
3082 while (*p) {
3083 blacklist = g_list_append(blacklist, g_strdup(*p++));
3084 }
3085 }
3086 #endif
3087
3088 #if !defined(HAVE_GETIFADDRS)
3089 blacklist = g_list_append(blacklist,
3090 g_strdup("guest-network-get-interfaces"));
3091 #endif
3092
3093 #if !defined(CONFIG_FSFREEZE)
3094 {
3095 const char *list[] = {
3096 "guest-get-fsinfo", "guest-fsfreeze-status",
3097 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3098 "guest-fsfreeze-thaw", "guest-get-fsinfo",
3099 "guest-get-disks", NULL};
3100 char **p = (char **)list;
3101
3102 while (*p) {
3103 blacklist = g_list_append(blacklist, g_strdup(*p++));
3104 }
3105 }
3106 #endif
3107
3108 #if !defined(CONFIG_FSTRIM)
3109 blacklist = g_list_append(blacklist, g_strdup("guest-fstrim"));
3110 #endif
3111
3112 blacklist = g_list_append(blacklist, g_strdup("guest-get-devices"));
3113
3114 return blacklist;
3115 }
3116
3117 /* register init/cleanup routines for stateful command groups */
3118 void ga_command_state_init(GAState *s, GACommandState *cs)
3119 {
3120 #if defined(CONFIG_FSFREEZE)
3121 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
3122 #endif
3123 }
3124
3125 #ifdef HAVE_UTMPX
3126
3127 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3128
3129 static double ga_get_login_time(struct utmpx *user_info)
3130 {
3131 double seconds = (double)user_info->ut_tv.tv_sec;
3132 double useconds = (double)user_info->ut_tv.tv_usec;
3133 useconds /= QGA_MICRO_SECOND_TO_SECOND;
3134 return seconds + useconds;
3135 }
3136
3137 GuestUserList *qmp_guest_get_users(Error **errp)
3138 {
3139 GHashTable *cache = NULL;
3140 GuestUserList *head = NULL, **tail = &head;
3141 struct utmpx *user_info = NULL;
3142 gpointer value = NULL;
3143 GuestUser *user = NULL;
3144 double login_time = 0;
3145
3146 cache = g_hash_table_new(g_str_hash, g_str_equal);
3147 setutxent();
3148
3149 for (;;) {
3150 user_info = getutxent();
3151 if (user_info == NULL) {
3152 break;
3153 } else if (user_info->ut_type != USER_PROCESS) {
3154 continue;
3155 } else if (g_hash_table_contains(cache, user_info->ut_user)) {
3156 value = g_hash_table_lookup(cache, user_info->ut_user);
3157 user = (GuestUser *)value;
3158 login_time = ga_get_login_time(user_info);
3159 /* We're ensuring the earliest login time to be sent */
3160 if (login_time < user->login_time) {
3161 user->login_time = login_time;
3162 }
3163 continue;
3164 }
3165
3166 user = g_new0(GuestUser, 1);
3167 user->user = g_strdup(user_info->ut_user);
3168 user->login_time = ga_get_login_time(user_info);
3169
3170 g_hash_table_insert(cache, user->user, user);
3171
3172 QAPI_LIST_APPEND(tail, user);
3173 }
3174 endutxent();
3175 g_hash_table_destroy(cache);
3176 return head;
3177 }
3178
3179 #else
3180
3181 GuestUserList *qmp_guest_get_users(Error **errp)
3182 {
3183 error_setg(errp, QERR_UNSUPPORTED);
3184 return NULL;
3185 }
3186
3187 #endif
3188
3189 /* Replace escaped special characters with theire real values. The replacement
3190 * is done in place -- returned value is in the original string.
3191 */
3192 static void ga_osrelease_replace_special(gchar *value)
3193 {
3194 gchar *p, *p2, quote;
3195
3196 /* Trim the string at first space or semicolon if it is not enclosed in
3197 * single or double quotes. */
3198 if ((value[0] != '"') || (value[0] == '\'')) {
3199 p = strchr(value, ' ');
3200 if (p != NULL) {
3201 *p = 0;
3202 }
3203 p = strchr(value, ';');
3204 if (p != NULL) {
3205 *p = 0;
3206 }
3207 return;
3208 }
3209
3210 quote = value[0];
3211 p2 = value;
3212 p = value + 1;
3213 while (*p != 0) {
3214 if (*p == '\\') {
3215 p++;
3216 switch (*p) {
3217 case '$':
3218 case '\'':
3219 case '"':
3220 case '\\':
3221 case '`':
3222 break;
3223 default:
3224 /* Keep literal backslash followed by whatever is there */
3225 p--;
3226 break;
3227 }
3228 } else if (*p == quote) {
3229 *p2 = 0;
3230 break;
3231 }
3232 *(p2++) = *(p++);
3233 }
3234 }
3235
3236 static GKeyFile *ga_parse_osrelease(const char *fname)
3237 {
3238 gchar *content = NULL;
3239 gchar *content2 = NULL;
3240 GError *err = NULL;
3241 GKeyFile *keys = g_key_file_new();
3242 const char *group = "[os-release]\n";
3243
3244 if (!g_file_get_contents(fname, &content, NULL, &err)) {
3245 slog("failed to read '%s', error: %s", fname, err->message);
3246 goto fail;
3247 }
3248
3249 if (!g_utf8_validate(content, -1, NULL)) {
3250 slog("file is not utf-8 encoded: %s", fname);
3251 goto fail;
3252 }
3253 content2 = g_strdup_printf("%s%s", group, content);
3254
3255 if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
3256 &err)) {
3257 slog("failed to parse file '%s', error: %s", fname, err->message);
3258 goto fail;
3259 }
3260
3261 g_free(content);
3262 g_free(content2);
3263 return keys;
3264
3265 fail:
3266 g_error_free(err);
3267 g_free(content);
3268 g_free(content2);
3269 g_key_file_free(keys);
3270 return NULL;
3271 }
3272
3273 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
3274 {
3275 GuestOSInfo *info = NULL;
3276 struct utsname kinfo;
3277 GKeyFile *osrelease = NULL;
3278 const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
3279
3280 info = g_new0(GuestOSInfo, 1);
3281
3282 if (uname(&kinfo) != 0) {
3283 error_setg_errno(errp, errno, "uname failed");
3284 } else {
3285 info->has_kernel_version = true;
3286 info->kernel_version = g_strdup(kinfo.version);
3287 info->has_kernel_release = true;
3288 info->kernel_release = g_strdup(kinfo.release);
3289 info->has_machine = true;
3290 info->machine = g_strdup(kinfo.machine);
3291 }
3292
3293 if (qga_os_release != NULL) {
3294 osrelease = ga_parse_osrelease(qga_os_release);
3295 } else {
3296 osrelease = ga_parse_osrelease("/etc/os-release");
3297 if (osrelease == NULL) {
3298 osrelease = ga_parse_osrelease("/usr/lib/os-release");
3299 }
3300 }
3301
3302 if (osrelease != NULL) {
3303 char *value;
3304
3305 #define GET_FIELD(field, osfield) do { \
3306 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3307 if (value != NULL) { \
3308 ga_osrelease_replace_special(value); \
3309 info->has_ ## field = true; \
3310 info->field = value; \
3311 } \
3312 } while (0)
3313 GET_FIELD(id, "ID");
3314 GET_FIELD(name, "NAME");
3315 GET_FIELD(pretty_name, "PRETTY_NAME");
3316 GET_FIELD(version, "VERSION");
3317 GET_FIELD(version_id, "VERSION_ID");
3318 GET_FIELD(variant, "VARIANT");
3319 GET_FIELD(variant_id, "VARIANT_ID");
3320 #undef GET_FIELD
3321
3322 g_key_file_free(osrelease);
3323 }
3324
3325 return info;
3326 }
3327
3328 GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
3329 {
3330 error_setg(errp, QERR_UNSUPPORTED);
3331
3332 return NULL;
3333 }
3334
3335 #ifndef HOST_NAME_MAX
3336 # ifdef _POSIX_HOST_NAME_MAX
3337 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
3338 # else
3339 # define HOST_NAME_MAX 255
3340 # endif
3341 #endif
3342
3343 char *qga_get_host_name(Error **errp)
3344 {
3345 long len = -1;
3346 g_autofree char *hostname = NULL;
3347
3348 #ifdef _SC_HOST_NAME_MAX
3349 len = sysconf(_SC_HOST_NAME_MAX);
3350 #endif /* _SC_HOST_NAME_MAX */
3351
3352 if (len < 0) {
3353 len = HOST_NAME_MAX;
3354 }
3355
3356 /* Unfortunately, gethostname() below does not guarantee a
3357 * NULL terminated string. Therefore, allocate one byte more
3358 * to be sure. */
3359 hostname = g_new0(char, len + 1);
3360
3361 if (gethostname(hostname, len) < 0) {
3362 error_setg_errno(errp, errno,
3363 "cannot get hostname");
3364 return NULL;
3365 }
3366
3367 return g_steal_pointer(&hostname);
3368 }