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