xref: /openbmc/qemu/qga/commands-posix.c (revision d9fe4f0fea31f0560dc40d3576bc6c48ad97109f)
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 #ifdef CONFIG_LIBUDEV
878     struct udev *udev = NULL;
879     struct udev_device *udevice = NULL;
880 #endif
881     bool ret = false;
882 
883     p = strstr(syspath, "/devices/pci");
884     if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
885                      pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
886         g_debug("only pci device is supported: sysfs path '%s'", syspath);
887         return false;
888     }
889 
890     p += 12 + pcilen;
891     while (true) {
892         driver = get_pci_driver(syspath, p - syspath, errp);
893         if (driver && (g_str_equal(driver, "ata_piix") ||
894                        g_str_equal(driver, "sym53c8xx") ||
895                        g_str_equal(driver, "virtio-pci") ||
896                        g_str_equal(driver, "ahci"))) {
897             break;
898         }
899 
900         g_free(driver);
901         if (sscanf(p, "/%x:%x:%x.%x%n",
902                           pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) {
903             p += pcilen;
904             continue;
905         }
906 
907         g_debug("unsupported driver or sysfs path '%s'", syspath);
908         return false;
909     }
910 
911     p = strstr(syspath, "/target");
912     if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
913                     tgt, tgt + 1, tgt + 2) == 3) {
914         has_tgt = true;
915     }
916 
917     p = strstr(syspath, "/ata");
918     if (p) {
919         q = p + 4;
920         has_ata = true;
921     } else {
922         p = strstr(syspath, "/host");
923         q = p + 5;
924     }
925     if (p && sscanf(q, "%u", &host) == 1) {
926         has_host = true;
927         nhosts = build_hosts(syspath, p, has_ata, hosts,
928                              ARRAY_SIZE(hosts), errp);
929         if (nhosts < 0) {
930             goto cleanup;
931         }
932     }
933 
934     pciaddr->domain = pci[0];
935     pciaddr->bus = pci[1];
936     pciaddr->slot = pci[2];
937     pciaddr->function = pci[3];
938 
939 #ifdef CONFIG_LIBUDEV
940     udev = udev_new();
941     udevice = udev_device_new_from_syspath(udev, syspath);
942     if (udev == NULL || udevice == NULL) {
943         g_debug("failed to query udev");
944     } else {
945         const char *devnode, *serial;
946         devnode = udev_device_get_devnode(udevice);
947         if (devnode != NULL) {
948             disk->dev = g_strdup(devnode);
949             disk->has_dev = true;
950         }
951         serial = udev_device_get_property_value(udevice, "ID_SERIAL");
952         if (serial != NULL && *serial != 0) {
953             disk->serial = g_strdup(serial);
954             disk->has_serial = true;
955         }
956     }
957 #endif
958 
959     if (strcmp(driver, "ata_piix") == 0) {
960         /* a host per ide bus, target*:0:<unit>:0 */
961         if (!has_host || !has_tgt) {
962             g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
963             goto cleanup;
964         }
965         for (i = 0; i < nhosts; i++) {
966             if (host == hosts[i]) {
967                 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
968                 disk->bus = i;
969                 disk->unit = tgt[1];
970                 break;
971             }
972         }
973         if (i >= nhosts) {
974             g_debug("no host for '%s' (driver '%s')", syspath, driver);
975             goto cleanup;
976         }
977     } else if (strcmp(driver, "sym53c8xx") == 0) {
978         /* scsi(LSI Logic): target*:0:<unit>:0 */
979         if (!has_tgt) {
980             g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
981             goto cleanup;
982         }
983         disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
984         disk->unit = tgt[1];
985     } else if (strcmp(driver, "virtio-pci") == 0) {
986         if (has_tgt) {
987             /* virtio-scsi: target*:0:0:<unit> */
988             disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
989             disk->unit = tgt[2];
990         } else {
991             /* virtio-blk: 1 disk per 1 device */
992             disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
993         }
994     } else if (strcmp(driver, "ahci") == 0) {
995         /* ahci: 1 host per 1 unit */
996         if (!has_host || !has_tgt) {
997             g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
998             goto cleanup;
999         }
1000         for (i = 0; i < nhosts; i++) {
1001             if (host == hosts[i]) {
1002                 disk->unit = i;
1003                 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
1004                 break;
1005             }
1006         }
1007         if (i >= nhosts) {
1008             g_debug("no host for '%s' (driver '%s')", syspath, driver);
1009             goto cleanup;
1010         }
1011     } else {
1012         g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
1013         goto cleanup;
1014     }
1015 
1016     ret = true;
1017 
1018 cleanup:
1019     g_free(driver);
1020 #ifdef CONFIG_LIBUDEV
1021     udev_unref(udev);
1022     udev_device_unref(udevice);
1023 #endif
1024     return ret;
1025 }
1026 
1027 /* Store disk device info specified by @sysfs into @fs */
1028 static void build_guest_fsinfo_for_real_device(char const *syspath,
1029                                                GuestFilesystemInfo *fs,
1030                                                Error **errp)
1031 {
1032     GuestDiskAddress *disk;
1033     GuestPCIAddress *pciaddr;
1034     GuestDiskAddressList *list = NULL;
1035     bool has_hwinf;
1036 
1037     pciaddr = g_new0(GuestPCIAddress, 1);
1038 
1039     disk = g_new0(GuestDiskAddress, 1);
1040     disk->pci_controller = pciaddr;
1041 
1042     list = g_new0(GuestDiskAddressList, 1);
1043     list->value = disk;
1044 
1045     has_hwinf = build_guest_fsinfo_for_pci_dev(syspath, disk, errp);
1046 
1047     if (has_hwinf) {
1048         list->next = fs->disk;
1049         fs->disk = list;
1050     } else {
1051         qapi_free_GuestDiskAddressList(list);
1052     }
1053 }
1054 
1055 static void build_guest_fsinfo_for_device(char const *devpath,
1056                                           GuestFilesystemInfo *fs,
1057                                           Error **errp);
1058 
1059 /* Store a list of slave devices of virtual volume specified by @syspath into
1060  * @fs */
1061 static void build_guest_fsinfo_for_virtual_device(char const *syspath,
1062                                                   GuestFilesystemInfo *fs,
1063                                                   Error **errp)
1064 {
1065     Error *err = NULL;
1066     DIR *dir;
1067     char *dirpath;
1068     struct dirent *entry;
1069 
1070     dirpath = g_strdup_printf("%s/slaves", syspath);
1071     dir = opendir(dirpath);
1072     if (!dir) {
1073         if (errno != ENOENT) {
1074             error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
1075         }
1076         g_free(dirpath);
1077         return;
1078     }
1079 
1080     for (;;) {
1081         errno = 0;
1082         entry = readdir(dir);
1083         if (entry == NULL) {
1084             if (errno) {
1085                 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
1086             }
1087             break;
1088         }
1089 
1090         if (entry->d_type == DT_LNK) {
1091             char *path;
1092 
1093             g_debug(" slave device '%s'", entry->d_name);
1094             path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
1095             build_guest_fsinfo_for_device(path, fs, &err);
1096             g_free(path);
1097 
1098             if (err) {
1099                 error_propagate(errp, err);
1100                 break;
1101             }
1102         }
1103     }
1104 
1105     g_free(dirpath);
1106     closedir(dir);
1107 }
1108 
1109 /* Dispatch to functions for virtual/real device */
1110 static void build_guest_fsinfo_for_device(char const *devpath,
1111                                           GuestFilesystemInfo *fs,
1112                                           Error **errp)
1113 {
1114     char *syspath = realpath(devpath, NULL);
1115 
1116     if (!syspath) {
1117         error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1118         return;
1119     }
1120 
1121     if (!fs->name) {
1122         fs->name = g_path_get_basename(syspath);
1123     }
1124 
1125     g_debug("  parse sysfs path '%s'", syspath);
1126 
1127     if (strstr(syspath, "/devices/virtual/block/")) {
1128         build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1129     } else {
1130         build_guest_fsinfo_for_real_device(syspath, fs, errp);
1131     }
1132 
1133     free(syspath);
1134 }
1135 
1136 /* Return a list of the disk device(s)' info which @mount lies on */
1137 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1138                                                Error **errp)
1139 {
1140     GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1141     struct statvfs buf;
1142     unsigned long used, nonroot_total, fr_size;
1143     char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1144                                     mount->devmajor, mount->devminor);
1145 
1146     fs->mountpoint = g_strdup(mount->dirname);
1147     fs->type = g_strdup(mount->devtype);
1148     build_guest_fsinfo_for_device(devpath, fs, errp);
1149 
1150     if (statvfs(fs->mountpoint, &buf) == 0) {
1151         fr_size = buf.f_frsize;
1152         used = buf.f_blocks - buf.f_bfree;
1153         nonroot_total = used + buf.f_bavail;
1154         fs->used_bytes = used * fr_size;
1155         fs->total_bytes = nonroot_total * fr_size;
1156 
1157         fs->has_total_bytes = true;
1158         fs->has_used_bytes = true;
1159     }
1160 
1161     g_free(devpath);
1162 
1163     return fs;
1164 }
1165 
1166 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1167 {
1168     FsMountList mounts;
1169     struct FsMount *mount;
1170     GuestFilesystemInfoList *new, *ret = NULL;
1171     Error *local_err = NULL;
1172 
1173     QTAILQ_INIT(&mounts);
1174     build_fs_mount_list(&mounts, &local_err);
1175     if (local_err) {
1176         error_propagate(errp, local_err);
1177         return NULL;
1178     }
1179 
1180     QTAILQ_FOREACH(mount, &mounts, next) {
1181         g_debug("Building guest fsinfo for '%s'", mount->dirname);
1182 
1183         new = g_malloc0(sizeof(*ret));
1184         new->value = build_guest_fsinfo(mount, &local_err);
1185         new->next = ret;
1186         ret = new;
1187         if (local_err) {
1188             error_propagate(errp, local_err);
1189             qapi_free_GuestFilesystemInfoList(ret);
1190             ret = NULL;
1191             break;
1192         }
1193     }
1194 
1195     free_fs_mount_list(&mounts);
1196     return ret;
1197 }
1198 
1199 
1200 typedef enum {
1201     FSFREEZE_HOOK_THAW = 0,
1202     FSFREEZE_HOOK_FREEZE,
1203 } FsfreezeHookArg;
1204 
1205 static const char *fsfreeze_hook_arg_string[] = {
1206     "thaw",
1207     "freeze",
1208 };
1209 
1210 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
1211 {
1212     int status;
1213     pid_t pid;
1214     const char *hook;
1215     const char *arg_str = fsfreeze_hook_arg_string[arg];
1216     Error *local_err = NULL;
1217 
1218     hook = ga_fsfreeze_hook(ga_state);
1219     if (!hook) {
1220         return;
1221     }
1222     if (access(hook, X_OK) != 0) {
1223         error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
1224         return;
1225     }
1226 
1227     slog("executing fsfreeze hook with arg '%s'", arg_str);
1228     pid = fork();
1229     if (pid == 0) {
1230         setsid();
1231         reopen_fd_to_null(0);
1232         reopen_fd_to_null(1);
1233         reopen_fd_to_null(2);
1234 
1235         execle(hook, hook, arg_str, NULL, environ);
1236         _exit(EXIT_FAILURE);
1237     } else if (pid < 0) {
1238         error_setg_errno(errp, errno, "failed to create child process");
1239         return;
1240     }
1241 
1242     ga_wait_child(pid, &status, &local_err);
1243     if (local_err) {
1244         error_propagate(errp, local_err);
1245         return;
1246     }
1247 
1248     if (!WIFEXITED(status)) {
1249         error_setg(errp, "fsfreeze hook has terminated abnormally");
1250         return;
1251     }
1252 
1253     status = WEXITSTATUS(status);
1254     if (status) {
1255         error_setg(errp, "fsfreeze hook has failed with status %d", status);
1256         return;
1257     }
1258 }
1259 
1260 /*
1261  * Return status of freeze/thaw
1262  */
1263 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1264 {
1265     if (ga_is_frozen(ga_state)) {
1266         return GUEST_FSFREEZE_STATUS_FROZEN;
1267     }
1268 
1269     return GUEST_FSFREEZE_STATUS_THAWED;
1270 }
1271 
1272 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1273 {
1274     return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1275 }
1276 
1277 /*
1278  * Walk list of mounted file systems in the guest, and freeze the ones which
1279  * are real local file systems.
1280  */
1281 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1282                                        strList *mountpoints,
1283                                        Error **errp)
1284 {
1285     int ret = 0, i = 0;
1286     strList *list;
1287     FsMountList mounts;
1288     struct FsMount *mount;
1289     Error *local_err = NULL;
1290     int fd;
1291 
1292     slog("guest-fsfreeze called");
1293 
1294     execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
1295     if (local_err) {
1296         error_propagate(errp, local_err);
1297         return -1;
1298     }
1299 
1300     QTAILQ_INIT(&mounts);
1301     build_fs_mount_list(&mounts, &local_err);
1302     if (local_err) {
1303         error_propagate(errp, local_err);
1304         return -1;
1305     }
1306 
1307     /* cannot risk guest agent blocking itself on a write in this state */
1308     ga_set_frozen(ga_state);
1309 
1310     QTAILQ_FOREACH_REVERSE(mount, &mounts, next) {
1311         /* To issue fsfreeze in the reverse order of mounts, check if the
1312          * mount is listed in the list here */
1313         if (has_mountpoints) {
1314             for (list = mountpoints; list; list = list->next) {
1315                 if (strcmp(list->value, mount->dirname) == 0) {
1316                     break;
1317                 }
1318             }
1319             if (!list) {
1320                 continue;
1321             }
1322         }
1323 
1324         fd = qemu_open(mount->dirname, O_RDONLY);
1325         if (fd == -1) {
1326             error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
1327             goto error;
1328         }
1329 
1330         /* we try to cull filesystems we know won't work in advance, but other
1331          * filesystems may not implement fsfreeze for less obvious reasons.
1332          * these will report EOPNOTSUPP. we simply ignore these when tallying
1333          * the number of frozen filesystems.
1334          * if a filesystem is mounted more than once (aka bind mount) a
1335          * consecutive attempt to freeze an already frozen filesystem will
1336          * return EBUSY.
1337          *
1338          * any other error means a failure to freeze a filesystem we
1339          * expect to be freezable, so return an error in those cases
1340          * and return system to thawed state.
1341          */
1342         ret = ioctl(fd, FIFREEZE);
1343         if (ret == -1) {
1344             if (errno != EOPNOTSUPP && errno != EBUSY) {
1345                 error_setg_errno(errp, errno, "failed to freeze %s",
1346                                  mount->dirname);
1347                 close(fd);
1348                 goto error;
1349             }
1350         } else {
1351             i++;
1352         }
1353         close(fd);
1354     }
1355 
1356     free_fs_mount_list(&mounts);
1357     /* We may not issue any FIFREEZE here.
1358      * Just unset ga_state here and ready for the next call.
1359      */
1360     if (i == 0) {
1361         ga_unset_frozen(ga_state);
1362     }
1363     return i;
1364 
1365 error:
1366     free_fs_mount_list(&mounts);
1367     qmp_guest_fsfreeze_thaw(NULL);
1368     return 0;
1369 }
1370 
1371 /*
1372  * Walk list of frozen file systems in the guest, and thaw them.
1373  */
1374 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1375 {
1376     int ret;
1377     FsMountList mounts;
1378     FsMount *mount;
1379     int fd, i = 0, logged;
1380     Error *local_err = NULL;
1381 
1382     QTAILQ_INIT(&mounts);
1383     build_fs_mount_list(&mounts, &local_err);
1384     if (local_err) {
1385         error_propagate(errp, local_err);
1386         return 0;
1387     }
1388 
1389     QTAILQ_FOREACH(mount, &mounts, next) {
1390         logged = false;
1391         fd = qemu_open(mount->dirname, O_RDONLY);
1392         if (fd == -1) {
1393             continue;
1394         }
1395         /* we have no way of knowing whether a filesystem was actually unfrozen
1396          * as a result of a successful call to FITHAW, only that if an error
1397          * was returned the filesystem was *not* unfrozen by that particular
1398          * call.
1399          *
1400          * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1401          * to unfreeze, continuing issuing FITHAW until an error is returned,
1402          * in which case either the filesystem is in an unfreezable state, or,
1403          * more likely, it was thawed previously (and remains so afterward).
1404          *
1405          * also, since the most recent successful call is the one that did
1406          * the actual unfreeze, we can use this to provide an accurate count
1407          * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1408          * may * be useful for determining whether a filesystem was unfrozen
1409          * during the freeze/thaw phase by a process other than qemu-ga.
1410          */
1411         do {
1412             ret = ioctl(fd, FITHAW);
1413             if (ret == 0 && !logged) {
1414                 i++;
1415                 logged = true;
1416             }
1417         } while (ret == 0);
1418         close(fd);
1419     }
1420 
1421     ga_unset_frozen(ga_state);
1422     free_fs_mount_list(&mounts);
1423 
1424     execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
1425 
1426     return i;
1427 }
1428 
1429 static void guest_fsfreeze_cleanup(void)
1430 {
1431     Error *err = NULL;
1432 
1433     if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1434         qmp_guest_fsfreeze_thaw(&err);
1435         if (err) {
1436             slog("failed to clean up frozen filesystems: %s",
1437                  error_get_pretty(err));
1438             error_free(err);
1439         }
1440     }
1441 }
1442 #endif /* CONFIG_FSFREEZE */
1443 
1444 #if defined(CONFIG_FSTRIM)
1445 /*
1446  * Walk list of mounted file systems in the guest, and trim them.
1447  */
1448 GuestFilesystemTrimResponse *
1449 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1450 {
1451     GuestFilesystemTrimResponse *response;
1452     GuestFilesystemTrimResultList *list;
1453     GuestFilesystemTrimResult *result;
1454     int ret = 0;
1455     FsMountList mounts;
1456     struct FsMount *mount;
1457     int fd;
1458     Error *local_err = NULL;
1459     struct fstrim_range r;
1460 
1461     slog("guest-fstrim called");
1462 
1463     QTAILQ_INIT(&mounts);
1464     build_fs_mount_list(&mounts, &local_err);
1465     if (local_err) {
1466         error_propagate(errp, local_err);
1467         return NULL;
1468     }
1469 
1470     response = g_malloc0(sizeof(*response));
1471 
1472     QTAILQ_FOREACH(mount, &mounts, next) {
1473         result = g_malloc0(sizeof(*result));
1474         result->path = g_strdup(mount->dirname);
1475 
1476         list = g_malloc0(sizeof(*list));
1477         list->value = result;
1478         list->next = response->paths;
1479         response->paths = list;
1480 
1481         fd = qemu_open(mount->dirname, O_RDONLY);
1482         if (fd == -1) {
1483             result->error = g_strdup_printf("failed to open: %s",
1484                                             strerror(errno));
1485             result->has_error = true;
1486             continue;
1487         }
1488 
1489         /* We try to cull filesystems we know won't work in advance, but other
1490          * filesystems may not implement fstrim for less obvious reasons.
1491          * These will report EOPNOTSUPP; while in some other cases ENOTTY
1492          * will be reported (e.g. CD-ROMs).
1493          * Any other error means an unexpected error.
1494          */
1495         r.start = 0;
1496         r.len = -1;
1497         r.minlen = has_minimum ? minimum : 0;
1498         ret = ioctl(fd, FITRIM, &r);
1499         if (ret == -1) {
1500             result->has_error = true;
1501             if (errno == ENOTTY || errno == EOPNOTSUPP) {
1502                 result->error = g_strdup("trim not supported");
1503             } else {
1504                 result->error = g_strdup_printf("failed to trim: %s",
1505                                                 strerror(errno));
1506             }
1507             close(fd);
1508             continue;
1509         }
1510 
1511         result->has_minimum = true;
1512         result->minimum = r.minlen;
1513         result->has_trimmed = true;
1514         result->trimmed = r.len;
1515         close(fd);
1516     }
1517 
1518     free_fs_mount_list(&mounts);
1519     return response;
1520 }
1521 #endif /* CONFIG_FSTRIM */
1522 
1523 
1524 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1525 #define SUSPEND_SUPPORTED 0
1526 #define SUSPEND_NOT_SUPPORTED 1
1527 
1528 typedef enum {
1529     SUSPEND_MODE_DISK = 0,
1530     SUSPEND_MODE_RAM = 1,
1531     SUSPEND_MODE_HYBRID = 2,
1532 } SuspendMode;
1533 
1534 /*
1535  * Executes a command in a child process using g_spawn_sync,
1536  * returning an int >= 0 representing the exit status of the
1537  * process.
1538  *
1539  * If the program wasn't found in path, returns -1.
1540  *
1541  * If a problem happened when creating the child process,
1542  * returns -1 and errp is set.
1543  */
1544 static int run_process_child(const char *command[], Error **errp)
1545 {
1546     int exit_status, spawn_flag;
1547     GError *g_err = NULL;
1548     bool success;
1549 
1550     spawn_flag = G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL |
1551                  G_SPAWN_STDERR_TO_DEV_NULL;
1552 
1553     success =  g_spawn_sync(NULL, (char **)command, environ, spawn_flag,
1554                             NULL, NULL, NULL, NULL,
1555                             &exit_status, &g_err);
1556 
1557     if (success) {
1558         return WEXITSTATUS(exit_status);
1559     }
1560 
1561     if (g_err && (g_err->code != G_SPAWN_ERROR_NOENT)) {
1562         error_setg(errp, "failed to create child process, error '%s'",
1563                    g_err->message);
1564     }
1565 
1566     g_error_free(g_err);
1567     return -1;
1568 }
1569 
1570 static bool systemd_supports_mode(SuspendMode mode, Error **errp)
1571 {
1572     const char *systemctl_args[3] = {"systemd-hibernate", "systemd-suspend",
1573                                      "systemd-hybrid-sleep"};
1574     const char *cmd[4] = {"systemctl", "status", systemctl_args[mode], NULL};
1575     int status;
1576 
1577     status = run_process_child(cmd, errp);
1578 
1579     /*
1580      * systemctl status uses LSB return codes so we can expect
1581      * status > 0 and be ok. To assert if the guest has support
1582      * for the selected suspend mode, status should be < 4. 4 is
1583      * the code for unknown service status, the return value when
1584      * the service does not exist. A common value is status = 3
1585      * (program is not running).
1586      */
1587     if (status > 0 && status < 4) {
1588         return true;
1589     }
1590 
1591     return false;
1592 }
1593 
1594 static void systemd_suspend(SuspendMode mode, Error **errp)
1595 {
1596     Error *local_err = NULL;
1597     const char *systemctl_args[3] = {"hibernate", "suspend", "hybrid-sleep"};
1598     const char *cmd[3] = {"systemctl", systemctl_args[mode], NULL};
1599     int status;
1600 
1601     status = run_process_child(cmd, &local_err);
1602 
1603     if (status == 0) {
1604         return;
1605     }
1606 
1607     if ((status == -1) && !local_err) {
1608         error_setg(errp, "the helper program 'systemctl %s' was not found",
1609                    systemctl_args[mode]);
1610         return;
1611     }
1612 
1613     if (local_err) {
1614         error_propagate(errp, local_err);
1615     } else {
1616         error_setg(errp, "the helper program 'systemctl %s' returned an "
1617                    "unexpected exit status code (%d)",
1618                    systemctl_args[mode], status);
1619     }
1620 }
1621 
1622 static bool pmutils_supports_mode(SuspendMode mode, Error **errp)
1623 {
1624     Error *local_err = NULL;
1625     const char *pmutils_args[3] = {"--hibernate", "--suspend",
1626                                    "--suspend-hybrid"};
1627     const char *cmd[3] = {"pm-is-supported", pmutils_args[mode], NULL};
1628     int status;
1629 
1630     status = run_process_child(cmd, &local_err);
1631 
1632     if (status == SUSPEND_SUPPORTED) {
1633         return true;
1634     }
1635 
1636     if ((status == -1) && !local_err) {
1637         return false;
1638     }
1639 
1640     if (local_err) {
1641         error_propagate(errp, local_err);
1642     } else {
1643         error_setg(errp,
1644                    "the helper program '%s' returned an unexpected exit"
1645                    " status code (%d)", "pm-is-supported", status);
1646     }
1647 
1648     return false;
1649 }
1650 
1651 static void pmutils_suspend(SuspendMode mode, Error **errp)
1652 {
1653     Error *local_err = NULL;
1654     const char *pmutils_binaries[3] = {"pm-hibernate", "pm-suspend",
1655                                        "pm-suspend-hybrid"};
1656     const char *cmd[2] = {pmutils_binaries[mode], NULL};
1657     int status;
1658 
1659     status = run_process_child(cmd, &local_err);
1660 
1661     if (status == 0) {
1662         return;
1663     }
1664 
1665     if ((status == -1) && !local_err) {
1666         error_setg(errp, "the helper program '%s' was not found",
1667                    pmutils_binaries[mode]);
1668         return;
1669     }
1670 
1671     if (local_err) {
1672         error_propagate(errp, local_err);
1673     } else {
1674         error_setg(errp,
1675                    "the helper program '%s' returned an unexpected exit"
1676                    " status code (%d)", pmutils_binaries[mode], status);
1677     }
1678 }
1679 
1680 static bool linux_sys_state_supports_mode(SuspendMode mode, Error **errp)
1681 {
1682     const char *sysfile_strs[3] = {"disk", "mem", NULL};
1683     const char *sysfile_str = sysfile_strs[mode];
1684     char buf[32]; /* hopefully big enough */
1685     int fd;
1686     ssize_t ret;
1687 
1688     if (!sysfile_str) {
1689         error_setg(errp, "unknown guest suspend mode");
1690         return false;
1691     }
1692 
1693     fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
1694     if (fd < 0) {
1695         return false;
1696     }
1697 
1698     ret = read(fd, buf, sizeof(buf) - 1);
1699     close(fd);
1700     if (ret <= 0) {
1701         return false;
1702     }
1703     buf[ret] = '\0';
1704 
1705     if (strstr(buf, sysfile_str)) {
1706         return true;
1707     }
1708     return false;
1709 }
1710 
1711 static void linux_sys_state_suspend(SuspendMode mode, Error **errp)
1712 {
1713     Error *local_err = NULL;
1714     const char *sysfile_strs[3] = {"disk", "mem", NULL};
1715     const char *sysfile_str = sysfile_strs[mode];
1716     pid_t pid;
1717     int status;
1718 
1719     if (!sysfile_str) {
1720         error_setg(errp, "unknown guest suspend mode");
1721         return;
1722     }
1723 
1724     pid = fork();
1725     if (!pid) {
1726         /* child */
1727         int fd;
1728 
1729         setsid();
1730         reopen_fd_to_null(0);
1731         reopen_fd_to_null(1);
1732         reopen_fd_to_null(2);
1733 
1734         fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
1735         if (fd < 0) {
1736             _exit(EXIT_FAILURE);
1737         }
1738 
1739         if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
1740             _exit(EXIT_FAILURE);
1741         }
1742 
1743         _exit(EXIT_SUCCESS);
1744     } else if (pid < 0) {
1745         error_setg_errno(errp, errno, "failed to create child process");
1746         return;
1747     }
1748 
1749     ga_wait_child(pid, &status, &local_err);
1750     if (local_err) {
1751         error_propagate(errp, local_err);
1752         return;
1753     }
1754 
1755     if (WEXITSTATUS(status)) {
1756         error_setg(errp, "child process has failed to suspend");
1757     }
1758 
1759 }
1760 
1761 static void guest_suspend(SuspendMode mode, Error **errp)
1762 {
1763     Error *local_err = NULL;
1764     bool mode_supported = false;
1765 
1766     if (systemd_supports_mode(mode, &local_err)) {
1767         mode_supported = true;
1768         systemd_suspend(mode, &local_err);
1769     }
1770 
1771     if (!local_err) {
1772         return;
1773     }
1774 
1775     error_free(local_err);
1776     local_err = NULL;
1777 
1778     if (pmutils_supports_mode(mode, &local_err)) {
1779         mode_supported = true;
1780         pmutils_suspend(mode, &local_err);
1781     }
1782 
1783     if (!local_err) {
1784         return;
1785     }
1786 
1787     error_free(local_err);
1788     local_err = NULL;
1789 
1790     if (linux_sys_state_supports_mode(mode, &local_err)) {
1791         mode_supported = true;
1792         linux_sys_state_suspend(mode, &local_err);
1793     }
1794 
1795     if (!mode_supported) {
1796         error_free(local_err);
1797         error_setg(errp,
1798                    "the requested suspend mode is not supported by the guest");
1799     } else {
1800         error_propagate(errp, local_err);
1801     }
1802 }
1803 
1804 void qmp_guest_suspend_disk(Error **errp)
1805 {
1806     guest_suspend(SUSPEND_MODE_DISK, errp);
1807 }
1808 
1809 void qmp_guest_suspend_ram(Error **errp)
1810 {
1811     guest_suspend(SUSPEND_MODE_RAM, errp);
1812 }
1813 
1814 void qmp_guest_suspend_hybrid(Error **errp)
1815 {
1816     guest_suspend(SUSPEND_MODE_HYBRID, errp);
1817 }
1818 
1819 static GuestNetworkInterfaceList *
1820 guest_find_interface(GuestNetworkInterfaceList *head,
1821                      const char *name)
1822 {
1823     for (; head; head = head->next) {
1824         if (strcmp(head->value->name, name) == 0) {
1825             break;
1826         }
1827     }
1828 
1829     return head;
1830 }
1831 
1832 static int guest_get_network_stats(const char *name,
1833                        GuestNetworkInterfaceStat *stats)
1834 {
1835     int name_len;
1836     char const *devinfo = "/proc/net/dev";
1837     FILE *fp;
1838     char *line = NULL, *colon;
1839     size_t n = 0;
1840     fp = fopen(devinfo, "r");
1841     if (!fp) {
1842         return -1;
1843     }
1844     name_len = strlen(name);
1845     while (getline(&line, &n, fp) != -1) {
1846         long long dummy;
1847         long long rx_bytes;
1848         long long rx_packets;
1849         long long rx_errs;
1850         long long rx_dropped;
1851         long long tx_bytes;
1852         long long tx_packets;
1853         long long tx_errs;
1854         long long tx_dropped;
1855         char *trim_line;
1856         trim_line = g_strchug(line);
1857         if (trim_line[0] == '\0') {
1858             continue;
1859         }
1860         colon = strchr(trim_line, ':');
1861         if (!colon) {
1862             continue;
1863         }
1864         if (colon - name_len  == trim_line &&
1865            strncmp(trim_line, name, name_len) == 0) {
1866             if (sscanf(colon + 1,
1867                 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
1868                   &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
1869                   &dummy, &dummy, &dummy, &dummy,
1870                   &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
1871                   &dummy, &dummy, &dummy, &dummy) != 16) {
1872                 continue;
1873             }
1874             stats->rx_bytes = rx_bytes;
1875             stats->rx_packets = rx_packets;
1876             stats->rx_errs = rx_errs;
1877             stats->rx_dropped = rx_dropped;
1878             stats->tx_bytes = tx_bytes;
1879             stats->tx_packets = tx_packets;
1880             stats->tx_errs = tx_errs;
1881             stats->tx_dropped = tx_dropped;
1882             fclose(fp);
1883             g_free(line);
1884             return 0;
1885         }
1886     }
1887     fclose(fp);
1888     g_free(line);
1889     g_debug("/proc/net/dev: Interface '%s' not found", name);
1890     return -1;
1891 }
1892 
1893 /*
1894  * Build information about guest interfaces
1895  */
1896 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1897 {
1898     GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1899     struct ifaddrs *ifap, *ifa;
1900 
1901     if (getifaddrs(&ifap) < 0) {
1902         error_setg_errno(errp, errno, "getifaddrs failed");
1903         goto error;
1904     }
1905 
1906     for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1907         GuestNetworkInterfaceList *info;
1908         GuestIpAddressList **address_list = NULL, *address_item = NULL;
1909         GuestNetworkInterfaceStat  *interface_stat = NULL;
1910         char addr4[INET_ADDRSTRLEN];
1911         char addr6[INET6_ADDRSTRLEN];
1912         int sock;
1913         struct ifreq ifr;
1914         unsigned char *mac_addr;
1915         void *p;
1916 
1917         g_debug("Processing %s interface", ifa->ifa_name);
1918 
1919         info = guest_find_interface(head, ifa->ifa_name);
1920 
1921         if (!info) {
1922             info = g_malloc0(sizeof(*info));
1923             info->value = g_malloc0(sizeof(*info->value));
1924             info->value->name = g_strdup(ifa->ifa_name);
1925 
1926             if (!cur_item) {
1927                 head = cur_item = info;
1928             } else {
1929                 cur_item->next = info;
1930                 cur_item = info;
1931             }
1932         }
1933 
1934         if (!info->value->has_hardware_address &&
1935             ifa->ifa_flags & SIOCGIFHWADDR) {
1936             /* we haven't obtained HW address yet */
1937             sock = socket(PF_INET, SOCK_STREAM, 0);
1938             if (sock == -1) {
1939                 error_setg_errno(errp, errno, "failed to create socket");
1940                 goto error;
1941             }
1942 
1943             memset(&ifr, 0, sizeof(ifr));
1944             pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
1945             if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
1946                 error_setg_errno(errp, errno,
1947                                  "failed to get MAC address of %s",
1948                                  ifa->ifa_name);
1949                 close(sock);
1950                 goto error;
1951             }
1952 
1953             close(sock);
1954             mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
1955 
1956             info->value->hardware_address =
1957                 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1958                                 (int) mac_addr[0], (int) mac_addr[1],
1959                                 (int) mac_addr[2], (int) mac_addr[3],
1960                                 (int) mac_addr[4], (int) mac_addr[5]);
1961 
1962             info->value->has_hardware_address = true;
1963         }
1964 
1965         if (ifa->ifa_addr &&
1966             ifa->ifa_addr->sa_family == AF_INET) {
1967             /* interface with IPv4 address */
1968             p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1969             if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
1970                 error_setg_errno(errp, errno, "inet_ntop failed");
1971                 goto error;
1972             }
1973 
1974             address_item = g_malloc0(sizeof(*address_item));
1975             address_item->value = g_malloc0(sizeof(*address_item->value));
1976             address_item->value->ip_address = g_strdup(addr4);
1977             address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1978 
1979             if (ifa->ifa_netmask) {
1980                 /* Count the number of set bits in netmask.
1981                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
1982                 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
1983                 address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
1984             }
1985         } else if (ifa->ifa_addr &&
1986                    ifa->ifa_addr->sa_family == AF_INET6) {
1987             /* interface with IPv6 address */
1988             p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
1989             if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
1990                 error_setg_errno(errp, errno, "inet_ntop failed");
1991                 goto error;
1992             }
1993 
1994             address_item = g_malloc0(sizeof(*address_item));
1995             address_item->value = g_malloc0(sizeof(*address_item->value));
1996             address_item->value->ip_address = g_strdup(addr6);
1997             address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1998 
1999             if (ifa->ifa_netmask) {
2000                 /* Count the number of set bits in netmask.
2001                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
2002                 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
2003                 address_item->value->prefix =
2004                     ctpop32(((uint32_t *) p)[0]) +
2005                     ctpop32(((uint32_t *) p)[1]) +
2006                     ctpop32(((uint32_t *) p)[2]) +
2007                     ctpop32(((uint32_t *) p)[3]);
2008             }
2009         }
2010 
2011         if (!address_item) {
2012             continue;
2013         }
2014 
2015         address_list = &info->value->ip_addresses;
2016 
2017         while (*address_list && (*address_list)->next) {
2018             address_list = &(*address_list)->next;
2019         }
2020 
2021         if (!*address_list) {
2022             *address_list = address_item;
2023         } else {
2024             (*address_list)->next = address_item;
2025         }
2026 
2027         info->value->has_ip_addresses = true;
2028 
2029         if (!info->value->has_statistics) {
2030             interface_stat = g_malloc0(sizeof(*interface_stat));
2031             if (guest_get_network_stats(info->value->name,
2032                 interface_stat) == -1) {
2033                 info->value->has_statistics = false;
2034                 g_free(interface_stat);
2035             } else {
2036                 info->value->statistics = interface_stat;
2037                 info->value->has_statistics = true;
2038             }
2039         }
2040     }
2041 
2042     freeifaddrs(ifap);
2043     return head;
2044 
2045 error:
2046     freeifaddrs(ifap);
2047     qapi_free_GuestNetworkInterfaceList(head);
2048     return NULL;
2049 }
2050 
2051 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
2052 
2053 static long sysconf_exact(int name, const char *name_str, Error **errp)
2054 {
2055     long ret;
2056 
2057     errno = 0;
2058     ret = sysconf(name);
2059     if (ret == -1) {
2060         if (errno == 0) {
2061             error_setg(errp, "sysconf(%s): value indefinite", name_str);
2062         } else {
2063             error_setg_errno(errp, errno, "sysconf(%s)", name_str);
2064         }
2065     }
2066     return ret;
2067 }
2068 
2069 /* Transfer online/offline status between @vcpu and the guest system.
2070  *
2071  * On input either @errp or *@errp must be NULL.
2072  *
2073  * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2074  * - R: vcpu->logical_id
2075  * - W: vcpu->online
2076  * - W: vcpu->can_offline
2077  *
2078  * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2079  * - R: vcpu->logical_id
2080  * - R: vcpu->online
2081  *
2082  * Written members remain unmodified on error.
2083  */
2084 static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
2085                           char *dirpath, Error **errp)
2086 {
2087     int fd;
2088     int res;
2089     int dirfd;
2090     static const char fn[] = "online";
2091 
2092     dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2093     if (dirfd == -1) {
2094         error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2095         return;
2096     }
2097 
2098     fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
2099     if (fd == -1) {
2100         if (errno != ENOENT) {
2101             error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
2102         } else if (sys2vcpu) {
2103             vcpu->online = true;
2104             vcpu->can_offline = false;
2105         } else if (!vcpu->online) {
2106             error_setg(errp, "logical processor #%" PRId64 " can't be "
2107                        "offlined", vcpu->logical_id);
2108         } /* otherwise pretend successful re-onlining */
2109     } else {
2110         unsigned char status;
2111 
2112         res = pread(fd, &status, 1, 0);
2113         if (res == -1) {
2114             error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
2115         } else if (res == 0) {
2116             error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
2117                        fn);
2118         } else if (sys2vcpu) {
2119             vcpu->online = (status != '0');
2120             vcpu->can_offline = true;
2121         } else if (vcpu->online != (status != '0')) {
2122             status = '0' + vcpu->online;
2123             if (pwrite(fd, &status, 1, 0) == -1) {
2124                 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
2125                                  fn);
2126             }
2127         } /* otherwise pretend successful re-(on|off)-lining */
2128 
2129         res = close(fd);
2130         g_assert(res == 0);
2131     }
2132 
2133     res = close(dirfd);
2134     g_assert(res == 0);
2135 }
2136 
2137 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2138 {
2139     int64_t current;
2140     GuestLogicalProcessorList *head, **link;
2141     long sc_max;
2142     Error *local_err = NULL;
2143 
2144     current = 0;
2145     head = NULL;
2146     link = &head;
2147     sc_max = SYSCONF_EXACT(_SC_NPROCESSORS_CONF, &local_err);
2148 
2149     while (local_err == NULL && current < sc_max) {
2150         GuestLogicalProcessor *vcpu;
2151         GuestLogicalProcessorList *entry;
2152         int64_t id = current++;
2153         char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
2154                                      id);
2155 
2156         if (g_file_test(path, G_FILE_TEST_EXISTS)) {
2157             vcpu = g_malloc0(sizeof *vcpu);
2158             vcpu->logical_id = id;
2159             vcpu->has_can_offline = true; /* lolspeak ftw */
2160             transfer_vcpu(vcpu, true, path, &local_err);
2161             entry = g_malloc0(sizeof *entry);
2162             entry->value = vcpu;
2163             *link = entry;
2164             link = &entry->next;
2165         }
2166         g_free(path);
2167     }
2168 
2169     if (local_err == NULL) {
2170         /* there's no guest with zero VCPUs */
2171         g_assert(head != NULL);
2172         return head;
2173     }
2174 
2175     qapi_free_GuestLogicalProcessorList(head);
2176     error_propagate(errp, local_err);
2177     return NULL;
2178 }
2179 
2180 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2181 {
2182     int64_t processed;
2183     Error *local_err = NULL;
2184 
2185     processed = 0;
2186     while (vcpus != NULL) {
2187         char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
2188                                      vcpus->value->logical_id);
2189 
2190         transfer_vcpu(vcpus->value, false, path, &local_err);
2191         g_free(path);
2192         if (local_err != NULL) {
2193             break;
2194         }
2195         ++processed;
2196         vcpus = vcpus->next;
2197     }
2198 
2199     if (local_err != NULL) {
2200         if (processed == 0) {
2201             error_propagate(errp, local_err);
2202         } else {
2203             error_free(local_err);
2204         }
2205     }
2206 
2207     return processed;
2208 }
2209 
2210 void qmp_guest_set_user_password(const char *username,
2211                                  const char *password,
2212                                  bool crypted,
2213                                  Error **errp)
2214 {
2215     Error *local_err = NULL;
2216     char *passwd_path = NULL;
2217     pid_t pid;
2218     int status;
2219     int datafd[2] = { -1, -1 };
2220     char *rawpasswddata = NULL;
2221     size_t rawpasswdlen;
2222     char *chpasswddata = NULL;
2223     size_t chpasswdlen;
2224 
2225     rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
2226     if (!rawpasswddata) {
2227         return;
2228     }
2229     rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
2230     rawpasswddata[rawpasswdlen] = '\0';
2231 
2232     if (strchr(rawpasswddata, '\n')) {
2233         error_setg(errp, "forbidden characters in raw password");
2234         goto out;
2235     }
2236 
2237     if (strchr(username, '\n') ||
2238         strchr(username, ':')) {
2239         error_setg(errp, "forbidden characters in username");
2240         goto out;
2241     }
2242 
2243     chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
2244     chpasswdlen = strlen(chpasswddata);
2245 
2246     passwd_path = g_find_program_in_path("chpasswd");
2247 
2248     if (!passwd_path) {
2249         error_setg(errp, "cannot find 'passwd' program in PATH");
2250         goto out;
2251     }
2252 
2253     if (pipe(datafd) < 0) {
2254         error_setg(errp, "cannot create pipe FDs");
2255         goto out;
2256     }
2257 
2258     pid = fork();
2259     if (pid == 0) {
2260         close(datafd[1]);
2261         /* child */
2262         setsid();
2263         dup2(datafd[0], 0);
2264         reopen_fd_to_null(1);
2265         reopen_fd_to_null(2);
2266 
2267         if (crypted) {
2268             execle(passwd_path, "chpasswd", "-e", NULL, environ);
2269         } else {
2270             execle(passwd_path, "chpasswd", NULL, environ);
2271         }
2272         _exit(EXIT_FAILURE);
2273     } else if (pid < 0) {
2274         error_setg_errno(errp, errno, "failed to create child process");
2275         goto out;
2276     }
2277     close(datafd[0]);
2278     datafd[0] = -1;
2279 
2280     if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
2281         error_setg_errno(errp, errno, "cannot write new account password");
2282         goto out;
2283     }
2284     close(datafd[1]);
2285     datafd[1] = -1;
2286 
2287     ga_wait_child(pid, &status, &local_err);
2288     if (local_err) {
2289         error_propagate(errp, local_err);
2290         goto out;
2291     }
2292 
2293     if (!WIFEXITED(status)) {
2294         error_setg(errp, "child process has terminated abnormally");
2295         goto out;
2296     }
2297 
2298     if (WEXITSTATUS(status)) {
2299         error_setg(errp, "child process has failed to set user password");
2300         goto out;
2301     }
2302 
2303 out:
2304     g_free(chpasswddata);
2305     g_free(rawpasswddata);
2306     g_free(passwd_path);
2307     if (datafd[0] != -1) {
2308         close(datafd[0]);
2309     }
2310     if (datafd[1] != -1) {
2311         close(datafd[1]);
2312     }
2313 }
2314 
2315 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2316                                int size, Error **errp)
2317 {
2318     int fd;
2319     int res;
2320 
2321     errno = 0;
2322     fd = openat(dirfd, pathname, O_RDONLY);
2323     if (fd == -1) {
2324         error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2325         return;
2326     }
2327 
2328     res = pread(fd, buf, size, 0);
2329     if (res == -1) {
2330         error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2331     } else if (res == 0) {
2332         error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2333     }
2334     close(fd);
2335 }
2336 
2337 static void ga_write_sysfs_file(int dirfd, const char *pathname,
2338                                 const char *buf, int size, Error **errp)
2339 {
2340     int fd;
2341 
2342     errno = 0;
2343     fd = openat(dirfd, pathname, O_WRONLY);
2344     if (fd == -1) {
2345         error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2346         return;
2347     }
2348 
2349     if (pwrite(fd, buf, size, 0) == -1) {
2350         error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2351     }
2352 
2353     close(fd);
2354 }
2355 
2356 /* Transfer online/offline status between @mem_blk and the guest system.
2357  *
2358  * On input either @errp or *@errp must be NULL.
2359  *
2360  * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2361  * - R: mem_blk->phys_index
2362  * - W: mem_blk->online
2363  * - W: mem_blk->can_offline
2364  *
2365  * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2366  * - R: mem_blk->phys_index
2367  * - R: mem_blk->online
2368  *-  R: mem_blk->can_offline
2369  * Written members remain unmodified on error.
2370  */
2371 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2372                                   GuestMemoryBlockResponse *result,
2373                                   Error **errp)
2374 {
2375     char *dirpath;
2376     int dirfd;
2377     char *status;
2378     Error *local_err = NULL;
2379 
2380     if (!sys2memblk) {
2381         DIR *dp;
2382 
2383         if (!result) {
2384             error_setg(errp, "Internal error, 'result' should not be NULL");
2385             return;
2386         }
2387         errno = 0;
2388         dp = opendir("/sys/devices/system/memory/");
2389          /* if there is no 'memory' directory in sysfs,
2390          * we think this VM does not support online/offline memory block,
2391          * any other solution?
2392          */
2393         if (!dp) {
2394             if (errno == ENOENT) {
2395                 result->response =
2396                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2397             }
2398             goto out1;
2399         }
2400         closedir(dp);
2401     }
2402 
2403     dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2404                               mem_blk->phys_index);
2405     dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2406     if (dirfd == -1) {
2407         if (sys2memblk) {
2408             error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2409         } else {
2410             if (errno == ENOENT) {
2411                 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2412             } else {
2413                 result->response =
2414                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2415             }
2416         }
2417         g_free(dirpath);
2418         goto out1;
2419     }
2420     g_free(dirpath);
2421 
2422     status = g_malloc0(10);
2423     ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2424     if (local_err) {
2425         /* treat with sysfs file that not exist in old kernel */
2426         if (errno == ENOENT) {
2427             error_free(local_err);
2428             if (sys2memblk) {
2429                 mem_blk->online = true;
2430                 mem_blk->can_offline = false;
2431             } else if (!mem_blk->online) {
2432                 result->response =
2433                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2434             }
2435         } else {
2436             if (sys2memblk) {
2437                 error_propagate(errp, local_err);
2438             } else {
2439                 error_free(local_err);
2440                 result->response =
2441                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2442             }
2443         }
2444         goto out2;
2445     }
2446 
2447     if (sys2memblk) {
2448         char removable = '0';
2449 
2450         mem_blk->online = (strncmp(status, "online", 6) == 0);
2451 
2452         ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2453         if (local_err) {
2454             /* if no 'removable' file, it doesn't support offline mem blk */
2455             if (errno == ENOENT) {
2456                 error_free(local_err);
2457                 mem_blk->can_offline = false;
2458             } else {
2459                 error_propagate(errp, local_err);
2460             }
2461         } else {
2462             mem_blk->can_offline = (removable != '0');
2463         }
2464     } else {
2465         if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2466             const char *new_state = mem_blk->online ? "online" : "offline";
2467 
2468             ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2469                                 &local_err);
2470             if (local_err) {
2471                 error_free(local_err);
2472                 result->response =
2473                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2474                 goto out2;
2475             }
2476 
2477             result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2478             result->has_error_code = false;
2479         } /* otherwise pretend successful re-(on|off)-lining */
2480     }
2481     g_free(status);
2482     close(dirfd);
2483     return;
2484 
2485 out2:
2486     g_free(status);
2487     close(dirfd);
2488 out1:
2489     if (!sys2memblk) {
2490         result->has_error_code = true;
2491         result->error_code = errno;
2492     }
2493 }
2494 
2495 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2496 {
2497     GuestMemoryBlockList *head, **link;
2498     Error *local_err = NULL;
2499     struct dirent *de;
2500     DIR *dp;
2501 
2502     head = NULL;
2503     link = &head;
2504 
2505     dp = opendir("/sys/devices/system/memory/");
2506     if (!dp) {
2507         /* it's ok if this happens to be a system that doesn't expose
2508          * memory blocks via sysfs, but otherwise we should report
2509          * an error
2510          */
2511         if (errno != ENOENT) {
2512             error_setg_errno(errp, errno, "Can't open directory"
2513                              "\"/sys/devices/system/memory/\"");
2514         }
2515         return NULL;
2516     }
2517 
2518     /* Note: the phys_index of memory block may be discontinuous,
2519      * this is because a memblk is the unit of the Sparse Memory design, which
2520      * allows discontinuous memory ranges (ex. NUMA), so here we should
2521      * traverse the memory block directory.
2522      */
2523     while ((de = readdir(dp)) != NULL) {
2524         GuestMemoryBlock *mem_blk;
2525         GuestMemoryBlockList *entry;
2526 
2527         if ((strncmp(de->d_name, "memory", 6) != 0) ||
2528             !(de->d_type & DT_DIR)) {
2529             continue;
2530         }
2531 
2532         mem_blk = g_malloc0(sizeof *mem_blk);
2533         /* The d_name is "memoryXXX",  phys_index is block id, same as XXX */
2534         mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2535         mem_blk->has_can_offline = true; /* lolspeak ftw */
2536         transfer_memory_block(mem_blk, true, NULL, &local_err);
2537         if (local_err) {
2538             break;
2539         }
2540 
2541         entry = g_malloc0(sizeof *entry);
2542         entry->value = mem_blk;
2543 
2544         *link = entry;
2545         link = &entry->next;
2546     }
2547 
2548     closedir(dp);
2549     if (local_err == NULL) {
2550         /* there's no guest with zero memory blocks */
2551         if (head == NULL) {
2552             error_setg(errp, "guest reported zero memory blocks!");
2553         }
2554         return head;
2555     }
2556 
2557     qapi_free_GuestMemoryBlockList(head);
2558     error_propagate(errp, local_err);
2559     return NULL;
2560 }
2561 
2562 GuestMemoryBlockResponseList *
2563 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2564 {
2565     GuestMemoryBlockResponseList *head, **link;
2566     Error *local_err = NULL;
2567 
2568     head = NULL;
2569     link = &head;
2570 
2571     while (mem_blks != NULL) {
2572         GuestMemoryBlockResponse *result;
2573         GuestMemoryBlockResponseList *entry;
2574         GuestMemoryBlock *current_mem_blk = mem_blks->value;
2575 
2576         result = g_malloc0(sizeof(*result));
2577         result->phys_index = current_mem_blk->phys_index;
2578         transfer_memory_block(current_mem_blk, false, result, &local_err);
2579         if (local_err) { /* should never happen */
2580             goto err;
2581         }
2582         entry = g_malloc0(sizeof *entry);
2583         entry->value = result;
2584 
2585         *link = entry;
2586         link = &entry->next;
2587         mem_blks = mem_blks->next;
2588     }
2589 
2590     return head;
2591 err:
2592     qapi_free_GuestMemoryBlockResponseList(head);
2593     error_propagate(errp, local_err);
2594     return NULL;
2595 }
2596 
2597 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2598 {
2599     Error *local_err = NULL;
2600     char *dirpath;
2601     int dirfd;
2602     char *buf;
2603     GuestMemoryBlockInfo *info;
2604 
2605     dirpath = g_strdup_printf("/sys/devices/system/memory/");
2606     dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2607     if (dirfd == -1) {
2608         error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2609         g_free(dirpath);
2610         return NULL;
2611     }
2612     g_free(dirpath);
2613 
2614     buf = g_malloc0(20);
2615     ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
2616     close(dirfd);
2617     if (local_err) {
2618         g_free(buf);
2619         error_propagate(errp, local_err);
2620         return NULL;
2621     }
2622 
2623     info = g_new0(GuestMemoryBlockInfo, 1);
2624     info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2625 
2626     g_free(buf);
2627 
2628     return info;
2629 }
2630 
2631 #else /* defined(__linux__) */
2632 
2633 void qmp_guest_suspend_disk(Error **errp)
2634 {
2635     error_setg(errp, QERR_UNSUPPORTED);
2636 }
2637 
2638 void qmp_guest_suspend_ram(Error **errp)
2639 {
2640     error_setg(errp, QERR_UNSUPPORTED);
2641 }
2642 
2643 void qmp_guest_suspend_hybrid(Error **errp)
2644 {
2645     error_setg(errp, QERR_UNSUPPORTED);
2646 }
2647 
2648 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2649 {
2650     error_setg(errp, QERR_UNSUPPORTED);
2651     return NULL;
2652 }
2653 
2654 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2655 {
2656     error_setg(errp, QERR_UNSUPPORTED);
2657     return NULL;
2658 }
2659 
2660 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2661 {
2662     error_setg(errp, QERR_UNSUPPORTED);
2663     return -1;
2664 }
2665 
2666 void qmp_guest_set_user_password(const char *username,
2667                                  const char *password,
2668                                  bool crypted,
2669                                  Error **errp)
2670 {
2671     error_setg(errp, QERR_UNSUPPORTED);
2672 }
2673 
2674 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2675 {
2676     error_setg(errp, QERR_UNSUPPORTED);
2677     return NULL;
2678 }
2679 
2680 GuestMemoryBlockResponseList *
2681 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2682 {
2683     error_setg(errp, QERR_UNSUPPORTED);
2684     return NULL;
2685 }
2686 
2687 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2688 {
2689     error_setg(errp, QERR_UNSUPPORTED);
2690     return NULL;
2691 }
2692 
2693 #endif
2694 
2695 #if !defined(CONFIG_FSFREEZE)
2696 
2697 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
2698 {
2699     error_setg(errp, QERR_UNSUPPORTED);
2700     return NULL;
2701 }
2702 
2703 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
2704 {
2705     error_setg(errp, QERR_UNSUPPORTED);
2706 
2707     return 0;
2708 }
2709 
2710 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
2711 {
2712     error_setg(errp, QERR_UNSUPPORTED);
2713 
2714     return 0;
2715 }
2716 
2717 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
2718                                        strList *mountpoints,
2719                                        Error **errp)
2720 {
2721     error_setg(errp, QERR_UNSUPPORTED);
2722 
2723     return 0;
2724 }
2725 
2726 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
2727 {
2728     error_setg(errp, QERR_UNSUPPORTED);
2729 
2730     return 0;
2731 }
2732 #endif /* CONFIG_FSFREEZE */
2733 
2734 #if !defined(CONFIG_FSTRIM)
2735 GuestFilesystemTrimResponse *
2736 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
2737 {
2738     error_setg(errp, QERR_UNSUPPORTED);
2739     return NULL;
2740 }
2741 #endif
2742 
2743 /* add unsupported commands to the blacklist */
2744 GList *ga_command_blacklist_init(GList *blacklist)
2745 {
2746 #if !defined(__linux__)
2747     {
2748         const char *list[] = {
2749             "guest-suspend-disk", "guest-suspend-ram",
2750             "guest-suspend-hybrid", "guest-network-get-interfaces",
2751             "guest-get-vcpus", "guest-set-vcpus",
2752             "guest-get-memory-blocks", "guest-set-memory-blocks",
2753             "guest-get-memory-block-size", "guest-get-memory-block-info",
2754             NULL};
2755         char **p = (char **)list;
2756 
2757         while (*p) {
2758             blacklist = g_list_append(blacklist, g_strdup(*p++));
2759         }
2760     }
2761 #endif
2762 
2763 #if !defined(CONFIG_FSFREEZE)
2764     {
2765         const char *list[] = {
2766             "guest-get-fsinfo", "guest-fsfreeze-status",
2767             "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2768             "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL};
2769         char **p = (char **)list;
2770 
2771         while (*p) {
2772             blacklist = g_list_append(blacklist, g_strdup(*p++));
2773         }
2774     }
2775 #endif
2776 
2777 #if !defined(CONFIG_FSTRIM)
2778     blacklist = g_list_append(blacklist, g_strdup("guest-fstrim"));
2779 #endif
2780 
2781     return blacklist;
2782 }
2783 
2784 /* register init/cleanup routines for stateful command groups */
2785 void ga_command_state_init(GAState *s, GACommandState *cs)
2786 {
2787 #if defined(CONFIG_FSFREEZE)
2788     ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
2789 #endif
2790 }
2791 
2792 #ifdef HAVE_UTMPX
2793 
2794 #define QGA_MICRO_SECOND_TO_SECOND 1000000
2795 
2796 static double ga_get_login_time(struct utmpx *user_info)
2797 {
2798     double seconds = (double)user_info->ut_tv.tv_sec;
2799     double useconds = (double)user_info->ut_tv.tv_usec;
2800     useconds /= QGA_MICRO_SECOND_TO_SECOND;
2801     return seconds + useconds;
2802 }
2803 
2804 GuestUserList *qmp_guest_get_users(Error **errp)
2805 {
2806     GHashTable *cache = NULL;
2807     GuestUserList *head = NULL, *cur_item = NULL;
2808     struct utmpx *user_info = NULL;
2809     gpointer value = NULL;
2810     GuestUser *user = NULL;
2811     GuestUserList *item = NULL;
2812     double login_time = 0;
2813 
2814     cache = g_hash_table_new(g_str_hash, g_str_equal);
2815     setutxent();
2816 
2817     for (;;) {
2818         user_info = getutxent();
2819         if (user_info == NULL) {
2820             break;
2821         } else if (user_info->ut_type != USER_PROCESS) {
2822             continue;
2823         } else if (g_hash_table_contains(cache, user_info->ut_user)) {
2824             value = g_hash_table_lookup(cache, user_info->ut_user);
2825             user = (GuestUser *)value;
2826             login_time = ga_get_login_time(user_info);
2827             /* We're ensuring the earliest login time to be sent */
2828             if (login_time < user->login_time) {
2829                 user->login_time = login_time;
2830             }
2831             continue;
2832         }
2833 
2834         item = g_new0(GuestUserList, 1);
2835         item->value = g_new0(GuestUser, 1);
2836         item->value->user = g_strdup(user_info->ut_user);
2837         item->value->login_time = ga_get_login_time(user_info);
2838 
2839         g_hash_table_insert(cache, item->value->user, item->value);
2840 
2841         if (!cur_item) {
2842             head = cur_item = item;
2843         } else {
2844             cur_item->next = item;
2845             cur_item = item;
2846         }
2847     }
2848     endutxent();
2849     g_hash_table_destroy(cache);
2850     return head;
2851 }
2852 
2853 #else
2854 
2855 GuestUserList *qmp_guest_get_users(Error **errp)
2856 {
2857     error_setg(errp, QERR_UNSUPPORTED);
2858     return NULL;
2859 }
2860 
2861 #endif
2862 
2863 /* Replace escaped special characters with theire real values. The replacement
2864  * is done in place -- returned value is in the original string.
2865  */
2866 static void ga_osrelease_replace_special(gchar *value)
2867 {
2868     gchar *p, *p2, quote;
2869 
2870     /* Trim the string at first space or semicolon if it is not enclosed in
2871      * single or double quotes. */
2872     if ((value[0] != '"') || (value[0] == '\'')) {
2873         p = strchr(value, ' ');
2874         if (p != NULL) {
2875             *p = 0;
2876         }
2877         p = strchr(value, ';');
2878         if (p != NULL) {
2879             *p = 0;
2880         }
2881         return;
2882     }
2883 
2884     quote = value[0];
2885     p2 = value;
2886     p = value + 1;
2887     while (*p != 0) {
2888         if (*p == '\\') {
2889             p++;
2890             switch (*p) {
2891             case '$':
2892             case '\'':
2893             case '"':
2894             case '\\':
2895             case '`':
2896                 break;
2897             default:
2898                 /* Keep literal backslash followed by whatever is there */
2899                 p--;
2900                 break;
2901             }
2902         } else if (*p == quote) {
2903             *p2 = 0;
2904             break;
2905         }
2906         *(p2++) = *(p++);
2907     }
2908 }
2909 
2910 static GKeyFile *ga_parse_osrelease(const char *fname)
2911 {
2912     gchar *content = NULL;
2913     gchar *content2 = NULL;
2914     GError *err = NULL;
2915     GKeyFile *keys = g_key_file_new();
2916     const char *group = "[os-release]\n";
2917 
2918     if (!g_file_get_contents(fname, &content, NULL, &err)) {
2919         slog("failed to read '%s', error: %s", fname, err->message);
2920         goto fail;
2921     }
2922 
2923     if (!g_utf8_validate(content, -1, NULL)) {
2924         slog("file is not utf-8 encoded: %s", fname);
2925         goto fail;
2926     }
2927     content2 = g_strdup_printf("%s%s", group, content);
2928 
2929     if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
2930                                    &err)) {
2931         slog("failed to parse file '%s', error: %s", fname, err->message);
2932         goto fail;
2933     }
2934 
2935     g_free(content);
2936     g_free(content2);
2937     return keys;
2938 
2939 fail:
2940     g_error_free(err);
2941     g_free(content);
2942     g_free(content2);
2943     g_key_file_free(keys);
2944     return NULL;
2945 }
2946 
2947 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
2948 {
2949     GuestOSInfo *info = NULL;
2950     struct utsname kinfo;
2951     GKeyFile *osrelease = NULL;
2952     const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
2953 
2954     info = g_new0(GuestOSInfo, 1);
2955 
2956     if (uname(&kinfo) != 0) {
2957         error_setg_errno(errp, errno, "uname failed");
2958     } else {
2959         info->has_kernel_version = true;
2960         info->kernel_version = g_strdup(kinfo.version);
2961         info->has_kernel_release = true;
2962         info->kernel_release = g_strdup(kinfo.release);
2963         info->has_machine = true;
2964         info->machine = g_strdup(kinfo.machine);
2965     }
2966 
2967     if (qga_os_release != NULL) {
2968         osrelease = ga_parse_osrelease(qga_os_release);
2969     } else {
2970         osrelease = ga_parse_osrelease("/etc/os-release");
2971         if (osrelease == NULL) {
2972             osrelease = ga_parse_osrelease("/usr/lib/os-release");
2973         }
2974     }
2975 
2976     if (osrelease != NULL) {
2977         char *value;
2978 
2979 #define GET_FIELD(field, osfield) do { \
2980     value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
2981     if (value != NULL) { \
2982         ga_osrelease_replace_special(value); \
2983         info->has_ ## field = true; \
2984         info->field = value; \
2985     } \
2986 } while (0)
2987         GET_FIELD(id, "ID");
2988         GET_FIELD(name, "NAME");
2989         GET_FIELD(pretty_name, "PRETTY_NAME");
2990         GET_FIELD(version, "VERSION");
2991         GET_FIELD(version_id, "VERSION_ID");
2992         GET_FIELD(variant, "VARIANT");
2993         GET_FIELD(variant_id, "VARIANT_ID");
2994 #undef GET_FIELD
2995 
2996         g_key_file_free(osrelease);
2997     }
2998 
2999     return info;
3000 }
3001