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