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