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